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 |
|---|---|---|---|---|---|
67,347,194 | The thing is , that I am given some code and it is structured this way that we expect some accesses to not - initialised elements in the list. (I don't want to change the logic behind it, because it deals with some math concepts ). But I've been given the code in some other language and I want to do the same with pytho... | 2021/05/01 | [
"https://Stackoverflow.com/questions/67347194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14386149/"
] | you can handle it with:
```
except IndexError:
pass
```
full code:
```
a = []
for i in range(1, 10, 2): a.append(i)
for j in range(10):
try:
a[i] += 1
except IndexError:
pass
finally:
a.append(1)
``` | ```
a = []
for i in range(1,10,2):
a.append(i)
try:
for j in range(10):
a[i] +=1
except:
pass
finally:
a.append(1)
print(a)
``` |
59,414,043 | Below is my project structure:
```
- MyProject
- src
- Master.py
- Myfolder
- file1
- Myfolder2
- file2
```
when i tried to run `python3 Master.py` from `src` folder i get
```
ModuleNotFoundError: No Module name 'src'
```
when i tried to run Master.py from root using this command ... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59414043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984616/"
] | Given the updated directory structure, you should add an `__init__.py` file to `myfolder` with the following line:
```py
from .file1 import * # or
# from .file1 import something # or
# from . import file1
```
and then in `master.py` do
```py
import myfolder # or
# from myfolder import file1 # or
# from myfolder.f... | While my solution worked with what was suggested by Maxim i also learned that with the help of simple `os.chdir(os.path.dirname('/usr/dirname'))` i was able to resolve the issue and i also did not have to add `__init__.py` anywhere in the package |
32,140,380 | I'm looking for a pythonic (1-line) way to extract a range of values from an array
Here's some sample code that will extract the array elements that are >2 and <8 from x,y data, and put them into a new array. Is there a way to accomplish this on a single line? The code below works but seems kludgier than it needs to be... | 2015/08/21 | [
"https://Stackoverflow.com/questions/32140380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4618362/"
] | You can chain together boolean arrays using `&` for element-wise `logical and` and `|` for element-wise `logical or`, so that the condition `2 < x0` and `x0 < 8` becomes
```
mask = (2 < x0) & (x0 < 8)
```
---
For example,
```
import numpy as np
x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
mask =... | ```
import numpy as np
x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
list( zip( *[(x,y) for x, y in zip(x0, y0) if 1<=x<=3 or 7<=x<=9] ) )
# [(3, 9, 8, 3), (3, 5, 7, 8)]
``` |
64,995,258 | I started learning python few days ago and im looking to create a simple program that creates conclusion text that shows what have i bought and how much have i paid depended on my inputs. So far i have created the program and technically it works well. But im having a problem with specifying the parts in text that migh... | 2020/11/24 | [
"https://Stackoverflow.com/questions/64995258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14702072/"
] | * Give each group a consecutive range. For example, for 15%, the range will be between 30 and 45.
* Pick a random number between 0 and 100.
* Find in which range that random number falls:
```sql
create or replace temp table probs
as
select 'a' id, 1 value, 20 prob
union all select 'a', 2, 30
union all select 'a', 3,... | Felipe's answer is great, it definitely solved the problem.
While trying out different approaches yesterday, I tested out this approach on Felipe's table and it seems to be working as well.
I'm giving each record a random probability and comparing against the actual probability. The idea is that if the random probabi... |
60,482,258 | How can i replace a string in list of lists in python but i want to apply the changes only to the specific index and not affecting the other index, here some example:
```
mylist = [["test_one", "test_two"], ["test_one", "test_two"]]
```
i want to change the word "test" to "my" so the result would be only affecting t... | 2020/03/02 | [
"https://Stackoverflow.com/questions/60482258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9675410/"
] | Use indexing:
```
newlist = []
for l in mylist:
l[1] = l[1].replace("test", "my")
newlist.append(l)
print(newlist)
```
Or oneliner if you always have two elements in the sublist:
```
newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)
```
Output:
```
[['test_one', 'my_two'], ['test... | There is a way to do this on one line but it is not coming to me at the moment. Here is how to do it in two lines.
```
for two_word_list in mylist:
two_word_list[1] = two_word_list.replace("test", "my")
``` |
53,048,002 | I have a semicolon separated csv file which has the following form:
```
indx1; string1; char1; entry1
indx2; string1; char2; entry2
indx3; string2; char2; entry3
indx4; string1; char1; entry4
indx5; string3; char2; entry5
```
I want to get unique entries of the 1st and 2nd columns of this file in the form of a ... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53048002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10415983/"
] | You could use [sets](https://docs.python.org/2.7/library/stdtypes.html#set) to keep track of the already seen values in the needed columns. Since you say that the order doesn't matter, you could just convert the sets to lists after processing all rows:
```
import csv
col1, col2 = set(), set()
with open('data.csv') a... | This should work. You can use it as benchmark.
```
myDict1 = {}
myDict2 = {}
with open('data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
for row in csv_reader:
myDict1[row[1]] = 0
myDict2[row[2]] = 0
x = myDict1.keys()
y = myDict2.keys()
``` |
10,631,419 | My django app saves django models to a remote database. Sometimes the saves are bursty. In order to free the main thread (\*thread\_A\*) of the application from the time toll of saving multiple objects to the database, I thought of transferring the model objects to a separate thread (\*thread\_B\*) using [`collections.... | 2012/05/17 | [
"https://Stackoverflow.com/questions/10631419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | Django's `save()` does nothing special to the GIL. In fact, there is hardly anything you can do with the GIL in Python code -- when it is executed, the thread must hold the GIL.
There are only two ways the GIL could get released in `save()`:
* Python decides to switch threads (after [`sys.getcheckinterval()`](http://... | I think python dont lock anything by itself, but database does. |
10,631,419 | My django app saves django models to a remote database. Sometimes the saves are bursty. In order to free the main thread (\*thread\_A\*) of the application from the time toll of saving multiple objects to the database, I thought of transferring the model objects to a separate thread (\*thread\_B\*) using [`collections.... | 2012/05/17 | [
"https://Stackoverflow.com/questions/10631419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | Generally you should never have to worry about threads in a Django application. If you're serving your application with Apache, gunicorn or nearly any other server other than the development server, the server will spawn multiple processes and evade the GIL entirely. The exception is if you're using gunicorn with geven... | I think python dont lock anything by itself, but database does. |
10,631,419 | My django app saves django models to a remote database. Sometimes the saves are bursty. In order to free the main thread (\*thread\_A\*) of the application from the time toll of saving multiple objects to the database, I thought of transferring the model objects to a separate thread (\*thread\_B\*) using [`collections.... | 2012/05/17 | [
"https://Stackoverflow.com/questions/10631419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | Django's `save()` does nothing special to the GIL. In fact, there is hardly anything you can do with the GIL in Python code -- when it is executed, the thread must hold the GIL.
There are only two ways the GIL could get released in `save()`:
* Python decides to switch threads (after [`sys.getcheckinterval()`](http://... | Generally you should never have to worry about threads in a Django application. If you're serving your application with Apache, gunicorn or nearly any other server other than the development server, the server will spawn multiple processes and evade the GIL entirely. The exception is if you're using gunicorn with geven... |
68,006,937 | I am trying to make a daily line graph for certain stocks, but am running into an issue. Getting the 'Close' price every 2 minutes functions correctly, but when I try and get 'Datetime' I am getting an error. I believe yfinance used pandas to create a dataframe, but I may be wrong. Regardless, I am having issues pullin... | 2021/06/16 | [
"https://Stackoverflow.com/questions/68006937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16245213/"
] | Datetime is no column name, it just looks like one:
[](https://i.stack.imgur.com/gK5iQ.png)
Try
`print(stock.history(period='1d',interval='2m).keys())`
and you will see. | The Datetime column is the index of the dataframe. If you reset the index you can do whatever with the ['Datetime'] column. |
41,761,293 | I am trying to access the worklogs in python by using the [jira python library](http://jira.readthedocs.io/en/latest/examples.html). I am doing the following:
```
issues = jira.search_issues("key=MYTICKET-1")
print(issues[0].fields.worklogs)
issue = jira.search_issues("MYTICKET-1")
print(issue.fields.worklogs)
```
... | 2017/01/20 | [
"https://Stackoverflow.com/questions/41761293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581090/"
] | This is because **it seems** `jira.JIRA.search_issues` doesn't fetch all "builtin" fields, like `worklog`, by default (although documentation only uses vague term ["fields - [...] Default is to include *all fields*"](https://jira.readthedocs.io/en/master/api.html?highlight=worklogs#jira.JIRA.search_issues)
- "all" ou... | This question [here](https://stackoverflow.com/questions/24375473/access-specific-information-within-worklogs-in-jira-python) is similar to yours and someone has posted a work around.
There is a also a [similar question on Github](https://github.com/pycontribs/jira/issues/224) in relation to attachments (not worklogs... |
48,244,805 | I need to execute a function named "send()" who contain an ajax request.
This function is in ajax.js (included in )
The Ajax success update the src of my image.
This function work well, I don't think that it is the problem
But when I load the page, send() function is not executed :o I don't understand why.
After loa... | 2018/01/13 | [
"https://Stackoverflow.com/questions/48244805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846114/"
] | There is no function named `send` in your code. You have a function named `envoi`. Change `function envoi()` to `function send()` The hazards of multilingual coding!
**Edit: since you updated your answer, try this.**
```
<script>
$(document).ready(function() {
send();
alert($("#image").attr('src'));
});
</scr... | The format of the javascript is incorrect. The Scope of your solution needs to be managed with JQuery. If you simply want to call the function when the page loads, you can call the function inside the JQuery handler. Also, your syntax is not correct.
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
... |
48,244,805 | I need to execute a function named "send()" who contain an ajax request.
This function is in ajax.js (included in )
The Ajax success update the src of my image.
This function work well, I don't think that it is the problem
But when I load the page, send() function is not executed :o I don't understand why.
After loa... | 2018/01/13 | [
"https://Stackoverflow.com/questions/48244805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846114/"
] | There is no function named `send` in your code. You have a function named `envoi`. Change `function envoi()` to `function send()` The hazards of multilingual coding!
**Edit: since you updated your answer, try this.**
```
<script>
$(document).ready(function() {
send();
alert($("#image").attr('src'));
});
</scr... | You could use the onload Event.
This Event is called, wenn the page is loded completely and you can reach the send() function.
<https://www.w3schools.com/jsref/event_onload.asp>
<https://www.w3schools.com/tags/ev_onload.asp>
For instance:
```
<body onload="myFunction()">
<script>
function myFunction() {
... |
48,244,805 | I need to execute a function named "send()" who contain an ajax request.
This function is in ajax.js (included in )
The Ajax success update the src of my image.
This function work well, I don't think that it is the problem
But when I load the page, send() function is not executed :o I don't understand why.
After loa... | 2018/01/13 | [
"https://Stackoverflow.com/questions/48244805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846114/"
] | You could use the onload Event.
This Event is called, wenn the page is loded completely and you can reach the send() function.
<https://www.w3schools.com/jsref/event_onload.asp>
<https://www.w3schools.com/tags/ev_onload.asp>
For instance:
```
<body onload="myFunction()">
<script>
function myFunction() {
... | The format of the javascript is incorrect. The Scope of your solution needs to be managed with JQuery. If you simply want to call the function when the page loads, you can call the function inside the JQuery handler. Also, your syntax is not correct.
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
... |
61,549,690 | I have a bash script that starts my python script. Point of this is, that I hand over a lot of (sometimes changing) arguments to the python script. So I found it useful to start my python script with a bash script where I "save" my argument list.
```
#!/bin/bash
cd $(dirname $0)
python3 script.py [arg0] [arg1]
```
I... | 2020/05/01 | [
"https://Stackoverflow.com/questions/61549690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sounds like a case of operator precedence? Does it work if you wrap the second part in brackets, like
```js
console.log('myFather.__proto__ === Object.prototype:' + (myFather.__proto__ === Object.prototype))
```
Operator precedence, as documented at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refer... | You are actually doing this :
```
console.log( ('myFather.__proto__ === Object.prototype:' + myFather.__proto__) === Object.prototype);
```
So the result of this equality is `false` |
48,364,407 | I'm new to python and I have found tons of my questions have already been answered. In 7 years of coding various languages, I've never actually posted a question on here before, so I'm really stumped this time.
I'm using python 3.6
I have a pandas dataframe with a column that is just Boolean values. I have some code ... | 2018/01/21 | [
"https://Stackoverflow.com/questions/48364407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9246417/"
] | `False not in S` is equivalent to `False not in S.index`. Since the first index element is 0 (which, in turn, is numerically equivalent to `False`), `False` is technically `in` `S`. | When you call `s.values` you are going to have access to a `numpy.array` version of the pandas Series/Dataframe.
Pandas provides a method called `isin` that is going to behave correctly, when calling `s.isin([False])` |
48,364,407 | I'm new to python and I have found tons of my questions have already been answered. In 7 years of coding various languages, I've never actually posted a question on here before, so I'm really stumped this time.
I'm using python 3.6
I have a pandas dataframe with a column that is just Boolean values. I have some code ... | 2018/01/21 | [
"https://Stackoverflow.com/questions/48364407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9246417/"
] | It's not directly what you're asking but you can use .all() on a boolean series to determine if all values are true. Something like:
```
if df["column_name"].all():
#do something
``` | When you call `s.values` you are going to have access to a `numpy.array` version of the pandas Series/Dataframe.
Pandas provides a method called `isin` that is going to behave correctly, when calling `s.isin([False])` |
36,468,707 | I'm having trouble loading the R-package `edgeR` in Python using `rpy2`.
When I run:
```
import rpy2.robjects as robjects
robjects.r('''
library(edgeR)
''')
```
I get the following error:
```
/home/user/.local/lib/python2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Loading required package: l... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36468707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5964533/"
] | If you want 2 different file button, you need to give them different names.
```
<form action="" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="userfile1" size="20">
<input type="file" name="userfile2" size="20">
<input type="submit" name="submit" value="upload">
```
Than... | ```
<form action="http://localhost/cod_login/club/test2" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="userfile" size="20" multiple="">
<input type="submit" name="submit" value="upload">
</form>
``` |
36,468,707 | I'm having trouble loading the R-package `edgeR` in Python using `rpy2`.
When I run:
```
import rpy2.robjects as robjects
robjects.r('''
library(edgeR)
''')
```
I get the following error:
```
/home/user/.local/lib/python2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Loading required package: l... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36468707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5964533/"
] | If you want 2 different file button, you need to give them different names.
```
<form action="" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="userfile1" size="20">
<input type="file" name="userfile2" size="20">
<input type="submit" name="submit" value="upload">
```
Than... | This is the controller code i Have applied for uploading two image in codeigniter
public function index()
{
```
if($this->input->post('Submit')){
//-----------Image File Section Start Here -----------//
$config['upload_path'] = './uploads/'; // Directory
$config['allowed_types'] = 'jpg|jpeg|bmp|png'; //type ... |
36,468,707 | I'm having trouble loading the R-package `edgeR` in Python using `rpy2`.
When I run:
```
import rpy2.robjects as robjects
robjects.r('''
library(edgeR)
''')
```
I get the following error:
```
/home/user/.local/lib/python2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Loading required package: l... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36468707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5964533/"
] | If you want 2 different file button, you need to give them different names.
```
<form action="" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="userfile1" size="20">
<input type="file" name="userfile2" size="20">
<input type="submit" name="submit" value="upload">
```
Than... | 1- create image\_uploader in your controller
```
function image_uploader($filename){
$config['upload_path'] = './assets/uploads/setting/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $... |
43,246,862 | Is there a way to create a cloudformation template, which invokes REST API calls to an EC2 instance ?
The use case is to modify the configuration of the application without having to use update stack and user-data, because user-data updation is disruptive.
I did search through all the documentation and found that thi... | 2017/04/06 | [
"https://Stackoverflow.com/questions/43246862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2617/"
] | I would attack this with Lambda, but it seems as though you already thought of that and might be dismissing it.
A little bit of a hack, but could you add Files to the instance via Metadata where the source is the REST url?
e.g.
```
"Type": "AWS::EC2::Instance",
"Metadata": {
"AWS::CloudFormation::Init": {
... | Lambda triggered by the event. Lifecycle hooks can be helpful.
You can hack CoudFormation, but please mind: it is not designed for this. |
3,893,038 | I use Hakyll to generate some documentation and I noticed that it has a weird way of closing the HTML tags in the code it generates.
There was a page where they said that you must generate the markup as they do, or the layout of your page will be broken under some conditions, but I can't find it now.
I created a smal... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3893038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/212865/"
] | It's actually [pandoc](http://johnmacfarlane.net/pandoc/) that's generating the HTML code. There's a good explanation in the Pandoc issue tracker:
<http://code.google.com/p/pandoc/issues/detail?id=134>
>
> The reason is
> because any whitespace (including newline and tabs) between HTML tags will cause the
> brows... | There are times when stripping the white space between two tags will make a difference, particularly when dealing with inline elements. |
3,893,038 | I use Hakyll to generate some documentation and I noticed that it has a weird way of closing the HTML tags in the code it generates.
There was a page where they said that you must generate the markup as they do, or the layout of your page will be broken under some conditions, but I can't find it now.
I created a smal... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3893038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/212865/"
] | It's actually [pandoc](http://johnmacfarlane.net/pandoc/) that's generating the HTML code. There's a good explanation in the Pandoc issue tracker:
<http://code.google.com/p/pandoc/issues/detail?id=134>
>
> The reason is
> because any whitespace (including newline and tabs) between HTML tags will cause the
> brows... | I ran tidy over it and it fixed the unusual linebreaks. |
3,183,185 | I want to send emails from my app engine application using one of my Google Apps accounts. According to the [GAE python docs](http://code.google.com/appengine/docs/python/mail/overview.html):
*The From: address can be the email address of a registered administrator (developer) of the application, the current user if s... | 2010/07/06 | [
"https://Stackoverflow.com/questions/3183185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358925/"
] | You're misusing the send()/recv() functions. send() and recv() are not required to send as much data as you request, due to limits that may be present in the kernel. You have to call send() over and over until all data has been pushed through.
e.g.:
```
int sent = 0;
int rc;
while ( sent < should_send )
{
rc = sen... | 1. m\_socket can't possibly be null the line after you call `m_socket = new Socket(...)`. It will either throw an exception or assign a `Socket` to m\_socket, never null. So that test is pointless.
2. After you call `readLine()` you must check for a null return value, which means EOS, which means the other end has clos... |
3,183,185 | I want to send emails from my app engine application using one of my Google Apps accounts. According to the [GAE python docs](http://code.google.com/appengine/docs/python/mail/overview.html):
*The From: address can be the email address of a registered administrator (developer) of the application, the current user if s... | 2010/07/06 | [
"https://Stackoverflow.com/questions/3183185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358925/"
] | Java side,
```
int lent2 = 0;
int LengthToReceive = 102400;
char[] chTemp = new char[LengthToReceive];
while (true) {
int readlength = bufferedreader.read(chTemp, lent2,LengthToReceive - lent2);
if(readlength==-1){
break;
}
lent2 += readlength;
if (lent2 >= LengthToReceive) {
fla... | 1. m\_socket can't possibly be null the line after you call `m_socket = new Socket(...)`. It will either throw an exception or assign a `Socket` to m\_socket, never null. So that test is pointless.
2. After you call `readLine()` you must check for a null return value, which means EOS, which means the other end has clos... |
29,682,897 | I am using py2neo and I would like to extract the information from query returns so that I can do stuff with it in python. For example, I have a DB containing three "Person" nodes:
`for num in graph.cypher.execute("MATCH (p:Person) RETURN count(*)"):
print num`
outputs:
`>> count(*)`
`3`
Sorry for shitty formatti... | 2015/04/16 | [
"https://Stackoverflow.com/questions/29682897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2505865/"
] | The clue is in the question: "Assume that I have a fetcher that fetches an image from a given link on a separate thread. The image will then be **cached** in memory."
And the answer is the `cache()` operator:
"remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers"
... | Have a look at `ConnectableObservable` and the `.replay()` method.
I'm currently using this is my fragments to handle orientation changes:
Fragment's onCreate:
```
ConnectableObservable<MyThing> connectableObservable =
retrofitService.fetchMyThing()
.map(...)
.replay();
connectableObservable.c... |
29,682,897 | I am using py2neo and I would like to extract the information from query returns so that I can do stuff with it in python. For example, I have a DB containing three "Person" nodes:
`for num in graph.cypher.execute("MATCH (p:Person) RETURN count(*)"):
print num`
outputs:
`>> count(*)`
`3`
Sorry for shitty formatti... | 2015/04/16 | [
"https://Stackoverflow.com/questions/29682897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2505865/"
] | This can be accomplished via ConcurrentMap and AsyncSubject:
```
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.concurrent.*;
import javax.imageio.ImageIO;
import rx.*;
import rx.Scheduler.Worker;
import rx.schedulers.Schedulers;
import rx.subjects.AsyncSubject;
public ... | Have a look at `ConnectableObservable` and the `.replay()` method.
I'm currently using this is my fragments to handle orientation changes:
Fragment's onCreate:
```
ConnectableObservable<MyThing> connectableObservable =
retrofitService.fetchMyThing()
.map(...)
.replay();
connectableObservable.c... |
53,892,106 | i wanted to make a python file that makes a copy of itself, then executes it and closes itself, then the copy makes another copy of itself and so on...
i am not asking for people to write my code and this could be taken as just a fun challenge, but i want to learn more about this stuff and help is appreciated.
i have... | 2018/12/22 | [
"https://Stackoverflow.com/questions/53892106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10756702/"
] | I don't have enough rep to reply to @Prune:
`os.startfile(file)` only works on Windows, and is [replaced by](https://docs.python.org/3/library/subprocess.html) `subprocess.call`
`shutil.copy2(src, dst)` works on both Windows and Linux.
Try this solution as well:
```
import shutil
import subprocess
old_file = __file... | You're close; you have things in the wrong order. Create the new file, *then* execute it.
```
import os
old_file = __file__
new_file = generate_unique_file_name()
os.system('cp ' + old_file + ' ' + new_file) #UNIX syntax; for Windows, use "copy"
os.startfile(new_file)
```
You'll have to choose & code your preferre... |
47,393,177 | I'm actually working on a django project and i'm migrating to a CustomUser model. On the database everything have gone well and now i want to force my user to update their informations (to respect the new model)
I would like to do it when they login (I set all the e-mail to end with @mysite.tmp in order to know if the... | 2017/11/20 | [
"https://Stackoverflow.com/questions/47393177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876232/"
] | You can write the logic as:
```
select *
from table
where (Vendorname = @Vendor) OR (@Vendor IS NULL)
```
One caution: This may not be as optimized as your version, if you have an index on `Vendorname`. | ```
select *
from table
where Vendorname = case when @Vendor is not null then @Vendor else Vendorname end;
``` |
47,393,177 | I'm actually working on a django project and i'm migrating to a CustomUser model. On the database everything have gone well and now i want to force my user to update their informations (to respect the new model)
I would like to do it when they login (I set all the e-mail to end with @mysite.tmp in order to know if the... | 2017/11/20 | [
"https://Stackoverflow.com/questions/47393177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876232/"
] | You can write the logic as:
```
select *
from table
where (Vendorname = @Vendor) OR (@Vendor IS NULL)
```
One caution: This may not be as optimized as your version, if you have an index on `Vendorname`. | Using an IF is the right choice here. Using "catch all" parameters can lead to poor choices by the query planner.
SQL doesn't use Brackets ({ }), it uses BEGIN and END. Thus you get:
```
IF @Vendor IS NOT NULL BEGIN
SELECT*
FROM table
WHERE Vendorname = @Vendor;
END ELSE BEGIN
SELECT *
FROM table... |
47,393,177 | I'm actually working on a django project and i'm migrating to a CustomUser model. On the database everything have gone well and now i want to force my user to update their informations (to respect the new model)
I would like to do it when they login (I set all the e-mail to end with @mysite.tmp in order to know if the... | 2017/11/20 | [
"https://Stackoverflow.com/questions/47393177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876232/"
] | You can write the logic as:
```
select *
from table
where (Vendorname = @Vendor) OR (@Vendor IS NULL)
```
One caution: This may not be as optimized as your version, if you have an index on `Vendorname`. | Another solution you can use :
```
select * from table
where isnull(Vendorname, '') = coalesce(@Vendor, Vendorname, '')
``` |
47,393,177 | I'm actually working on a django project and i'm migrating to a CustomUser model. On the database everything have gone well and now i want to force my user to update their informations (to respect the new model)
I would like to do it when they login (I set all the e-mail to end with @mysite.tmp in order to know if the... | 2017/11/20 | [
"https://Stackoverflow.com/questions/47393177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876232/"
] | ```
select *
from table
where Vendorname = case when @Vendor is not null then @Vendor else Vendorname end;
``` | Using an IF is the right choice here. Using "catch all" parameters can lead to poor choices by the query planner.
SQL doesn't use Brackets ({ }), it uses BEGIN and END. Thus you get:
```
IF @Vendor IS NOT NULL BEGIN
SELECT*
FROM table
WHERE Vendorname = @Vendor;
END ELSE BEGIN
SELECT *
FROM table... |
47,393,177 | I'm actually working on a django project and i'm migrating to a CustomUser model. On the database everything have gone well and now i want to force my user to update their informations (to respect the new model)
I would like to do it when they login (I set all the e-mail to end with @mysite.tmp in order to know if the... | 2017/11/20 | [
"https://Stackoverflow.com/questions/47393177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876232/"
] | ```
select *
from table
where Vendorname = case when @Vendor is not null then @Vendor else Vendorname end;
``` | Another solution you can use :
```
select * from table
where isnull(Vendorname, '') = coalesce(@Vendor, Vendorname, '')
``` |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You could use `defaultdict` to store the result instead of a list. The keys of the dictionary would be the months and you can simply add the values with the same month (key).
Possible implementation:
```py
# Test Data
from collections import defaultdict
sum_weekly = [('2020/01/05', 59), ('2020/01/19', 88), ('2020/01... | You can use `itertools.groupby` (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:
```
import itertools
def select_month(item):
return item[0].split('/')[1]
def ... |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You could use `defaultdict` to store the result instead of a list. The keys of the dictionary would be the months and you can simply add the values with the same month (key).
Possible implementation:
```py
# Test Data
from collections import defaultdict
sum_weekly = [('2020/01/05', 59), ('2020/01/19', 88), ('2020/01... | Terse, but maybe not that pythonic:
```
import calendar, functools, collections
{calendar.month_name[i]: val for i, val in functools.reduce(lambda a, b: a + b, [collections.Counter({datetime.datetime.strptime(time, '%Y/%m/%d').month: val}) for time, val in sum_weekly]).items()}
``` |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You could use `defaultdict` to store the result instead of a list. The keys of the dictionary would be the months and you can simply add the values with the same month (key).
Possible implementation:
```py
# Test Data
from collections import defaultdict
sum_weekly = [('2020/01/05', 59), ('2020/01/19', 88), ('2020/01... | a method using pyspark
```
from pyspark import SparkContext
sc = SparkContext()
l = sc.parallelize(sum_weekly)
r = l.map(lambda x: (x[0].split("/")[1], x[1])).reduceByKey(lambda p, q: (p + q)).collect()
print(r) #[('04', 13), ('02', 360), ('01', 242), ('03', 220), ('05', 67)]
``` |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You could use `defaultdict` to store the result instead of a list. The keys of the dictionary would be the months and you can simply add the values with the same month (key).
Possible implementation:
```py
# Test Data
from collections import defaultdict
sum_weekly = [('2020/01/05', 59), ('2020/01/19', 88), ('2020/01... | You can accomplish this with a Pandas dataframe. First, you isolate the month, and then use groupby.sum().
```
import pandas as pd
sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89), ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08',... |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You can use `itertools.groupby` (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:
```
import itertools
def select_month(item):
return item[0].split('/')[1]
def ... | Terse, but maybe not that pythonic:
```
import calendar, functools, collections
{calendar.month_name[i]: val for i, val in functools.reduce(lambda a, b: a + b, [collections.Counter({datetime.datetime.strptime(time, '%Y/%m/%d').month: val}) for time, val in sum_weekly]).items()}
``` |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You can use `itertools.groupby` (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:
```
import itertools
def select_month(item):
return item[0].split('/')[1]
def ... | a method using pyspark
```
from pyspark import SparkContext
sc = SparkContext()
l = sc.parallelize(sum_weekly)
r = l.map(lambda x: (x[0].split("/")[1], x[1])).reduceByKey(lambda p, q: (p + q)).collect()
print(r) #[('04', 13), ('02', 360), ('01', 242), ('03', 220), ('05', 67)]
``` |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You can use `itertools.groupby` (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:
```
import itertools
def select_month(item):
return item[0].split('/')[1]
def ... | You can accomplish this with a Pandas dataframe. First, you isolate the month, and then use groupby.sum().
```
import pandas as pd
sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89), ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08',... |
43,252,531 | I am installing python 3.5, django 1.10 and psycopg2 2.7.1 on Amazon EC2 server in order to use a Postgresql database. I am using python 3 inside a virtual environment, and followed the classic installation steps:
```
cd /home/mycode
virtualenv-3.5 p3env
source p3env/bin/activate
pip install django
cd kenbot
django-ad... | 2017/04/06 | [
"https://Stackoverflow.com/questions/43252531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5591278/"
] | As suggested by @dentemm: the issue was resolved by copying all the psysopg2 directories from their current location in the lib64 directory, to the directory where django was installed /home/mycode/p3env/lib/python3.5/dist-packages. | Uninstalling and then reinstalling the library really helped!
>
> **(venv)$ pip uninstall psycopg2**
>
>
>
---
>
> **(venv)$ pip install psycopg2**
>
>
> |
52,101,595 | SQLAlchemy nicely documents [how to use Association Objects with `back_populates`](http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#association-object).
However, when copy-and-pasting the example from that documentation, adding children to a parent throws a `KeyError` as following code shows. The mode... | 2018/08/30 | [
"https://Stackoverflow.com/questions/52101595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543875/"
] | **tldr;** We have to use Association Proxy extensions *and* create a custom constructor for the association object which takes the child object as the first (!) parameter. See solution based on the example from the question below.
SQLAlchemy's documentation actually states in the next paragraph that we aren't done yet... | So to make a long story short.
You need to append an association object containing your child object onto your parent. Otherwise, you need to follow Lars' suggestion about a proxy association.
I recommend the former since it's the ORM-based way:
```
p = Parent()
p.children.append(Association(child = Child()))
sessio... |
35,996,175 | ```
'''
Created on 13.3.2016
worm game
@author: Hai
'''
import pygame
import random
from pygame import * ##
class Worm:
def __init__(self, surface):
self.surface = surface
self.x = surface.get_width() / 2
self.y = surface.get_height() / 2
self.length = 1
self.grow_to = 50
... | 2016/03/14 | [
"https://Stackoverflow.com/questions/35996175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4802223/"
] | I had to remove all the N preview stuff from my sdk to make things normal again. Don't forget the cache too.
```
sdk/extras/android/m2repository/com/android/support/design|support-v-13|ect./24~
``` | The syntax of xml line you wrote is wrong
instead of
`android:setTextColor=""`
use
```
android:textColor=""
``` |
35,996,175 | ```
'''
Created on 13.3.2016
worm game
@author: Hai
'''
import pygame
import random
from pygame import * ##
class Worm:
def __init__(self, surface):
self.surface = surface
self.x = surface.get_width() / 2
self.y = surface.get_height() / 2
self.length = 1
self.grow_to = 50
... | 2016/03/14 | [
"https://Stackoverflow.com/questions/35996175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4802223/"
] | I had to remove all the N preview stuff from my sdk to make things normal again. Don't forget the cache too.
```
sdk/extras/android/m2repository/com/android/support/design|support-v-13|ect./24~
``` | You can change the Text Color in layout XML by using android:textColor
example:
```
android:textColor="#0E0E9A"
```
it overrides the style.xml
the only way to override your layout.xml is by code
example:
```
mEditText.setTextColor(Color.DKGRAY);
``` |
14,738,725 | I am asked:
>
> Using your raspberry pi, write a python script that determines the randomness
> of /dev/random and /dev/urandom. Read bytes and histogram the results.
> Plot in matplotlib. For your answer include the python script.
>
>
>
I am currently lost on the phrasing "determines the randomness."
I can re... | 2013/02/06 | [
"https://Stackoverflow.com/questions/14738725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779920/"
] | Could it be as simple as:
```
In [664]: f = open("/dev/random", "rb")
In [665]: len(set(f.read(256)))
Out[665]: 169
In [666]: ff = open("/dev/urandom", "rb")
In [667]: len(set(ff.read(256)))
Out[667]: 167
In [669]: len(set(f.read(512)))
Out[669]: 218
In [670]: len(set(ff.read(512)))
Out[670]: 224
```
ie. asking ... | Your experience may be exactly what they're looking for. From the man page of urandom(4):
>
> When read, the /dev/random device will only return
> random bytes within the estimated number of bits of noise
> in the entropy pool. /dev/random should be suitable for uses that need very high quality randomness such as
>... |
66,104,854 | I want to download the data from `USDA` site with custom queries. So instead of manually selecting queries in the website, I am thinking about how should I do this handier in python. To do so, I used `request`, `http` to access the url and read the content, it is not intuitive for me how should I pass the queries then ... | 2021/02/08 | [
"https://Stackoverflow.com/questions/66104854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14126595/"
] | A few details
* simplest format is text rather that HTML. Got URL from HTML page for text download
* `requests(params=)` is a `dict`. Built it up and passed, no need to deal with building complete URL string
* clearly text is space delimited, found minimum of double space
```
import io
import requests
import pandas a... | Just format the query data in the url - it's actually a REST API:
To add more query data, as @mullinscr said, you can change the values on the left and press submit, then see the query name in the URL (for example, start date is called `repDate`).
If you hover on the Download as XML link, you will also discover you c... |
57,252,637 | I'm using PySpark (a new thing for me). Now, suppose I Have the following table:
`+-------+-------+----------+
| Col1 | Col2 | Question |
+-------+-------+----------+
| val11 | val12 | q1 |
| val21 | val22 | q2 |
| val31 | val32 | q3 |
+-------+-------+----------+`
and I would like to append to it a new column, `random... | 2019/07/29 | [
"https://Stackoverflow.com/questions/57252637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690045/"
] | This should do the trick:
```
import pyspark.sql.functions as F
questions = df.select(F.col('Question').alias('random_question'))
random = questions.orderBy(F.rand())
```
Give the dataframes a unique row id:
```
df = df.withColumn('row_id', F.monotonically_increasing_id())
random = random.withColumn('row_id', F.mo... | The above answer is wrong. You are not guaranteed to have the same set of ids in the two dataframes and you will lose rows.
```
df = spark.createDataFrame(pd.DataFrame({'a':[1,2,3,4],'b':[10,11,12,13],'c':[100,101,102,103]}))
questions = df.select(F.col('a').alias('random_question'))
random = questions.orderBy(F.rand(... |
57,373,034 | I have a list of tuples:
```
d = [("a", "x"), ("b", "y"), ("a", "y")]
```
and the `DataFrame`:
```
y x
b 0.0 0.0
a 0.0 0.0
```
I would like to replace any `0s` with `1s` if the row and column labels correspond to a tuple in `d`, such that the new DataFrame is:
```
y x
b 1.0 0.0
a 1.0 1.0
... | 2019/08/06 | [
"https://Stackoverflow.com/questions/57373034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6017833/"
] | **Approach #1: No bad entries in `d`**
Here's one NumPy based method -
```
def assign_val(df, d, newval=1):
# Get d-rows,cols as arrays for efficient usage latet on
di,dc = np.array([j[0] for j in d]), np.array([j[1] for j in d])
# Get col and index data
i,c = df.index.values.astype(di.dtype),d... | Use [`get_dummies`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html) with `DataFrame` constructor:
```
df = pd.get_dummies(pd.DataFrame(d).set_index(0)[1]).rename_axis(None).max(level=0)
```
Or use `zip` with `Series`:
```
lst = list(zip(*d))
df = pd.get_dummies(pd.Series(lst[1], i... |
40,664,226 | i'm tryng to get some tweet data from a MySql database.
I've got tons of encoding errors while i was developing this code. This last for is the only way i got for running the code and getting this outfile full with \uxx characters all around, as you can see here:
```
[{..., "lang_tweet": "es", "text_tweet": "Recuerdo ... | 2016/11/17 | [
"https://Stackoverflow.com/questions/40664226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5298808/"
] | This is not a string concatenation, but adding `.x` and `.y` to pointer to `","`:
```
cursorLocation.x + "," + cursorLocation.y
```
Instead, try e.g.:
```
char s[256];
sprintf_s(s, "%d,%d", cursorLocation.x, cursorLocation.y);
OutputDebugStringA(s); // added 'A' after @IInspectable's comment, but
... | String concatenation doesn't work with integers.
Try using `std::ostringstream`:
```
std::ostringstream out_stream;
out_stream << cursorLocation.x << ", " << cursorLocation.y;
OuputDebugString(out_stream.str().c_str());
``` |
45,375,944 | While parsing attributes using [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__), my [`@staticmethod`](https://docs.python.org/3/library/functions.html?highlight=staticmethod#staticmethod) is not [`callable`](https://docs.python.org/3/library/functions.html?highlight=staticmethod#callable).
... | 2017/07/28 | [
"https://Stackoverflow.com/questions/45375944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938111/"
] | The reason for this behavior is the descriptor protocol. The `C.foo` won't return a `staticmethod` but a normal function while the `'foo'` in `__dict__` is a [`staticmethod`](https://docs.python.org/library/functions.html#staticmethod) (and `staticmethod` is a descriptor).
In short `C.foo` isn't the same as `C.__dict_... | You can't check if a `staticmethod` object is callable or not. This was discussed on the tracker in [Issue 20309 -- Not all method descriptors are callable](https://bugs.python.org/issue20309) and closed as "not a bug".
In short, there's been no rationale for implementing `__call__` for staticmethod objects. The buil... |
50,117,538 | I use windows 7 without admin rights and i would like to use python3.
Even if i set PYTHONPATH, environment variable is ignored. However PYTHONPATH is valid when printed.
```
>>> print(sys.path)
['c:\\Python365\\python36.zip', 'c:\\Python365']
>>> print(os.environ["PYTHONPATH"])
d:\libs
```
any idea ?
thank you ver... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50117538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922846/"
] | When using the embedded distribution (.zip file), then the `PYTHONPATH` environment variable is not respected. If this behavior is needed, then one needs to add some Python code that load the setting it from os.environ.get('PYTHONPATH', '') split the directories and add them to `sys.path`.
Also note that pip is not su... | Add the contents of PYTHONPATH to python.\_pth in the root folder one entry per line. |
17,585,207 | I copied this verbatim from python.org unittest documentation:
```
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(s... | 2013/07/11 | [
"https://Stackoverflow.com/questions/17585207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1913647/"
] | Check that you are really using 2.7 python.
Tested using `pythonbrew`:
```
$ pythonbrew use 2.7.2
$ python test.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
$ pythonbrew use 2.6.5
$ python test.py
.E.
=========================================================... | If you're using 2.7 and still seeing this issue, it could be because you're not using python's `unittest` module. Some other modules like `twisted` provide `assertRaises` and though they try to maintain compatibility with python's `unittest`, your particular version of that module may be out of date. |
17,585,207 | I copied this verbatim from python.org unittest documentation:
```
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(s... | 2013/07/11 | [
"https://Stackoverflow.com/questions/17585207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1913647/"
] | The ability to use unittest.TestCase.AssertRaises() as context manager was added in python 2.7.
<http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises> | If you're using 2.7 and still seeing this issue, it could be because you're not using python's `unittest` module. Some other modules like `twisted` provide `assertRaises` and though they try to maintain compatibility with python's `unittest`, your particular version of that module may be out of date. |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | Here is one way to sort the list using `reduce`:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(
lambda a, b: [x for x in a if x <= b] + [b] + [x for x in a if x > b],
arr,
[]
)
print(sorted_arr)
#[1, 1, 2, 3, 3, 3, 5, 6, 9, 17]
```
At each reduce step, build a new output list which concat... | I think you're misunderstanding how reduce works here. Reduce is synonymous to *right-fold* in some other languages (e.g. Haskell). The first argument expects a function which takes two parameters: an *accumulator* and an element to accumulate.
Let's hack into it:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
reduce(lamb... |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | Here is one way to sort the list using `reduce`:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(
lambda a, b: [x for x in a if x <= b] + [b] + [x for x in a if x > b],
arr,
[]
)
print(sorted_arr)
#[1, 1, 2, 3, 3, 3, 5, 6, 9, 17]
```
At each reduce step, build a new output list which concat... | Ninjad! But yes, it's an insertion sort.
```py
def insert(acc, e):
for i, x in enumerate(acc):
if x > e:
acc.insert(i, e)
return acc
acc.append(e)
return acc
reduce(insert, [1, 2, 6, 4, 7, 3, 0, -1], [])
```
outputs
```py
[-1, 0, 1, 2, 3, 4, 6, 7]
``` |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | Here is one way to sort the list using `reduce`:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(
lambda a, b: [x for x in a if x <= b] + [b] + [x for x in a if x > b],
arr,
[]
)
print(sorted_arr)
#[1, 1, 2, 3, 3, 3, 5, 6, 9, 17]
```
At each reduce step, build a new output list which concat... | After some thinking I concluded that it is also possible to do swap-based sort, if you are allowed to use `reduce` more than once. Namely:
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
def func(acc,x):
if not acc:
return [x]
if acc[-1]<x:
return acc+[x]
else:
... |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | Here is one way to sort the list using `reduce`:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(
lambda a, b: [x for x in a if x <= b] + [b] + [x for x in a if x > b],
arr,
[]
)
print(sorted_arr)
#[1, 1, 2, 3, 3, 3, 5, 6, 9, 17]
```
At each reduce step, build a new output list which concat... | Let's understand this
(1)Usage of Reduce is basically to reduce the expression to a single final value
(2)reduce() stores the intermediate result and only returns the final summation value
(3)We will take the smallest element using reduce, append it to sorted\_list and remove from the original list
(4)Now the ... |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | I think you're misunderstanding how reduce works here. Reduce is synonymous to *right-fold* in some other languages (e.g. Haskell). The first argument expects a function which takes two parameters: an *accumulator* and an element to accumulate.
Let's hack into it:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
reduce(lamb... | Ninjad! But yes, it's an insertion sort.
```py
def insert(acc, e):
for i, x in enumerate(acc):
if x > e:
acc.insert(i, e)
return acc
acc.append(e)
return acc
reduce(insert, [1, 2, 6, 4, 7, 3, 0, -1], [])
```
outputs
```py
[-1, 0, 1, 2, 3, 4, 6, 7]
``` |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | I think you're misunderstanding how reduce works here. Reduce is synonymous to *right-fold* in some other languages (e.g. Haskell). The first argument expects a function which takes two parameters: an *accumulator* and an element to accumulate.
Let's hack into it:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
reduce(lamb... | After some thinking I concluded that it is also possible to do swap-based sort, if you are allowed to use `reduce` more than once. Namely:
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
def func(acc,x):
if not acc:
return [x]
if acc[-1]<x:
return acc+[x]
else:
... |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | I think you're misunderstanding how reduce works here. Reduce is synonymous to *right-fold* in some other languages (e.g. Haskell). The first argument expects a function which takes two parameters: an *accumulator* and an element to accumulate.
Let's hack into it:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
reduce(lamb... | Let's understand this
(1)Usage of Reduce is basically to reduce the expression to a single final value
(2)reduce() stores the intermediate result and only returns the final summation value
(3)We will take the smallest element using reduce, append it to sorted\_list and remove from the original list
(4)Now the ... |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | Ninjad! But yes, it's an insertion sort.
```py
def insert(acc, e):
for i, x in enumerate(acc):
if x > e:
acc.insert(i, e)
return acc
acc.append(e)
return acc
reduce(insert, [1, 2, 6, 4, 7, 3, 0, -1], [])
```
outputs
```py
[-1, 0, 1, 2, 3, 4, 6, 7]
``` | Let's understand this
(1)Usage of Reduce is basically to reduce the expression to a single final value
(2)reduce() stores the intermediate result and only returns the final summation value
(3)We will take the smallest element using reduce, append it to sorted\_list and remove from the original list
(4)Now the ... |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | After some thinking I concluded that it is also possible to do swap-based sort, if you are allowed to use `reduce` more than once. Namely:
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
def func(acc,x):
if not acc:
return [x]
if acc[-1]<x:
return acc+[x]
else:
... | Let's understand this
(1)Usage of Reduce is basically to reduce the expression to a single final value
(2)reduce() stores the intermediate result and only returns the final summation value
(3)We will take the smallest element using reduce, append it to sorted\_list and remove from the original list
(4)Now the ... |
59,398,271 | I am doing object tracking on my videos which are in .mpg format what i am doing is i am using OpenCV to track the objects but i am facing some while opening it in my code i have attached my code.
```
import cv2
import sys
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if __name__ == '__main__'... | 2019/12/18 | [
"https://Stackoverflow.com/questions/59398271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449718/"
] | POSSIBLY WRONG PATH
Check if Stroll.mpg is in right there in your working directory. If yes try with an .mp4 video. Most probably the path is wrong or file name Is misspelled.
Refer: <https://answers.opencv.org/question/1965/cv2videocapture-cannot-read-from-file/> | Make sure your opencv is compiled *with ffmpeg* which provides all those media-decoders (probably missing without).
[Someone with a similar problem](https://answers.opencv.org/question/220468/video-from-ip-camera-cant-find-starting-number-cvicvextractpattern/) due to this. |
43,401,174 | I'm new to python and I would like to know if this is possible or not:
I want to create an object and attach to it another object.
```
OBJECT A
Child 1
Child 2
OBJECT B
Child 3
Child 4
Child 5
Child 6
Child 7
```
is this possible ? | 2017/04/13 | [
"https://Stackoverflow.com/questions/43401174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6218501/"
] | If you are talking about object oriented terms, yes you can,you dont explain clearly what you want to do, but the 2 things that come to my mind if you are talking about OOP are:
* If you are talking about inheritance you can make child objects extend parent objects when you create your child class: class child(parent)... | Here is an example:
In this scenario an object can be a person without being an employee, however to be an employee they must be a person. Therefor the person class is a parent to the employee
Here's the link to an article that really helped me understand inheritance:
<http://www.python-course.eu/python3_inheritance.... |
43,401,174 | I'm new to python and I would like to know if this is possible or not:
I want to create an object and attach to it another object.
```
OBJECT A
Child 1
Child 2
OBJECT B
Child 3
Child 4
Child 5
Child 6
Child 7
```
is this possible ? | 2017/04/13 | [
"https://Stackoverflow.com/questions/43401174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6218501/"
] | To follow your example:
```
class Car(object):
def __init__(self, tire_size = 1):
self.tires = [Tire(tire_size) for _ in range(4)]
class Tire(object):
def __init__(self, size):
self.weight = 2.25 * size
```
Now you can make a car and query the tire weights:
```
>>> red = Car(1)
>>> red.tire... | Here is an example:
In this scenario an object can be a person without being an employee, however to be an employee they must be a person. Therefor the person class is a parent to the employee
Here's the link to an article that really helped me understand inheritance:
<http://www.python-course.eu/python3_inheritance.... |
21,047,114 | For sublime text, I installed RstPreview, downloaded `docutils-0.11`, and installed it by running `C:\Anaconda\python setup.py install` in Command Prompt (I am using windows 7 64 bits).
When I press `Ctrl+Shift+R` to parse a `.rst` file I get the following,
 for this plugin, it doesn't look like there is any good way of getting it to work on Windows. I can expand on the technicalities if you want, but basically this plugin relies on installing a third-party package (`docutils`) into the version... | I just came across restview, which does work on windows and offers a nice approach for providing feedback about how your rst file will be rendered as html. Here is an excerpt from the [restview pypi page](https://pypi.python.org/pypi/restview).
>
> A viewer for ReStructuredText documents that renders them on the fly.... |
57,645,717 | I'm trying to dockerize my python code but centos latest image does not have python3 in the repository packages at all .
I tried:
```
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
* base: mirror.karneval.cz
* extras: mirror.karneval.cz
* updates: mirror.karneval.cz
================... | 2019/08/25 | [
"https://Stackoverflow.com/questions/57645717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10306308/"
] | Well i tested some other images as well like Ubuntu:latest and alpine:latest and python3 not installed by default but it's in the repos and you can install by the package manager
In Centos:latest I can confirm that python3 isn't in the default configured Repos of the image
However you can find it in other Repos as m... | I need python3.5 or later in centos:latest Docker image, and I found that I can get it easily by:
```
RUN yum -y install epel-release
RUN yum -y install python3 python3-pip
```
This way I get:
```
[user@machine /]# python3 --version
Python 3.6.8
```
And I can use "pip3 install package" to install additional pytho... |
8,179,068 | I'm working with SQLAlchemy for the first time and was wondering...generally speaking is it enough to rely on python's default equality semantics when working with SQLAlchemy vs id (primary key) equality?
In other projects I've worked on in the past using ORM technologies like Java's Hibernate, we'd always override .e... | 2011/11/18 | [
"https://Stackoverflow.com/questions/8179068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/964823/"
] | Short answer: No, unless you're working with multiple Session objects.
Longer answer, quoting the awesome [documentation](http://www.sqlalchemy.org/docs/orm/tutorial.html#adding-new-objects):
>
> The ORM concept at work here is known as an identity map and ensures that all operations upon a particular row within a S... | I had a few situations where my sqlalchemy application would load multiple instances of the same object (multithreading/ different sqlalchemy sessions ...). It was absolutely necessary to override eq() for those objects or I would get various problems. This could be a problem in my application design, but it probably d... |
12,214,326 | I am new in python and I making a new code and I need a little help
Main file :
```
import os
import time
import sys
import app
import dbg
import dbg
import me
sys.path.append("lib")
class TraceFile:
def write(self, msg):
dbg.Trace(msg)
class TraceErrorFile:
def write(self, msg):
dbg.TraceE... | 2012/08/31 | [
"https://Stackoverflow.com/questions/12214326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638487/"
] | Why not doing this: define a method in the module you import and call this method 5 times in a loop with a certain `time.sleep(x)` in each iteration.
Edit:
Consider this is your module to import (e.g. `very_good_module.py`):
```
def interesting_action():
print "Wow, I did not expect this! This is a very good mod... | ```
#my_module.py (print hello once)
print "hello"
#main (print hello n times)
import time
import my_module # this will print hello
import my_module # this will not print hello
reload(my_module) # this will print hello
for i in xrange(n-2):
reload(my_module) #this will print hello n-2 times
time.sleep(seconds... |
47,064,278 | I've been working on this script today and have made some really good progress with looping through the data and importing it to an external database. I'm trying to troubleshoot a field that I'm having an issue with and it doesn't make much sense. Whenever I attempt to run it, I get the following error `KeyError: 'manu... | 2017/11/01 | [
"https://Stackoverflow.com/questions/47064278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257896/"
] | my guess is that one of the items in your data does not have a 'manufacturer' key set.
replace
item['manufacturer']
by
item.get('manufacturer', None)
or replace None by a default manufacturer... | Here are two ways of doing getting around a dictionary not having a key. Both work but the first one is probably easier to use and will work as a drop in for your current code.
This is a way of doing it using python's `dictionary.get()` method. [Here is a page with more examples of how it works](https://www.tutorials... |
47,064,278 | I've been working on this script today and have made some really good progress with looping through the data and importing it to an external database. I'm trying to troubleshoot a field that I'm having an issue with and it doesn't make much sense. Whenever I attempt to run it, I get the following error `KeyError: 'manu... | 2017/11/01 | [
"https://Stackoverflow.com/questions/47064278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257896/"
] | my guess is that one of the items in your data does not have a 'manufacturer' key set.
replace
item['manufacturer']
by
item.get('manufacturer', None)
or replace None by a default manufacturer... | Not quite the issue at hand (item is missing key `manufacturer`, perhaps more), but since you're just copying fields with the exact same keys, you can write something like this. Also note that `item.get(key, None)` will rid you of this error at the cost of having `None` values in product (so if you like your code to fa... |
47,064,278 | I've been working on this script today and have made some really good progress with looping through the data and importing it to an external database. I'm trying to troubleshoot a field that I'm having an issue with and it doesn't make much sense. Whenever I attempt to run it, I get the following error `KeyError: 'manu... | 2017/11/01 | [
"https://Stackoverflow.com/questions/47064278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1257896/"
] | Not quite the issue at hand (item is missing key `manufacturer`, perhaps more), but since you're just copying fields with the exact same keys, you can write something like this. Also note that `item.get(key, None)` will rid you of this error at the cost of having `None` values in product (so if you like your code to fa... | Here are two ways of doing getting around a dictionary not having a key. Both work but the first one is probably easier to use and will work as a drop in for your current code.
This is a way of doing it using python's `dictionary.get()` method. [Here is a page with more examples of how it works](https://www.tutorials... |
65,364,425 | I'm trying to pass primary key as URL argument from CreatePost to UploadImage view but I'm constantly getting an error even if I see primary key in URL. I'm new to Django, so please help me :)
**views.py**
```
class CreatePost(CreateView):
model=shopModels.UserPost
template_name='shop/create_post.html'
... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65364425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14852796/"
] | I think you are not including `user_post` key in html form, you should include it in jinja style
`<a class="btn btn-success" href="{% url 'image_upload' user_post=user_post_key %}">`
And if you want to do some operations based on that `user_post` You should override the `form_valid(self)` method and access the `int:u... | Your path explicitly expects and integer for user\_post:
```
path('image_upload/<int:user_post>',views.UploadImage.as_view(),name="image_upload"),
```
If you call reverse(...) and you handover 123 you meed to make sure that 123 is a type integer and not e.g. string. |
37,103,682 | I am only starting out programming and currently making a text game. I know there is no goto command in python and after doing some research I understood that I have to use loops to replace that command but it just isn't doing what i was hoping it would do. Here's my code:
```
print('Welcome to my bad game!')
print('P... | 2016/05/08 | [
"https://Stackoverflow.com/questions/37103682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6307467/"
] | If you mean to the beginning to the loop, just leave out the call to `quit`. If you mean to the beginning of the *program*, then you'll need a loop around that as well. | Instead of quit you could use 'continue' to loop back to your while. But it's not clear from this example what you want the while to do. |
4,619,580 | With python, I can use [logging](http://docs.python.org/library/logging.html) library.
What do you use for the logging library with C++? | 2011/01/06 | [
"https://Stackoverflow.com/questions/4619580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | I personally like: <http://code.google.com/p/google-glog/>
You have many options though. This one is pretty similar to what you are used to. | Maybe you will want to take a look at <https://github.com/gabime/spdlog>, they used a Python style syntax to compose log messages, and is pretty fast and safe. |
4,619,580 | With python, I can use [logging](http://docs.python.org/library/logging.html) library.
What do you use for the logging library with C++? | 2011/01/06 | [
"https://Stackoverflow.com/questions/4619580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | I personally like: <http://code.google.com/p/google-glog/>
You have many options though. This one is pretty similar to what you are used to. | You can also have a look at [quill](https://github.com/odygrd/quill).
It is using a python style syntax to log and has a similar API to the python logging module. It is stable and built for low latency as well. |
4,619,580 | With python, I can use [logging](http://docs.python.org/library/logging.html) library.
What do you use for the logging library with C++? | 2011/01/06 | [
"https://Stackoverflow.com/questions/4619580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | We are heavyweight users of [log4cxx](http://logging.apache.org/log4cxx/index.html). I can recommend it, though I am told that the current version won't build in Visual Studio 2010. | Maybe you will want to take a look at <https://github.com/gabime/spdlog>, they used a Python style syntax to compose log messages, and is pretty fast and safe. |
4,619,580 | With python, I can use [logging](http://docs.python.org/library/logging.html) library.
What do you use for the logging library with C++? | 2011/01/06 | [
"https://Stackoverflow.com/questions/4619580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260127/"
] | We are heavyweight users of [log4cxx](http://logging.apache.org/log4cxx/index.html). I can recommend it, though I am told that the current version won't build in Visual Studio 2010. | You can also have a look at [quill](https://github.com/odygrd/quill).
It is using a python style syntax to log and has a similar API to the python logging module. It is stable and built for low latency as well. |
45,386,035 | I run several python subprocesses to migrate data to S3. I noticed that my python subprocesses often drops to 0% and *this condition lasts more than one minute*. This significantly decreases the performance of the migration process.
Here is the pic of the sub process:
[) and especially about [TSR](https://en.wikipedia.org/wiki/Terminate_and_stay_resident_p... |
54,509,350 | I want to write aws lambda function to fetch data from on premises oracle db and migrate to aurora db.
I tried :
```
var oracledb = require('oracledb-for-lambda');
var os = require('os');
var fs = require('fs');
'use strict';
str_host = os.hostname() + ' localhost\n';
fs.appendFile(process.env.HOSTALIASES,str_host ... | 2019/02/04 | [
"https://Stackoverflow.com/questions/54509350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951102/"
] | ***KeyNotFoundException ... Why?***
The distilled, core reason is that the `Equals` and `GetHashCode` methods are inconsistent. This situation is fixed by doing 2 things:
* Override `Equals` in `TestClass`
* Never modify a dictionary during iteration
+ It's that the key object/value is being modified
---
**`GetHa... | That is the expected behavior with your code. Then what is your wrong with your code?
Look at your Key Class. You are overriding your `GetHashCode()` and on top of that you are using a mutable value to calculate the `GetHashCode()` method (very very bad :( ).
```
public class TestClass
{
public int MyProperty { ... |
54,509,350 | I want to write aws lambda function to fetch data from on premises oracle db and migrate to aurora db.
I tried :
```
var oracledb = require('oracledb-for-lambda');
var os = require('os');
var fs = require('fs');
'use strict';
str_host = os.hostname() + ' localhost\n';
fs.appendFile(process.env.HOSTALIASES,str_host ... | 2019/02/04 | [
"https://Stackoverflow.com/questions/54509350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951102/"
] | >
> What I want to know is, why we got this error?
>
>
>
There are *guidelines* for GetHashCode, and there are *rules*. If you violate the guidelines, you get lousy performance. If you violate the *rules*, things break.
You are violating the *rules*. One of the *rules* of GetHashCode is *while an object is in a ... | That is the expected behavior with your code. Then what is your wrong with your code?
Look at your Key Class. You are overriding your `GetHashCode()` and on top of that you are using a mutable value to calculate the `GetHashCode()` method (very very bad :( ).
```
public class TestClass
{
public int MyProperty { ... |
33,630,400 | How do I extract two `i32`s from a single line of input in Rust? In Python I can read two `int`s like:
```python
a, b = map(int, input().split()) # "2 3" => a=2 and b=3
```
As of Rust 1.3.0, I can run the following to read one i32:
```rust
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok().expect... | 2015/11/10 | [
"https://Stackoverflow.com/questions/33630400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2370748/"
] | `&str` has a [`split_whitespace()`](http://doc.rust-lang.org/std/primitive.str.html#method.split_whitespace) method which returns an iterator yielding parts of the target string separated by an arbitrary amount of whitespace, much like `split()` in Python. You can use the [`map()`](http://doc.rust-lang.org/std/iter/tra... | The Rust code is always going to be more verbose than the Python one. But since version 1.26, Rust also supports slice patterns as shown below. The code looks more readable in my opinion.
```
fn main() {
let a = "2 3";
if let [Ok(aa), Ok(aaa)] = &a.split(" ")
.map(|a| a.parse::... |
33,630,400 | How do I extract two `i32`s from a single line of input in Rust? In Python I can read two `int`s like:
```python
a, b = map(int, input().split()) # "2 3" => a=2 and b=3
```
As of Rust 1.3.0, I can run the following to read one i32:
```rust
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok().expect... | 2015/11/10 | [
"https://Stackoverflow.com/questions/33630400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2370748/"
] | `&str` has a [`split_whitespace()`](http://doc.rust-lang.org/std/primitive.str.html#method.split_whitespace) method which returns an iterator yielding parts of the target string separated by an arbitrary amount of whitespace, much like `split()` in Python. You can use the [`map()`](http://doc.rust-lang.org/std/iter/tra... | You can use the [`text_io`](https://crates.io/crates/text_io) crate which offers a macro `read!` to read from standard input to produce tuples:
```
#[macro_use] extern crate text_io;
let (a, b): (i32, i32);
scan!("{} {}", a, b);
```
You can also read the values one by one
```
#[macro_use] extern crate text_io;
let ... |
33,630,400 | How do I extract two `i32`s from a single line of input in Rust? In Python I can read two `int`s like:
```python
a, b = map(int, input().split()) # "2 3" => a=2 and b=3
```
As of Rust 1.3.0, I can run the following to read one i32:
```rust
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok().expect... | 2015/11/10 | [
"https://Stackoverflow.com/questions/33630400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2370748/"
] | You can use the [`text_io`](https://crates.io/crates/text_io) crate which offers a macro `read!` to read from standard input to produce tuples:
```
#[macro_use] extern crate text_io;
let (a, b): (i32, i32);
scan!("{} {}", a, b);
```
You can also read the values one by one
```
#[macro_use] extern crate text_io;
let ... | The Rust code is always going to be more verbose than the Python one. But since version 1.26, Rust also supports slice patterns as shown below. The code looks more readable in my opinion.
```
fn main() {
let a = "2 3";
if let [Ok(aa), Ok(aaa)] = &a.split(" ")
.map(|a| a.parse::... |
14,259,660 | I am calling a python script from within a shell script. The python script returns error codes in case of failures.
How do I handle these error codes in shell script and exit it when necessary? | 2013/01/10 | [
"https://Stackoverflow.com/questions/14259660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202325/"
] | The exit code of last command is contained in `$?`.
Use below pseudo code:
```
python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
#Handle failure
#exit if required
fi
``` | You mean [the `$?` variable](http://tldp.org/LDP/abs/html/exit-status.html)?
```
$ python -c 'import foobar' > /dev/null
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named foobar
$ echo $?
1
$ python -c 'import this' > /dev/null
$ echo $?
0
``` |
14,259,660 | I am calling a python script from within a shell script. The python script returns error codes in case of failures.
How do I handle these error codes in shell script and exit it when necessary? | 2013/01/10 | [
"https://Stackoverflow.com/questions/14259660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202325/"
] | The exit code of last command is contained in `$?`.
Use below pseudo code:
```
python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
#Handle failure
#exit if required
fi
``` | Please use logic below to process script execution result:
```
python myPythonScript.py
# $? = is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure.
if [ $? -eq 0 ]
then
echo "Successfully executed script"
else
# Redirect stdout from echo co... |
21,517,740 | I am new to Python having come from mainly Java programming.
I am currently pondering over how classes in Python are instantiated.
I understand that `__init__()`: is like the constructor in Java. However, sometimes python classes do not have an `__init__()` method which in this case I assume there is a default const... | 2014/02/02 | [
"https://Stackoverflow.com/questions/21517740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020869/"
] | >
> I understand that `__init__()`: is like the constructor in Java.
>
>
>
To be more precise, in Python `__new__` is the constructor method, `__init__` is the initializer. When you do `SomeClass('foo', bar='baz')`, the `type.__call__` method basically does:
```
def __call__(cls, *args, **kwargs):
instance = ... | This answer pertains to new-style Python classes, which subclass `object`. New-style classes were added in 2.2, and they're the only kind of class available in PY3.
```
>>> print object.__doc__
The most base type
```
The class itself is an instance of a metaclass, which is usually `type`:
```
>>> print type.__doc_... |
21,517,740 | I am new to Python having come from mainly Java programming.
I am currently pondering over how classes in Python are instantiated.
I understand that `__init__()`: is like the constructor in Java. However, sometimes python classes do not have an `__init__()` method which in this case I assume there is a default const... | 2014/02/02 | [
"https://Stackoverflow.com/questions/21517740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020869/"
] | >
> I understand that `__init__()`: is like the constructor in Java.
>
>
>
To be more precise, in Python `__new__` is the constructor method, `__init__` is the initializer. When you do `SomeClass('foo', bar='baz')`, the `type.__call__` method basically does:
```
def __call__(cls, *args, **kwargs):
instance = ... | Attributes of Python objects are generally stored in a dictionary, just like the ones you create with `{}`. Since you can add new items to a dictionary at any time, you can add attributes to an object at any time. And since any type of object can be stored in a dictionary without previous declaration of type, any type ... |
21,517,740 | I am new to Python having come from mainly Java programming.
I am currently pondering over how classes in Python are instantiated.
I understand that `__init__()`: is like the constructor in Java. However, sometimes python classes do not have an `__init__()` method which in this case I assume there is a default const... | 2014/02/02 | [
"https://Stackoverflow.com/questions/21517740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2020869/"
] | Attributes of Python objects are generally stored in a dictionary, just like the ones you create with `{}`. Since you can add new items to a dictionary at any time, you can add attributes to an object at any time. And since any type of object can be stored in a dictionary without previous declaration of type, any type ... | This answer pertains to new-style Python classes, which subclass `object`. New-style classes were added in 2.2, and they're the only kind of class available in PY3.
```
>>> print object.__doc__
The most base type
```
The class itself is an instance of a metaclass, which is usually `type`:
```
>>> print type.__doc_... |
56,760,023 | I am trying yo use a PyTorch library SparseConvNet (<https://github.com/facebookresearch/SparseConvNet>) in Google Colaboratory. In order to install it properly, you need to first install Conda, and then using Conda install the SparseConvNet package. Here is the code I am using (following the instructions from scn read... | 2019/06/25 | [
"https://Stackoverflow.com/questions/56760023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11627002/"
] | You can specify the directory for conda to install to using
```
conda install -p path_to_your_dir
```
So, you can mount your google drive and conda install there to make it permanent. | The whole environment that Google Colaboratory runs your notebooks is not permanent, it is one of their premises. If you need a persistent environment consider running Jupyter directly on a Google Cloud Compute Engine VM, they have pre-built images with everything configured [here](https://cloud.google.com/deep-learnin... |
56,760,023 | I am trying yo use a PyTorch library SparseConvNet (<https://github.com/facebookresearch/SparseConvNet>) in Google Colaboratory. In order to install it properly, you need to first install Conda, and then using Conda install the SparseConvNet package. Here is the code I am using (following the instructions from scn read... | 2019/06/25 | [
"https://Stackoverflow.com/questions/56760023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11627002/"
] | You can specify the directory for conda to install to using
```
conda install -p path_to_your_dir
```
So, you can mount your google drive and conda install there to make it permanent. | Unfortunately no. Google colab machine will erase after some time. It is a docker inside, and every time you start the GC it will start a new docker image. But you can connect to your local machine via colab. Check the option on Connect button. |
58,131,697 | While reading a file in python, I was wondering how to get the next `n` lines when we encounter a line that meets my condition.
Say there is a file like this
```
mangoes:
1 2 3 4
5 6 7 8
8 9 0 7
7 6 8 0
apples:
1 2 3 4
8 9 0 9
```
Now whenever we find a line starting with mangoes, I want to be able to read all the... | 2019/09/27 | [
"https://Stackoverflow.com/questions/58131697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886357/"
] | just repeat what you did
```
if (line.startswith("mangoes:")):
for i in range(n):
print(next(ifile))
``` | Unless it's a huge file and you don't want to read all lines into memory at once you could do something like this
```py
n = 4
with open(fn) as f:
lines = f.readlines()
for idx, ln in enumerate(lines):
if ln.startswith("mangoes"):
break
mangoes = lines[idx:idx+n]
```
This would give you a list of ... |
58,131,697 | While reading a file in python, I was wondering how to get the next `n` lines when we encounter a line that meets my condition.
Say there is a file like this
```
mangoes:
1 2 3 4
5 6 7 8
8 9 0 7
7 6 8 0
apples:
1 2 3 4
8 9 0 9
```
Now whenever we find a line starting with mangoes, I want to be able to read all the... | 2019/09/27 | [
"https://Stackoverflow.com/questions/58131697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886357/"
] | just repeat what you did
```
if (line.startswith("mangoes:")):
for i in range(n):
print(next(ifile))
``` | With [`itertools.islice`](https://docs.python.org/3/library/itertools.html#itertools.islice) feature:
```
from itertools import islice
with open('yourfile') as ifile:
n = 4
for line in ifile:
if line.startswith('mangoes:'):
mango_lines = list(islice(ifile, n))
```
From your input sample ... |
27,528,566 | I am trying to return a python dictionary to the view with AJAX and reading from a JSON file, but so far I am only returning `[object Object],[object Object]`...
and if I inspect the network traffic, I can indeed see the correct data.
So here is how my code looks like. I have a class and a method which based on the... | 2014/12/17 | [
"https://Stackoverflow.com/questions/27528566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731280/"
] | I think you're getting confused because you actually have two tables of
data linked by a common ID:
```
library(dplyr)
df <- tbl_df(df)
years <- df %>%
filter(attributes == "YR") %>%
select(id = ID, year = values)
years
#> Source: local data frame [6 x 2]
#>
#> id year
#> 1 1 2014
#> 2 2 2013
#> 3 3 2... | I misunderstood the structure of your dataset initially. Thanks to the comments below I realize your data needs to be restructured.
```
# split the data out
df1 <- df[df$attributes == "AU",]
df2 <- df[df$attributes == "YR",]
# just keeping the columns with data as opposed to the label
df3 <- merge(df1, df2, by="ID")[... |
27,528,566 | I am trying to return a python dictionary to the view with AJAX and reading from a JSON file, but so far I am only returning `[object Object],[object Object]`...
and if I inspect the network traffic, I can indeed see the correct data.
So here is how my code looks like. I have a class and a method which based on the... | 2014/12/17 | [
"https://Stackoverflow.com/questions/27528566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731280/"
] | Here's a possible `data.table` solution
I would also suggest to create some aggregated data set with separated columns. For example:
```
library(data.table)
(subdf <- as.data.table(df)[, .(N.AU = sum(attributes == "AU"),
Year = values[attributes == "YR"]) , ID])
# ID N.AU Year
# 1: ... | I misunderstood the structure of your dataset initially. Thanks to the comments below I realize your data needs to be restructured.
```
# split the data out
df1 <- df[df$attributes == "AU",]
df2 <- df[df$attributes == "YR",]
# just keeping the columns with data as opposed to the label
df3 <- merge(df1, df2, by="ID")[... |
27,528,566 | I am trying to return a python dictionary to the view with AJAX and reading from a JSON file, but so far I am only returning `[object Object],[object Object]`...
and if I inspect the network traffic, I can indeed see the correct data.
So here is how my code looks like. I have a class and a method which based on the... | 2014/12/17 | [
"https://Stackoverflow.com/questions/27528566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731280/"
] | I think you're getting confused because you actually have two tables of
data linked by a common ID:
```
library(dplyr)
df <- tbl_df(df)
years <- df %>%
filter(attributes == "YR") %>%
select(id = ID, year = values)
years
#> Source: local data frame [6 x 2]
#>
#> id year
#> 1 1 2014
#> 2 2 2013
#> 3 3 2... | Here's a possible `data.table` solution
I would also suggest to create some aggregated data set with separated columns. For example:
```
library(data.table)
(subdf <- as.data.table(df)[, .(N.AU = sum(attributes == "AU"),
Year = values[attributes == "YR"]) , ID])
# ID N.AU Year
# 1: ... |
56,924,174 | I'm importing files from the following folder inside a python code:
```
Mask_RCNN
-mrcnn
-config.py
-model.py
-__init__.py
-utils.py
-visualize.py
```
I'm using the following imports:
These work ok:
from Mask\_RCNN.mrcnn.config import Config
from Mask\_RCNN. mrcnn import utils
These give me... | 2019/07/07 | [
"https://Stackoverflow.com/questions/56924174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10028453/"
] | You get an error for the 2nd import, where you omit `Mask_RCNN` from the package name.
Try changing the lines to:
```
from Mask_RCNN.mrcnn import visualize
import Mask_RCNN.mrcnn.model as modellib
``` | Use this line before importing the libraries
```
sys.path.append("Mask_RCNN/")
``` |
25,012,210 | Steps I followed to build WebRTC for Android in UBUNTU 13.10 env.
Check out the code:
```
gclient config https://webrtc.googlecode.com/svn/trunk
echo "target_os = ['android', 'unix']" >> .gclient
gclient sync --nohooks
cd trunk
source ./build/android/envsetup.sh
export GYP_DEFINES="build_with_libjingle=1 build_with_c... | 2014/07/29 | [
"https://Stackoverflow.com/questions/25012210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580291/"
] | I don't think you're doing anything wrong.
your error is mentioned [here](https://code.google.com/p/webrtc/issues/detail?id=3622) and i guess it will be fixed.
```
"Yes, chrome has moved to BoringSSL from OpenSSL, which causes some problems in WebRTC Android. We are looking into it."
```
You can try an older revisi... | Follow this [example](http://simonguest.com/2013/08/06/building-a-webrtc-client-for-android/), i have tried it and work success fully.
Only need to make one change is the link provided in this example for gclient config command is older one. Follow your link gclient config <http://webrtc.googlecode.com/svn/trunk>
Als... |
20,712,314 | I have a simple python code
```
path1 = //path1/
path2 = //path2/
write_html = """
<form name="input" action="copy_file.php" method="get">
"""
Outfile.write(write_html)
```
Now copy\_file.php copies files from one folder to another. I want the python path1 and path2 variable values to be passed to php script. **H... | 2013/12/20 | [
"https://Stackoverflow.com/questions/20712314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538688/"
] | ```
write_html = """
<form name="input" action="copy_file.php" method="get">
<input type="hidden" name="path1" value="{0}" />
<input type="hidden" name="path2" value="{1}" />
<input type="button" name="button" value="onClick="copyfile('{0}', '{1}')"/>
<script> function moveFile(path1, path2){ ...} </script>
""".f... | >
> I want the python path1 and path2 variable values to be passed to php script.
>
>
>
Doable:
```
write_html = """
<form name="input" action="copy_file.php" method="get">
<input type="hidden" name="path1" value="%s" />
<input type="hidden" name="path2" value="%s" />
""" % (path1, path2)
```
My python is a b... |
20,712,314 | I have a simple python code
```
path1 = //path1/
path2 = //path2/
write_html = """
<form name="input" action="copy_file.php" method="get">
"""
Outfile.write(write_html)
```
Now copy\_file.php copies files from one folder to another. I want the python path1 and path2 variable values to be passed to php script. **H... | 2013/12/20 | [
"https://Stackoverflow.com/questions/20712314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538688/"
] | ```
write_html = """
<form name="input" action="copy_file.php" method="get">
<input type="hidden" name="path1" value="{0}" />
<input type="hidden" name="path2" value="{1}" />
<input type="button" name="button" value="onClick="copyfile('{0}', '{1}')"/>
<script> function moveFile(path1, path2){ ...} </script>
""".f... | Passing arguments to your PHP script the way you do looks like for me to be done like:
in python file
```
path1 = '//path1/'
path2 = '//path2/'
write_html = """
<form name="input" action="copy_file.php" method="get">
<input type="hidden" name="path1" value="%s"/>
<input type="hidden" name="path2" value="%s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.