Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,904,200 | 49,544,755 |
Memory error in Python while using fractions
|
<p>I am using the stern-brocot sequence to generate fractions. These fractions have been appended to list. Now I need to modify this list of fractions as the problem requires me to satisfy 2 conditions on the fractions that exist in the list.</p>
<p>1) for every simplified fraction <code>a/b</code> that is present in the list, <code>b/2a</code> must also be present.</p>
<p>2) for every 2 simplified fractions <code>a/b</code> and <code>c/d</code>, <code>(a+b)/(c+d)</code>
should also be present.</p>
<p>I've written to following code to just do that.</p>
<pre><code># Python program to print
# Brocot Sequence
from fractions import Fraction
import math
class MyFraction: # This class has been defined to return unsimplified fractions as they are as the'd get simplified using the fractions module
def __init__(self, numerator=1, denominator=1):
self.numerator = numerator
self.denominator = denominator
def get_fraction(self):
return Fraction(numerator=self.numerator, denominator=self.denominator)
def __repr__(self):
return '{}/{}'.format(self.numerator, self.denominator)
def SternSequenceFunc(BrocotSequence, n):
# loop to create sequence
for i in range(1, n):
considered_element = BrocotSequence[i]
precedent = BrocotSequence[i-1]
# adding sum of considered
# element and it's precedent
BrocotSequence.append(considered_element + precedent)
# adding next considered element
BrocotSequence.append(considered_element)
# printing sequence..
for i in range(0, n):
print(BrocotSequence[i] , end=" ")
print("\n")
# Function to determine if a fraction is simplified or not
def is_simplified(frac):
if frac == Fraction(frac.numerator, frac.denominator):
return True
else:
return False
# Function to modify the set to satisfy the given conditions
def modify_set(list_fractions):
# To satisfy the 1st condition
for fraction in list_fractions:
numerator = fraction.numerator
denominator = fraction.denominator
list_fractions.append(MyFraction(denominator, 2*numerator))
# To satisfy the 2nd condition
for fraction in list_fractions:
if is_simplified(fraction):
for frac in list_fractions:
if frac != fraction:
if is_simplified(frac):
f = MyFraction((fraction.numerator+frac.numerator), (fraction.denominator+frac.denominator))
list_S.append(f)
while True:
list_S = []
count = 0
# Driver code
n = int(input("Enter value of n : "))
BrocotSequence = []
# adding first two element
# in the sequence
BrocotSequence.append(1)
BrocotSequence.append(1)
SternSequenceFunc(BrocotSequence, n)
for i in range(1, n):
list_S.append(Fraction(BrocotSequence[i], BrocotSequence[i-1])) # Appending the list with fractions generated from stern-brocot sequence
modify_set(list_S)
print("\n Printing all fractions : \n")
for fraction in list_S:
count = count + 1
print("\n", fraction)
print("Number of fractions: {}".format(count))
</code></pre>
<p>After running this code, I got a <code>Memory Error</code> while running the <code>modify_set</code> function. I don't understand why. Can anyone help me understand why and how to solve this?</p>
<p>Thanks in advance.</p>
|
<p>You're adding to a <code>list</code> as you iterate it here:</p>
<pre><code>for fraction in list_fractions:
numerator = fraction.numerator
denominator = fraction.denominator
list_fractions.append(MyFraction(denominator, 2*numerator))
</code></pre>
<p>Each time you pull one element from <code>list_fractions</code>, then add a new one (which will eventually be iterated in turn). So this loop never ends, and the <code>list</code> grows forever (or until the <code>MemoryError</code> anyway).</p>
<p>Similarly, in your next loop in that function (not that you'd ever reach it), you've got a nested loop over <code>list_fractions</code>, and while it's less obvious here, it would also be infinite, because each iteration appends to <code>list_S</code> (which is a global), which was passed as the <code>list_fractions</code> argument, so they're both aliases to the same <code>list</code> (Python function calls don't copy the contents of their arguments, only the reference itself, so anything aside from rebinding <code>list_fractions</code> to a new object would modify <code>list_S</code> too).</p>
<p>I don't know your intended logic, but if the goal is to only add new entries for the existing entries (and not process the added entries), a solution would be to iterate over a shallow copy of the <code>list</code>, e.g.:</p>
<pre><code># list_fractions[:] returns a new list with references to the same values as
# the original list, but unaffected by subsequent additions and removals
for fraction in list_fractions[:]:
numerator = fraction.numerator
denominator = fraction.denominator
list_fractions.append(MyFraction(denominator, 2*numerator))
</code></pre>
<p>Your nested loop will be more complicated (depending on whether the inner loop should process an updated copy of <code>list_fractions</code> or not); I'll leave you to determine the correct course of action.</p>
|
python|python-3.x|fractions
| 1 |
1,904,201 | 20,914,013 |
Implementing Memoization
|
<p>After viewing code samples from RosettaCode and Literate Programming I am still confused at how to implement memoization for a problem I am doing.</p>
<p>In the problem, I perform a magic() formula, similar to a Collatz Sequence on the number, and eventually the sequence either yields 1,2,or 3.</p>
<p>for example it might go: </p>
<pre><code>123849 -> 2342453 -> 1233453 ->3
</code></pre>
<p>I would like to store the values after I calculate them, so that as I perform magic() on increasingly big numbers, the run time is reduced. So for instance, after doing magic(123849), I would like to store 123849, 2342453, and 1233453. If any of these numbers comes up in the future, instead of having to perform the magic function, it will immediately output 3. </p>
<pre><code>ones=[]
twos=[]
threes=[]
def magic(x):
# Memoization
if ones.count(x)>0: return 1
if twos.count(x)>0: return 2
if threes.count(x)>0: return 3
sequence=[]
<generate magic sequence, add each value to sequence>
# Add each sequence to the appropriate list
if final_value==1: ones.extend(sequence)
if final_value==2: twos.extend(sequence)
if final_value==3: threes.extend(sequence)
return final_value
</code></pre>
<p>My question: is there a better (more efficient/faster) way of implementing this memoization? Can I use lists instead of dicts?</p>
<ul>
<li>I have read this: <a href="https://stackoverflow.com/questions/1988804/what-is-memoization-and-how-can-i-use-it-in-python?rq=1">What is memoization and how can I use it in Python?</a> and understand that you are normally supposed to use dicts. I was just wondering if there is a big difference between using lists and dicts for memoization.</li>
</ul>
|
<p>Definitely check out <code>functools.lru_cache</code>, the Python stdlib's memoization implementation: <a href="http://docs.python.org/dev/library/functools.html#functools.lru_cach" rel="nofollow">http://docs.python.org/dev/library/functools.html#functools.lru_cach</a></p>
|
python|memoization
| 1 |
1,904,202 | 53,661,536 |
Google signin API using oauth Post Method in python flask server
|
<p>I got question about implementing google login. I was able to implement Google Login button on my react app using an open source library called <a href="https://i.stack.imgur.com/awxQj.png" rel="nofollow noreferrer">react-google-login</a>. I was able to set up the backend server using python flask. I host my api method on the api on Heroku: <a href="http://arrangement-server.herokuapp.com/login" rel="nofollow noreferrer">http://arrangement-server.herokuapp.com/login</a>.
And my react app runs successfully locally, and I am able to use login-in button. But, my issue is that my server displays the following error:</p>
<pre><code>Method not Allowed.
</code></pre>
<p>Is this because it is post method? </p>
<p>Why is it my Server shows me that that method is not allowed?</p>
<p><a href="https://i.stack.imgur.com/awxQj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awxQj.png" alt="enter image description here"></a></p>
<p>Even though on the client side it runs fine, and I am able to see user profile and user information.</p>
<p>Here's the code to my backend server, you can find it at <a href="https://github.com/arrangement-io/arrangethat-io-server/blob/master/app.py" rel="nofollow noreferrer">Github</a>:</p>
<pre><code>@app.route("/login", methods=['POST'])
def login():
data = request.json
session['access_token'] = data['access_token'], ''
return jsonify({'message':'You are logged in.'})
</code></pre>
|
<p>Your "login" endpoint will accept only "POST" HTTP requests. Because of this line:</p>
<pre><code>@app.route("/login", methods=['POST'])
</code></pre>
<p>When you try to open your page in a browser - the browser will send the "GET" HTTP request to that URL.</p>
<p>That is why you are getting "Method Not Allowed" error.
Take a look at my answer on upwork for more details.</p>
|
python|flask|google-signin
| 3 |
1,904,203 | 53,781,227 |
missing redis library when redis is installed
|
<p>I have redis and celery python libraries installed. I have redis server installed and running. using bash i can run <code>python</code> and <code>import redis</code> without errors. I have python-celery-common installed. I am using PyCharm and WSL. For some reason when i create tasks.py and try to run <code>celery -A tasks worker --loglevel=info
</code> in bash i get the following stack trace (note the python3 in the path to celery when i am running python 2.7 - i have a feeling this is important but not sure how, or how to change):</p>
<pre><code>Traceback (most recent call last):
File "/usr/bin/celery", line 26, in <module>
load_entry_point("celery", "console_scripts", "celery")()
File "/usr/lib/python3/dist-packages/celery/__main__.py", line 14, in main
_main()
File "/usr/lib/python3/dist-packages/celery/bin/celery.py", line 326, in main
cmd.execute_from_commandline(argv)
File "/usr/lib/python3/dist-packages/celery/bin/celery.py", line 488, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/usr/lib/python3/dist-packages/celery/bin/base.py", line 281, in execute_from_commandline
return self.handle_argv(self.prog_name, argv[1:])
File "/usr/lib/python3/dist-packages/celery/bin/celery.py", line 480, in handle_argv
return self.execute(command, argv)
File "/usr/lib/python3/dist-packages/celery/bin/celery.py", line 412, in execute
).run_from_argv(self.prog_name, argv[1:], command=argv[0])
File "/usr/lib/python3/dist-packages/celery/bin/worker.py", line 221, in run_from_argv
return self(*args, **options)
File "/usr/lib/python3/dist-packages/celery/bin/base.py", line 244, in __call__
ret = self.run(*args, **kwargs)
File "/usr/lib/python3/dist-packages/celery/bin/worker.py", line 255, in run
**kwargs)
File "/usr/lib/python3/dist-packages/celery/worker/worker.py", line 99, in __init__
self.setup_instance(**self.prepare_args(**kwargs))
File "/usr/lib/python3/dist-packages/celery/worker/worker.py", line 122, in setup_instance
self.should_use_eventloop() if use_eventloop is None
File "/usr/lib/python3/dist-packages/celery/worker/worker.py", line 241, in should_use_eventloop
self._conninfo.transport.implements.async and
File "/usr/lib/python3/dist-packages/kombu/connection.py", line 832, in transport
self._transport = self.create_transport()
File "/usr/lib/python3/dist-packages/kombu/connection.py", line 576, in create_transport
return self.get_transport_cls()(client=self)
File "/usr/lib/python3/dist-packages/kombu/transport/redis.py", line 1009, in __init__
raise ImportError('Missing redis library (pip install redis)')
ImportError: Missing redis library (pip install redis)
</code></pre>
<p>output from bash when i run <code>python</code>:</p>
<pre><code>Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
</code></pre>
<p>output from <code>pip freeze</code></p>
<pre><code> amqp==2.3.2
asn1crypto==0.24.0
billiard==3.5.0.5
celery==4.2.1
cryptography==2.1.4
Django==1.11.11
djangorestframework==3.9.0
enum34==1.1.6
idna==2.6
ipaddress==1.0.17
keyring==10.6.0
keyrings.alt==3.0
kombu==4.2.2
psycopg2==2.7.4
pycrypto==2.6.1
pygobject==3.26.1
pytz==2018.7
pyxdg==0.25
redis==3.0.1
SecretStorage==2.3.1
six==1.11.0
sqlparse==0.2.4
vine==1.1.4
</code></pre>
|
<p>The more plausible problem is that in pycharm when you set up the interpreter you gave it the wrong path.You set it to /usr/bin/python3 instead of the path to python2 </p>
|
python|redis|pycharm|celery|windows-subsystem-for-linux
| 0 |
1,904,204 | 53,699,447 |
Parsing a log file by applying condition
|
<p>I have a debug log file as you can see below:</p>
<p>Sample file:</p>
<pre><code>DEBUG: Fri Dec 7 06:49:14 2018:16920 extra text
DEBUG: Fri Dec 7 06:49:14 2018:16920: start <ID>
DEBUG: Fri Dec 7 06:49:14 2018:16920: Final output is "output
output output
output"
DEBUG: extra lines
</code></pre>
<p>I want to fetch only the IDs and the final output as shown below.</p>
<p>Expected output:</p>
<pre><code><ID> "output
output output
output"
</code></pre>
<p>I would like to do this in either python or bash. Any help would be appreciated.
Thanks</p>
<p>Current code works for "final output" only. but I want to fetch IDs as well and there should be a way to distinguish (seperator) for each ID and their output.</p>
<pre><code>stream=open("debuglog.txt","r")
lines=stream.readlines()
flag = 0
for i in lines:
if "DEBUG:" in i:
flag = 0
if "final output is" in i:
flag = 1
if flag:
print(i)
</code></pre>
|
<p>Sample log file:</p>
<pre><code>DEBUG: Fri Dec 7 06:49:14 2018:16920 extra text
DEBUG: Fri Dec 7 06:49:14 2018:16920: start 12324
DEBUG: Fri Dec 7 06:49:14 2018:16920: Final output is "output output output output"
DEBUG: extra lines
</code></pre>
<p>Please find the code. Also, I am assuming you have only one instance of each ID and output</p>
<pre><code>import sys, re
stream=open("log","r")
lines=stream.readlines()
flag_ID = 0
flag_output = 0
flag_print = 1
for i in lines:
ID = re.match("DEBUG: [\w :]* start (\d+)", i)
output = re.match("DEBUG: [\w :]* Final output is \"([\w ]*)\"", i)
if ID:
flag_ID = 1
value_ID = ID.group(1)
if output:
flag_output = 1
value_output = output.group(1)
if flag_output == 1 and flag_ID == 1 and flag_print == 1:
print "{0} {1}".format(value_ID, value_output)
flag_print = 0
</code></pre>
<p>output</p>
<pre><code>12324 output output output output
</code></pre>
<p>Please tick mark and accept if this solves your problem ;)</p>
|
python|regex|bash|shell|text-processing
| 2 |
1,904,205 | 45,860,593 |
mongodb random sample strange behavior
|
<p>I am using:</p>
<pre><code>mongodb server 3.47
windows 10 64-bit
python 3.62 64-bit
pymongo 3.50
</code></pre>
<p>There are two record in "k" collection in "dict" database:</p>
<pre><code>{"text": "xdcdcdcd", "sent": "false"}
{"text": "vvrvrrrv", "sent": "true"}
</code></pre>
<p>I want to choose a random record which has "sent" equals false:</p>
<pre><code>from pymongo import MongoClient
client = MongoClient()
db = client.dict
k = db.k
item = list(k.aggregate([{"$sample": {"size": 1}}, {"$match": {"sent": False}}]))
</code></pre>
<p>The variable item should be "[{"_id":".....", "text": "xdcdcdcd", "sent": "false"}]", but I tried several times, sometimes it works fine, but sometimes it returns [].</p>
|
<p><a href="https://docs.mongodb.com/manual/aggregation/" rel="nofollow noreferrer">Mongo's aggregate</a> is a pipeline action. It means that it will apply your aggregate list one by one.</p>
<p>In your example, it does two steps(you have two elements in your lists):</p>
<pre><code>1. {"$sample": {"size": 1}}
2. {"$match": {"sent": False}}
</code></pre>
<p>The first step you get only one data(<code>size=1</code>), It's either <code>{"text": "xdcdcdcd", "sent": "false"}</code> or <code>{"text": "vvrvrrrv", "sent": "true"}</code>. </p>
<p>And then in step two you apply <code>"$match"</code>, there is 50% you will get <code>[]</code>(when you get <code>{"text": "vvrvrrrv", "sent": "true"}</code> in first step).</p>
<p>So if you set <code>{"size": 1}</code> you will always get what you expected.</p>
<p>But actually the <code>{"$sample": {"size": 1}}</code> is useless, just delete it.</p>
|
python|mongodb|random
| 2 |
1,904,206 | 54,982,255 |
Passing data to refresh_view_attrs. Python. Kivy
|
<p>How can I pass <code>data</code> from <code>RequestRecycleView</code> to <code>refresh_view_data</code>? I tried with global variables and instantiating <code>data</code> in <code>RequestRecycleView</code> but still can't trigger <code>refresh_view_data</code> by appending Observable <code>data</code>. It is working when I return <code>RequestRecycleView</code> as root but I want <code>ScreenManager</code> to be my root. </p>
<pre><code>from kivy.config import Config
Config.set('graphics', 'multisamples', '0')
from random import sample
from string import ascii_lowercase
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
kv = """
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManager:
transition: FadeTransition()
RequestsScreen:
<RequestRow@BoxLayout>
size_hint_y: None
orientation: 'vertical'
row_index: id_row_index.text
row_index:''
pos: self.pos
size: self.size
Label:
id: id_row_index
text: root.row_index
<RequestRecycleView@RecycleView>:
#id: rv
viewclass: 'RequestRow'
SelectableRecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
<RequestsScreen>
name: 'RequestsScreen'
BoxLayout:
orientation: 'vertical'
Label:
text: 'recycle'
RequestRecycleView:
"""
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
''' Adds selection and focus behaviour to the view. '''
class RequestRow(RecycleDataViewBehavior):
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
self.row_index = str(index)
self.row_content = data['text']
return super(RequestRow, self).refresh_view_attrs(
rv, index, data)
class ScreenManagement(ScreenManager):
pass
class RequestRecycleView(RecycleView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.data = []
for r in range(30):
row = {'text': ''.join(sample(ascii_lowercase, 6))}
self.data.append(row)
class RequestsScreen(Screen):
pass
Builder.load_string(kv)
sm = ScreenManagement()
sm.add_widget(RequestsScreen(name = 'requests'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
</code></pre>
|
<p>By modifying</p>
<pre><code><RequestRow@BoxLayout>
size_hint_y: None
orientation: 'vertical'
row_index: id_row_index.text
row_index:''
pos: self.pos
size: self.size
Label:
id: id_row_index
text: root.row_index
</code></pre>
<p>to</p>
<pre><code><RequestRow@BoxLayout>
text: 'abba'
size_hint_y: None
orientation: 'vertical'
row_index: id_row_index.text
row_index:''
pos: self.pos
size: self.size
Label:
id: id_row_index
text: self.parent.text
</code></pre>
<p>results in working code. Note that the dictionary keys in the <code>data</code> are expected to be attributes of the <code>viewclass</code>. The added <code>text</code> attribute in <code>RequestRow</code>, provides that attribute, and the <code>text: self.parent.text</code> in the <code>Label</code> places that text (from the <code>viewclass</code>) into the <code>Label</code>. Also, you can replace the lines:</p>
<pre><code>Builder.load_string(kv)
sm = ScreenManagement()
sm.add_widget(RequestsScreen(name = 'requests'))
</code></pre>
<p>with just:</p>
<pre><code>sm = Builder.load_string(kv)
</code></pre>
<p>since your <code>kv</code> file specifies the <code>ScreenManager</code> as the root object.</p>
|
python|kivy
| 0 |
1,904,207 | 73,717,556 |
How to swap column values on conditions in python polars?
|
<p>I have a data frame as below:</p>
<pre><code>df_n = pl.from_pandas(pd.DataFrame({'last_name':[np.nan,'mallesh','bhavik'],
'first_name':['a','b','c'],
'middle_name_or_initial':['aa','bb','cc']}))
</code></pre>
<p><a href="https://i.stack.imgur.com/Bu9K2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bu9K2.png" alt="enter image description here" /></a></p>
<p>Here I would like to find an observation which has First and Middle Name not NULL and Last Name is Null, in this case first_name should be swapped to last_name and middle_name should be swapped to first_name, and middle_name to be EMPTY.</p>
<p>expected output will be:</p>
<p><a href="https://i.stack.imgur.com/TTJ8d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TTJ8d.png" alt="enter image description here" /></a></p>
<p>I'm trying with this command:</p>
<pre><code>df_n.with_columns([
pl.when((pl.col('first_name').is_not_null()) & (pl.col('middle_name_or_initial').is_not_null()) & (pl.col('last_name').is_null())
).then(pl.col('first_name').alias('last_name')).otherwise(pl.col('last_name').alias('first_name')),
pl.when((pl.col('first_name').is_not_null()) & (pl.col('middle_name_or_initial').is_not_null()) & (pl.col('last_name').is_null())
).then(pl.col('middle_name_or_initial').alias('first_name')).otherwise('').alias('middle_name_or_initial')
]
)
</code></pre>
<p><a href="https://i.stack.imgur.com/ozO8N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ozO8N.png" alt="enter image description here" /></a></p>
<p>Here it is throwing a wrong output and any help ?</p>
|
<p>You can actually change the values of multiple columns within a single <code>when/then/otherwise</code> statement.</p>
<h4>The Algorithm</h4>
<pre class="lang-py prettyprint-override"><code>name_cols = ["last_name", "first_name", "middle_name_or_initial"]
(
df_n.with_column(
pl.when(
(pl.col("first_name").is_not_null())
& (pl.col("middle_name_or_initial").is_not_null())
& (pl.col("last_name").is_null())
)
.then(pl.struct([
pl.col('first_name').alias('last_name'),
pl.col('middle_name_or_initial').alias('first_name'),
pl.col('last_name').alias('middle_name_or_initial'),
]))
.otherwise(pl.struct(name_cols))
.alias('name_struct')
)
.drop(name_cols)
.unnest('name_struct')
)
</code></pre>
<pre><code>shape: (3, 3)
βββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββ
β last_name β first_name β middle_name_or_initial β
β --- β --- β --- β
β str β str β str β
βββββββββββββͺβββββββββββββͺβββββββββββββββββββββββββ‘
β a β aa β null β
βββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββ€
β mallesh β b β bb β
βββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββ€
β bhavik β c β cc β
βββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββ
</code></pre>
<h4>How it works</h4>
<p>To change the values of multiple columns within a single <code>when/then/otherwise</code> statement, we can use structs. But you must observe some rules with structs. In all your <code>then</code> and <code>otherwise</code> statements, your structs must have:</p>
<ul>
<li>the same field names</li>
<li>in the same order</li>
<li>with the same data type in corresponding fields.</li>
</ul>
<p>So, in both the <code>then</code> and <code>otherwise</code> statements, I'm going to create a struct with field names in this order:</p>
<ol>
<li>last_name: string</li>
<li>first_name: string</li>
<li>middle_name_or_initial: string</li>
</ol>
<p>In our <code>then</code> statement, I'm swapping values and using <code>alias</code> to ensure that my fields names are as stated above. (This is important.)</p>
<pre class="lang-py prettyprint-override"><code>.then(pl.struct([
pl.col('first_name').alias('last_name'),
pl.col('middle_name_or_initial').alias('first_name'),
pl.col('last_name').alias('middle_name_or_initial'),
]))
</code></pre>
<p>And in the <code>otherwise</code> statement, we'll simply name the existing columns that we want, in the order that we want - using the list <code>name_cols</code> that I created in a previous step.</p>
<pre class="lang-py prettyprint-override"><code>name_cols = ["last_name", "first_name", "middle_name_or_initial"]
...
.otherwise(pl.struct(name_cols))
</code></pre>
<p>Here's the result after the <code>when/then/otherwise</code> statement.</p>
<pre class="lang-py prettyprint-override"><code>name_cols = ["last_name", "first_name", "middle_name_or_initial"]
(
df_n.with_column(
pl.when(
(pl.col("first_name").is_not_null())
& (pl.col("middle_name_or_initial").is_not_null())
& (pl.col("last_name").is_null())
)
.then(pl.struct([
pl.col('first_name').alias('last_name'),
pl.col('middle_name_or_initial').alias('first_name'),
pl.col('last_name').alias('middle_name_or_initial'),
]))
.otherwise(pl.struct(name_cols))
.alias('name_struct')
)
)
</code></pre>
<pre><code>shape: (3, 4)
βββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββββββββββ
β last_name β first_name β middle_name_or_initial β name_struct β
β --- β --- β --- β --- β
β str β str β str β struct[3] β
βββββββββββββͺβββββββββββββͺβββββββββββββββββββββββββͺβββββββββββββββββββββββ‘
β null β a β aa β {"a","aa",null} β
βββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββββββ€
β mallesh β b β bb β {"mallesh","b","bb"} β
βββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββββββ€
β bhavik β c β cc β {"bhavik","c","cc"} β
βββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββββββ
</code></pre>
<p>Notice that our new struct <code>name_struct</code> has the values that we want - in the correct order.</p>
<p>Next, we will use <a href="https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.DataFrame.unnest.html#polars.DataFrame.unnest" rel="nofollow noreferrer"><code>unnest</code></a> to break the struct into separate columns. (But first, we must drop the existing columns so that we don't get 2 sets of columns with the same names.)</p>
<pre class="lang-py prettyprint-override"><code>name_cols = ["last_name", "first_name", "middle_name_or_initial"]
(
df_n.with_column(
pl.when(
(pl.col("first_name").is_not_null())
& (pl.col("middle_name_or_initial").is_not_null())
& (pl.col("last_name").is_null())
)
.then(pl.struct([
pl.col('first_name').alias('last_name'),
pl.col('middle_name_or_initial').alias('first_name'),
pl.col('last_name').alias('middle_name_or_initial'),
]))
.otherwise(pl.struct(name_cols))
.alias('name_struct')
)
.drop(name_cols)
.unnest('name_struct')
)
</code></pre>
<pre><code>shape: (3, 3)
βββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββ
β last_name β first_name β middle_name_or_initial β
β --- β --- β --- β
β str β str β str β
βββββββββββββͺβββββββββββββͺβββββββββββββββββββββββββ‘
β a β aa β null β
βββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββ€
β mallesh β b β bb β
βββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββ€
β bhavik β c β cc β
βββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββ
</code></pre>
|
python|python-polars
| 2 |
1,904,208 | 12,919,204 |
Python: Applying common keys from one Dictionary to another
|
<p>I am fairly new to dictionaries, so this is probably a fairly basic question.</p>
<p>Let's say I have two different dictionaries with similar elements.
Example:</p>
<pre><code> Dictionary1 = {'Bob' : 1, 'Mary' : 2, 'Sue' : 3, 'George' : 4}
Dictionary2 = {'Bob' : 1, 'Sue' : 2, 'Jill' : 3, 'Isaac' : 4, 'George' : 5}
</code></pre>
<p>I want to be able to take the intersection of the two dictionaries and apply the indices of the first dictionary to the second. So I want an output that looks something like this:</p>
<pre><code> DictionaryCombo = {'Bob' : 1, 'Sue' : 3, 'George' : 4}
</code></pre>
<p>Please excuse my formatting for my desired output, as I am not certain what it should look like, though I know that I want the key and value pairs of the intersection of the two dictionaries.</p>
|
<p>If you want to subset d1 so it only has elements present in d2</p>
<pre><code>d1 = {'Bob': 1, 'Mary': 2, 'Sue': 3, 'George': 4}
d2 = {'Bob': 101, 'Sue': 102, 'Jill': 103, 'Isaac': 104, 'George': 105}
{k: v for k, v in d1.items() if k in d2}
# {'Bob': 1, 'Sue': 3, 'George': 4}
</code></pre>
<p>Or you mention <em>apply</em>, so did you want to update values in d2?</p>
<pre><code>d2.update(d1)
print d2
# {'Sue': 3, 'Mary': 2, 'Jill': 103, 'Isaac': 104, 'Bob': 1, 'George': 4}
</code></pre>
<p>Or, if you really are starting with two lists (and not starting with dict's):</p>
<pre><code>el1 = ['Bob', 'Mary', 'Sue', 'George']
el2 = ['Bob', 'Sue', 'Jill', 'Isaac', 'George']
dict( (val, idx) for idx, val in enumerate(d1, start=1) if val in set(el2) )
#{'Bob': 1, 'Sue': 3, 'George': 4}
</code></pre>
<p>If you have two lists, one of keys, and one of values, and wish to make them a <code>dict</code>, then you can use <code>zip</code>:</p>
<pre><code>keys = ['Bob', 'Mary', 'Sue', 'George']
vals = [1, 2, 3, 4]
dict( zip(keys, vals) )
# {'Bob': 1, 'Mary': 2, 'Sue': 3, 'George': 4}
</code></pre>
|
python|dictionary
| 4 |
1,904,209 | 21,689,070 |
Form buttons routine with web.py
|
<p>I have a page with 3 buttons. When I press one, I want the page to tell me which button I pressed. In the end I want to toggle processes and run scripts from this page and instantly get the feedback next to the buttons. Like a control panel.</p>
<p>My problem is taking the button action, do something with it and return the result to the page with the buttons.</p>
<p>I've read the web.py forms tutorials and followed them. I also looked for examples in templetor, all forms there seem to handle a login routine or write the response to a database. Sometimes the response is shown on a new page but never in the same page next to the button.</p>
<p>There must be something I don't get about the form routine as I built it.</p>
<p><strong>The script:</strong></p>
<pre><code>#===============================================================================
# Imports
#===============================================================================
import web
import os
from web import form
#===============================================================================
# Start webPy environment
#===============================================================================
urls = ('/', 'index',
'/images/(.*)', 'images'
)
render = web.template.render('templates/')
button_resp = "temp"
#===============================================================================
# Menu buttons
#===============================================================================
my_form = form.Form(
form.Button("btn", id="Search planet", value="ipfact", html="Find Target", class_="ipfact"),
form.Button("btn", id="Lock on Target", value="lockta", html="Select planet to target", class_="lockta"),
form.Button("btn", id="Destroy all humans", value="deshum", html="Destroy all humans", class_="deshum")
)
#===============================================================================
# Classes
#===============================================================================
class index:
def GET(self):
form = my_form()
return render.index(form, button_resp)
def POST(self):
form = my_form()
userData = web.input()
if not form.validates():
return render.formtest(form)
else:
# Determine which colour LedBorg should display
if userData.btn == "ipfact":
button_resp = "Find Target"
print "ipfact"
elif userData.btn == "lockta":
button_resp = "Select planet to target"
print "lockta"
elif userData.btn == "deshum":
button_resp = "Destroy all humans"
print "deshum"
else:
button_resp = "Do nothing else - assume something fishy is going on..."
print "nothing"
# reload the web form ready for the next user input
raise web.seeother('/')
class images:
def GET(self,name):
ext = name.split(".")[-1] # Gather extension
cType = {
"png":"images/png",
"jpg":"images/jpeg",
"gif":"images/gif",
"ico":"images/x-icon" }
if name in os.listdir('images'): # Security
web.header("Content-Type", cType[ext]) # Set the Header
return open('images/%s'%name,"rb").read() # Notice 'rb' for reading images
else:
raise web.notfound()
#===============================================================================
# Run it!
#===============================================================================
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
</code></pre>
<p><strong>The index.html template file:</strong></p>
<pre><code>$def with (form, button_resp)
<!doctype html>
<html>
<head
<link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon">
<link rel="icon" href="/images/favicon.ico" type="image/x-icon">
</head>
<center>
<img src="/images/deathstar.jpg" width="256" height="256" >
<br>
<b>Welcome aboard!</b>
<br>
$button_resp
</center>
<form name="main" method="post">
$:form.render()
</form>
</html>
</code></pre>
|
<p>You must be talking about asynchronous requests where the web page can handle requests without refreshing the page. Not like the web.py examples like a login page.</p>
<p>Easy. Use jQuery for the job. The <a href="https://api.jquery.com/jQuery.ajax/" rel="nofollow">documentation</a> is more than enough to get you started. But here I will give you an example. </p>
<p>Add this code snippet to your .js file:</p>
<pre><code>$.ajax({
url: '/',
type: 'POST',
data: {
params: text
}).done(function(){
/* Do something */
});
</code></pre>
|
python|python-2.7|web.py
| 1 |
1,904,210 | 24,569,131 |
Python scraping from a complex HTML file
|
<p>I have a huge html file. I want to scrape certain info. from it. Basically there are some 2000 variables and each has some values. I need these values and variable names in this format -
varname1,val1,val2,...
varname2,val1,val2...
..
..</p>
<p>The values are in this format - </p>
<hr>
<pre><code><h2><span lang=EN-US>Element Values</span></h2>
<p class=MsoListParagraph><span lang=EN-US style='mso-no-proof:yes'>01 = 01<o:p></o:p></span></p>
<p class=MsoListParagraph><span lang=EN-US style='mso-no-proof:yes'>02<o:p></o:p></span></p>
.
.
.
<p class=MsoListParagraph style='line-height:normal'><span lang=EN-US
style='mso-no-proof:yes'>20[true]</span></p>
<p class=MsoListParagraph style='line-height:normal'><span lang=EN-US
style='font-size:6.0pt;mso-bidi-font-size:12.0pt'><o:p>&nbsp;</o:p></span></p>
<h2><span lang=EN-US>Element Notes</span></h2>
</code></pre>
<hr>
<p>I need the values 01=01,02,...,20[true]</p>
<p>The variable names are always in this format - </p>
<pre><code><span style='mso-no-proof:yes'>2716</span>
</code></pre>
<p>i.e 4 digits inside that span tag.</p>
<p>so 1 output could be 2716,01=01,02,...,20[true]</p>
|
<p>This will match the required tags (<code>span</code> tags with attribute <code>style</code> set to <code>mso-no-proof:yes</code>), it's then a matter of extracting the text.</p>
<pre><code>from bs4 import BeautifulSoup
html = """<h2><span lang=EN-US>Element Values</span></h2>
<p class=MsoListParagraph><span lang=EN-US style='mso-no-proof:yes'>01 = 01<o:p></o:p></span></p>
<p class=MsoListParagraph><span lang=EN-US style='mso-no-proof:yes'>02<o:p></o:p></span></p>
<p class=MsoListParagraph style='line-height:normal'><span lang=EN-US
style='mso-no-proof:yes'>20[true]</span></p>
<p class=MsoListParagraph style='line-height:normal'><span lang=EN-US
style='font-size:6.0pt;mso-bidi-font-size:12.0pt'><o:p>&nbsp;</o:p></span></p>
<h2><span lang=EN-US>Element Notes</span></h2>"""
soup = BeautifulSoup(html)
elements = soup.find_all(name='span', attrs={'style' : 'mso-no-proof:yes'})
print ','.join(e.text for e in elements)
</code></pre>
<p>Outputs:</p>
<pre><code>01 = 01,02,20[true]
</code></pre>
|
python|web-scraping|beautifulsoup
| 0 |
1,904,211 | 38,363,640 |
Why hash function on two different objects return same value?
|
<p>I used Spyder, run Python 2.7.</p>
<p>Just found interesting things:</p>
<ol>
<li>hash(-1) and hash(-2) both return -2, is there a problem? I though hash function on different object should return different values. I read previous posts that -1 is reserved as an error in Python.</li>
<li>hash('s') returns 1835142386, then hash(1835142386) returns the same value. Is this another problem?</li>
</ol>
<p>Thanks.</p>
|
<p>-1 is not "reserved as an error" in Python. Not sure what that would even mean. There are a huge number of programs you couldn't write simply and clearly if you weren't allowed to use -1.</p>
<p>"Is there a problem?" No. Hash functions do not need to return a different hash for every object. In fact, this is not possible, since there are many more possible objects than there are hashes. CPython's <code>hash()</code> has the nice property of returning its argument for non-negative numbers up to <code>sys.maxint</code>, which is why in your second question <code>hash(hash('s')) == hash('s')</code>, but that is an implementation detail.</p>
<p>The fact that -1 and -2 have the same hash simply means that using those values as, for example, dictionary keys will result in a hash conflict. Hash conflicts are an <em>expected situation</em> and are automatically resolved by Python, and the second key added would simply go in the next available slot in the dictionary. Accessing the key that was inserted second would then be slightly slower than accessing the other one, but in most cases, not <em>enough</em> slower that you'd notice.</p>
<p>It is possible to construct a huge number of unequal objects all with the same hash value, which would, when stored in a dictionary or a set, cause the performance of the container to deteriorate substantially because every object added would cause a hash collision, but it isn't something you will run into unless you go looking for it.</p>
|
python|hash
| 3 |
1,904,212 | 31,047,606 |
how to urlencode a value that is a python dictionary with encoded unicode characters
|
<p>I'm trying to make a url-encoded web request in python 2.7 where I want to send a list of python dictionaries that would be on the server decoded as a list of JSON objects.
In essence I'm making:</p>
<p><code>>>>urllib.urlencode({"param":"val", "items":[item1, item2] }, True)</code></p>
<p>where <code>item1</code> can be something like <code>{ "a": u"Ε‘".encode("utf8") }</code> (simplified for the example)</p>
<p>The problem arises because of the unicode characters.</p>
<p>If an <code>item1</code> is by itself encoded, you get something meaningful:</p>
<pre><code>>>>urllib.urlencode(item1)
'a=%C5%A1'
</code></pre>
<p>however, if I call <code>urllib.urlencode({"test": item1})</code> I get a mess:</p>
<pre><code>'test=%7B%27a%27%3A+%27%5Cxc5%5Cxa1%27%7D'
</code></pre>
<p>In this case, the unicode character is no longer encoded as <code>%C5%A1</code> but as a longer sequence that is then incorrectly decoded on the server side.</p>
<p>Does anybody have a suggestion how to properly transform complex dictionary values (i.e. <code>item1</code>) before calling <code>urlencode</code> to avoid this issue?</p>
|
<p>One way or another you need to decode anything that was encoded before re-encoding Here is one approach:</p>
<pre><code>dictionary = {"test": item1}
urllib.urlencode(dict([(k, decode_operation(v)) for k, v in dictionary.iteritems()]))
</code></pre>
|
python|dictionary|unicode|urllib
| 0 |
1,904,213 | 40,076,160 |
Rectangle collision in pygame? (Bumping rectangles into each other)
|
<p>I decided to move that Squarey game to pygame, and now I have 2 rectangles that can move around and bump into the walls. However, the rectangles can move right through each other. How would I make them bump into each other and stop?
My code:</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption("Squarey")
done = False
is_red = True
x = 30
y = 30
x2 = 100
y2 = 30
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_red = not is_red
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 3
if pressed[pygame.K_DOWN]: y += 3
if pressed[pygame.K_LEFT]: x -= 3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_w]: y2 -= 3
if pressed[pygame.K_s]: y2 += 3
if pressed[pygame.K_a]: x2 -= 3
if pressed[pygame.K_d]: x2 += 3
if y < 0:
y += 3
if x > 943:
x -= 3
if y > 743:
y -= 3
if x < 0:
x += 3
if y2 < 0:
y2 += 3
if x2 > 943:
x2 -= 3
if y2 > 743:
y2 -= 3
if x2 < 0:
x2 += 3
screen.fill((0, 0, 0))
if is_red: color = (252, 117, 80)
else: color = (168, 3, 253)
if is_red: color2 = (0, 175, 0)
else: color2 = (255, 255, 0)
rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
rect2 = pygame.draw.rect(screen, color2, pygame.Rect(x2, y2, 60, 60))
pygame.display.flip()
clock.tick(60)
pygame.quit()
</code></pre>
|
<p>To check for collisions, try something like this:</p>
<pre><code>def doRectsOverlap(rect1, rect2):
for a, b in [(rect1, rect2), (rect2, rect1)]:
# Check if a's corners are inside b
if ((isPointInsideRect(a.left, a.top, b)) or
(isPointInsideRect(a.left, a.bottom, b)) or
(isPointInsideRect(a.right, a.top, b)) or
(isPointInsideRect(a.right, a.bottom, b))):
return True
return False
def isPointInsideRect(x, y, rect):
if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
return True
else:
return False
</code></pre>
<p>Then, while moving them, you can call</p>
<pre><code>if doRectsOverlap(rect1, rect2):
x -= 3
y -= 3
rect1 = pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
</code></pre>
<p>Or something like that.</p>
|
python|pygame|collision|rectangles
| 1 |
1,904,214 | 29,066,409 |
Django1.7 : 'list' object is not callable
|
<p>I'm getting 'list' object is not callable.</p>
<p>My models.py </p>
<pre><code>class KeyValues(models.Model):
value=models.IntegerField(max_length=1,blank=True)
class Key(models.Model):
position=models.IntegerField(max_length=1,default=0,blank=True)
keyValues= key=models.ManyToManyField(KeyValues)
class FileDetails(models.Model):
fileId = models.CharField(max_length = 100,primary_key=True,db_index=True)
key=models.ManyToManyField(Key)
</code></pre>
<p>My code :</p>
<pre><code>def Arrangement(fileid,key,user):
Key=[]
NewKey=[]
Key[:0]=key
length=len(key)
for i in range (0,length):
NewKey.append(str(ord(key[i])%5))
pos=int(ord(key[i])%5)
key_values=KeyValues(value=key[i])
key_values.save()
KeY=Key(position=pos)
KeY.save()
KeY.keyValues.add(key_values)
KeY.save()
filedetails=FileDetails.objects.get(fileId=fileid)
filedetails.key.add(KeY)
filedetails.save()
</code></pre>
<p>I'm getting 'list' object is not callable at </p>
<blockquote>
<p>KeY=Key(position=pos)</p>
</blockquote>
<p>Why i'm getting such an error ? How can i correct it ?</p>
|
<p>You initialized a list named <code>Key</code>, and you also have a class named <code>Key</code>. Rename the <code>Key</code> variable in the first line in your <code>Arrangement</code> method to something else.</p>
<p>Your naming conventions is very confusing, by the way. Try to follow <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a> or at least name your variables in lowercase.</p>
|
python|django|list|python-2.7|django-1.7
| 1 |
1,904,215 | 29,112,003 |
Saving pygame display as pygame.Subsurface
|
<p>I have created a program where small tiles are printed to the screen. The tiles are reprinted every iteration of my game loop. It works fine the way it is but I think it could cause problems if I used more tiles on a slower computer. My idea to improve it is save all the tiles as a joined subsurface rather than individual subsurfaces. That way I'd only have to print one subsurface to the display oppose to x many objects.<img src="https://i.stack.imgur.com/3If5U.png" alt="enter image description here"> This is how the screen looks. <strong>How do I save the screen as a subsurface?</strong></p>
|
<p>It's rather simple to accomplish this. First, take your map building operation out of the game loop and place it just before. Secondly, after the map has been blit (to what I'm assuming was your screen but any surface will work), simply hold that surface as a variable.</p>
<p>Example:</p>
<pre><code>map = screen.subsurface(screen.get_rect())
</code></pre>
<p>Then at the end of your game loop, simply blit this map before blitting any other items.</p>
<pre><code>screen.blit(map,(0,0))
screen.blit(player.image,(player.rect.x,player.rect.y))
for monster in monster_list:
screen.blit(monster.image,(monster.rect.x,monster.rect.y)) # of course if you're using sprites, it's be best to just use group.draw()
pygame.display.update()
</code></pre>
<p>This way all entities end up on top of your map surface.</p>
|
python|pygame
| 0 |
1,904,216 | 8,801,104 |
creating gtalk type app using django
|
<p>I am learning Python and Django. I want to create a Gtalk type of application using Django and Python. Please tell me where I can find documentation that will help me build my application. Mainly I want to know how to determine when anyone logs in if their friends is online, busy, offline, etc. I also would like to know how to respond to those events. Thanks in advance.</p>
|
<p>you can start with learning the <a href="http://xmpp.org/" rel="nofollow">XMPP</a> protocol, or learning to use <a href="http://xmpppy.sourceforge.net/" rel="nofollow">any of the python libraries that deal with XMPP</a>.</p>
<p>I referred you to XMPP because this is the protocol used by GTalk. there are other instant messaging protocols that can be used.</p>
|
python|django|xmpp|instant-messaging
| 1 |
1,904,217 | 52,059,163 |
GUIDED to LOITER Mode
|
<p>I'm trying to change the guided mode to loiter when vehicle reaches a point.
but as soon as mode changes , the altitude is becoming zero - vehicle crashes in
simulator.</p>
<p>Do i have specify any altitude before changing to loiter mode ?</p>
<pre><code>#change the mode to loiter and wait for 10 seconds
vehicle.mode = VehicleMode("LOITER")
while not vehicle.mode.name == "LOITER":
print "Waiting for vehicle to change to LOITER Mode"
sleep(1)
</code></pre>
|
<p>Others who are facing the same issue.
assiging 1500 to throttle (after takeoff ?) will solve the issue.</p>
<pre><code>armAndTakeOff()
#set the channel overrides which avoids crashing when mode changed to loiter
print "setting throttle channel to 1500 via channel overrides"
vehicle.channels.overrides['3'] = 1500
</code></pre>
<p>I dont know is this proper way or not, since <a href="http://python.dronekit.io/examples/channel_overrides.html" rel="nofollow noreferrer">dronekit doc</a> highly dis-commended using rc overrides</p>
|
dronekit-python|dronekit
| 1 |
1,904,218 | 52,172,675 |
Creating dice simulator in Python, how to find most common roll
|
<pre><code>import random
#Making sure all values are = to 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
#Loop for rolling the die 100 times
for r in range(0, 100):
roll = random.randint(1, 6)
if roll == 1:
one += 1
elif roll == 2:
two += 1
elif roll == 3:
three += 1
elif roll == 4:
four += 1
elif roll == 5:
five += 1
elif roll == 6:
six += 1
#print how many times each number was rolled
print(one)
print(two)
print(three)
print(four)
print(five)
print(six)
#How many times the 3 was rolled
print("The 3 was rolled", three, "times!")
#Average roll between all of them
print("The average roll was", (one * 1 + two * 2 + three * 3 + 4 * four + 5 * five + 6 * six)/100)
</code></pre>
<p>I am trying to make it so it prints out</p>
<p>"number is the most common roll." for whichever the roll is. </p>
<p>Just trying to do this is the most simple way, and I'm confused on how to do it. I tried to do like if one > two > three etc etc. but that did not work. </p>
|
<p>Choosing an appropriate data structure to gain maximum leverage of a languageβs core features is one of the most valuable skills a programmer can develop.</p>
<p>For this particular use case, itβs best to use an iterable data type that facilitates operations (e.g. sort, obtain the maximum) on the collection of numbers. As we want to associate a number (1-6) with the number of times that number was rolled, a dictionary seems like the simplest data structure to choose.</p>
<p>Iβve re-written the program to show how its existing functionality could be re-implemented using a dictionary as its data structure. With the comments, the code should be fairly self-explanatory.</p>
<p>The tricky part is what this question is actually asking: determining the number rolled most often. Instead of manually implementing a sorting algorithm, we can use the Python built-in <a href="https://docs.python.org/3.5/library/functions.html#max" rel="nofollow noreferrer"><code>max</code> function</a>. It can accept an optional <code>key</code> argument which specifies the function that should be applied to each item in the iterable object before carrying out the comparison. In this case, I chose the <code>dict.get()</code> method which returns the value corresponding to a key. This is how the dictionary of roll results is compared by the number of rolls for each result for determining the number rolled most often. Note that <code>max()</code> only returns one item so in the case of a tie, only one of the results will be printed (see <a href="https://stackoverflow.com/q/6783000/1640661">Which maximum does Python pick in the case of a tie?</a>).</p>
<p>See also: <a href="https://stackoverflow.com/q/613183/1640661">How do I sort a dictionary by value?</a></p>
<pre><code>import random
NUM_ROLLS = 100
DIE_SIDES = 6
# Create the dictionary to store the results of each roll of the die.
rolls = {}
#Loop for rolling the die NUM_ROLLS times
for r in range(NUM_ROLLS):
roll_result = random.randint(1, DIE_SIDES)
if roll_result in rolls:
# Add to the count for this number.
rolls[roll_result] += 1
else:
# Record the first roll result for this number.
rolls[roll_result] = 1
# Print how many times each number was rolled
for roll_result in range(1, 7):
print("The number", str(roll_result), "was rolled", str(rolls[roll_result]), "times.")
#How many times the 3 was rolled
print("The number three was rolled", str(rolls[3]), "times.")
#Average roll between all of them
sum = 0
for roll_result in rolls:
sum += roll_result * rolls[roll_result]
print("The average roll result was", str(sum/NUM_ROLLS))
# The number rolled most often.
print(str(max(rolls, key=rolls.get)), "is the most common roll result.")
</code></pre>
|
python|python-3.x|data-structures
| 1 |
1,904,219 | 52,398,079 |
what does this expression do ? default=lambda self: _('New'))
|
<p>I am working on Odoo Erp and during code analysis i found this expression in a field definition</p>
<pre><code>default=lambda self: _('New')
</code></pre>
<p>the exact expression is:</p>
<pre><code>reference = fields.Char(string='Schedule Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)]}, index=True, default=lambda self: _('New'))
</code></pre>
<p>i want to know what is _('New') do here.</p>
|
<p>The field default value will be used to create new records and it accepts a direct value or a function to be called. Using a function is a way to be able to use the context values like lang of the current user in order to be able to return more accurate values. </p>
<p>The _ function in Odoo is the translation shortcut function so _('New') is a way to return the translation of the 'New' string and due to the _ function is used with the current user context is able to return the translation of the value for the user defined lang if it's available.</p>
|
python|orm|odoo
| 3 |
1,904,220 | 51,843,791 |
requests fails to download any image from a certain site although all image there is downloadable?
|
<p>Here is the code I use for downloading any image (it always works fine except for this site www.pexels.com) . It actually download the image, but corrupted when it comes to this site ? I wonder why ??</p>
<pre><code>url = "https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
response = requests.get(url , stream = True)
file= open("Hello.jpg" , 'wb')
for chunk in response.iter_content(10000):
file.write(chunk)
file.close()
</code></pre>
|
<p>You need to add a <code>user-agent</code> to your request headers. </p>
<p>The following code works:</p>
<pre><code>import requests
url = "https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"
headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
}
response = requests.get(url , stream = True, headers=headers)
file= open("Hello.jpg" , 'wb')
for chunk in response.iter_content(10000):
file.write(chunk)
file.close()
</code></pre>
|
python|python-3.x|python-requests
| 4 |
1,904,221 | 68,970,061 |
Python input interpretation as string
|
<p>I am writing a discord python bot.</p>
<p>I am trying to create a guessing style command for primary colors.</p>
<p>However I am receiving a <code>TypeError: 'str' object is not callable</code> after the user submits their guess.</p>
<p>I was able to solve this with an integer guessing style command with <code>m.content.isdigit()</code> however I am hung up on solving this.</p>
<p>I have tried adding <code>str()</code> containers around several areas with no joy.</p>
<pre><code>elif user_message.lower().startswith('!guesscolor'):
await message.channel.send('Guess a color of a rainbow')
def is_correct(m):
return m.author == message.author and m.content()
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo,', 'violet']
answer = random.choice(colors)
print(f'The correct color is: {answer}.')
try:
guess = await client.wait_for('message', check=is_correct, timeout=5.0)
except asyncio.TimeoutError:
return await message.channel.send(f'Sorry, you took too long it was {answer}.')
if (guess.content) == answer:
await message.channel.send('You are right!')
else:
await message.channel.send(f'Oops, it was actually {answer}.')
return
return
</code></pre>
<p>Any input or direction to solve this is greatly appreciated.</p>
<p>Below is the working version for the integer guess:</p>
<pre><code>elif user_message.lower().startswith('!guessnumber'):
await message.channel.send('Guess a number between 1 and 10')
def is_correct(m):
return m.author == message.author and m.content.isdigit()
answer = random.randint(1,10)
print(f'The correct answer is: {answer}.')
try:
guess = await client.wait_for('message', check=is_correct, timeout=5.0)
except asyncio.TimeoutError:
return await message.channel.send(f'Sorry, you took too long it was {answer}.')
if int(guess.content) == answer:
await message.channel.send('You are right!')
else:
await message.channel.send(f'Oops, it was actually {answer}.')
return
return
</code></pre>
|
<p>If you want to check that it's one of the possible colors, do this:</p>
<pre><code> def is_correct(m):
return m.author == message.author and m.content in colors
</code></pre>
|
python|discord|discord.py|bots
| 1 |
1,904,222 | 67,388,999 |
How to ignore system/hidden directories when using os.listdir?
|
<p>When I am using <code>os.listdir()</code> to analyze a content of a zip file, I often get unexpected system directories like <code>__MACOSX</code>. I know I just can write a function to ignore <code>__MACOSX</code> but I need a more sophisticated solutions . I need all hidden directories from whatever operating system (MAC OS, windows or linux) to be automatically ignored.</p>
<p>Any suggestion ?</p>
|
<p>Hidden Files start with ".", so you can remove filename that starts with "."</p>
<pre><code>import os
for f in os.listdir('Your_path'):
if not f.startswith('.'):
print(f)
</code></pre>
|
python
| 0 |
1,904,223 | 19,524,832 |
list comprehension to create list of list
|
<p>What is the list comprehension to achieve this:</p>
<pre><code>a=[1,2,3,4,5]
b=[[x,False] for x in a]
</code></pre>
<p>will give,</p>
<pre><code>[[1,False],[2,False],[3,False],[4,False],[5,False]]
</code></pre>
<p>How can I get True for some number in the list? I need something like this:</p>
<pre><code>[[1,False],[2,False],[3,False],[4,True],[5,False]]
</code></pre>
<p>My random playing has not solved the problem.</p>
|
<p>Use <code>if-else</code> conditional:</p>
<pre><code>>>> a = [1,2,3,4,5]
>>> b = [[x, True if x == 4 else False] for x in a]
>>> b
[[1, False], [2, False], [3, False], [4, True], [5, False]]
</code></pre>
<p>or just:</p>
<pre><code>>>> b = [[x, x == 4] for x in a]
</code></pre>
|
python
| 5 |
1,904,224 | 17,054,022 |
Remove specific characters from list python
|
<p>I am fairly new to Python. I have a list as follows:</p>
<pre><code>sorted_x = [('pvg-cu2', 50.349189), ('hkg-pccw', 135.14921), ('syd-ipc', 163.441705), ('sjc-inap', 165.722676)]
</code></pre>
<p>I am trying to write a regex which will remove everything after the '-' and before the ',', i.e I need the same list to look as below:</p>
<pre><code>[('pvg', 50.349189), ('hkg', 135.14921), ('syd', 163.441705), ('sjc', 165.722676)]
</code></pre>
<p>I have written a regex as follows:</p>
<pre><code>for i in range(len(sorted_x)):
title_search = re.search('^\(\'(.*)-(.*)\', (.*)\)$', str(sorted_x[i]), re.IGNORECASE)
if title_search:
title = title_search.group(1)
time = title_search.group(3)
</code></pre>
<p>But this requires me to create two new lists and I don't want to change my original list.
Can you please suggest a simple way so that I can modify my original list without creating a new list? </p>
|
<pre><code>result = [(a.split('-', 1)[0], b) for a, b in sorted_x]
</code></pre>
<p>Example:</p>
<pre><code>>>> sorted_x = [('pvg-cu2', 50.349189), ('hkg-pccw', 135.14921), ('syd-ipc', 163.441705), ('sjc-inap', 165.722676)]
>>> [(a.split('-', 1)[0], b) for a, b in sorted_x]
[('pvg', 50.349189000000003), ('hkg', 135.14921000000001), ('syd', 163.44170500000001), ('sjc', 165.72267600000001)]
</code></pre>
|
python|regex
| 8 |
1,904,225 | 16,785,920 |
PEP 8: Function and method arguments naming convention
|
<p>From PEP 8 section of Function and method arguments :</p>
<blockquote>
<p>Always use self for the first argument to instance methods.</p>
<p>Always use cls for the first argument to class methods.</p>
<p>If a function argument's name clashes with a reserved keyword, it is generally better to append a >single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is >better than clss. (Perhaps better is to avoid such clashes by using a synonym.)</p>
</blockquote>
<p>It does not say anything about the preferred naming style. I guess it should be "lower_case_with_underscores" or "mixedCase" but I am not sure. What is preferred?</p>
|
<p>From the PEP 8 section immediately above the one you quoted.</p>
<blockquote>
<h2>Function Names</h2>
<p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>
<p>mixedCase is allowed only in contexts where that's already the prevailing style
(e.g. threading.py), to retain backwards compatibility.</p>
</blockquote>
<p>Link: <a href="https://www.python.org/dev/peps/pep-0008/#function-names" rel="nofollow noreferrer">https://www.python.org/dev/peps/pep-0008/#function-names</a></p>
|
python|python-3.x|arguments|naming-conventions|pep8
| 1 |
1,904,226 | 43,746,385 |
Django: Trunc datetime results in none
|
<p>I have the following model:</p>
<pre><code>class Statistic(models.Model):
meter = models.ForeignKey(Meter, on_delete=models.CASCADE, db_index=True)
timestamp_start = models.DateTimeField(db_index=True)
timestamp_end = models.DateTimeField(db_index=True)
usage_start = models.DecimalField(max_digits=10, decimal_places=3)
usage_end = models.DecimalField(max_digits=10, decimal_places=3)
return_start = models.DecimalField(max_digits=10, decimal_places=3)
return_end = models.DecimalField(max_digits=10, decimal_places=3)
</code></pre>
<p>I have the following value in the first record of timestamp_start in my sqllite database</p>
<pre><code>2016-12-22T06:15:30.420+02:00
</code></pre>
<p>When I run the following query:</p>
<pre><code>statistics = Statistic.objects.filter(id=1)
.annotate(timestamp=Trunc('timestamp_start','day', output_field=DateTimeField()))
.values('timestamp')
.annotate(usage_start = Min('usage_start'))
</code></pre>
<p>timestamp results in None</p>
<blockquote>
<p>QuerySet [{'usage_start': Decimal('136.972'), 'timestamp': None}]</p>
</blockquote>
<p>When I attach the debugger and check the first records of my statistics table like this</p>
<pre><code>Statistics.objects.all()[0].timestamp_start
</code></pre>
<p>it returns:</p>
<blockquote>
<p>datetime.datetime(2016, 12, 22, 6, 0)</p>
</blockquote>
<p>Before facing this problem I got this exception:</p>
<blockquote>
<p>Database returned an invalid datetime value. Are time zone definitions for your database and pytz installed?</p>
</blockquote>
<p>I do have pytz installed. But no idea how to fix this. Is the value incorrect ? Anyway in the end I set use_tz in settings.py to false. The exception vanisched but trunc returns none now. Is this causing the problem?</p>
<p>p.s.: My environment Python 3, Django, Sql lite database, windows</p>
|
<p>You probably haven't loaded the timezone data into mysql. TruncDate uses the <code>CONVERT_TZ</code> function under the hood, which returns <code>NULL</code> if no timezone data is available. You can check what SQL the query is using by evaluating the following:</p>
<pre><code>str(statistics.query)
</code></pre>
<p>Windows instructions for loading timezone data can be found here:</p>
<ul>
<li><a href="https://dev.mysql.com/downloads/timezones.html" rel="nofollow noreferrer">https://dev.mysql.com/downloads/timezones.html</a></li>
<li><a href="https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html#time-zone-installation" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html#time-zone-installation</a> (Make sure you scroll down the section which talks about Windows)</li>
</ul>
<p>I ran into this issue on Linux and resolved it as indicated in this other StackOverflow post:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/14454304/convert-tz-returns-null">convert_tz returns null</a></li>
</ul>
|
python|django|sqlite|datetime|truncate
| 2 |
1,904,227 | 43,854,195 |
Regular Expression : Complex Multiple Matches
|
<pre><code>line = 'bla bla bla Tax_Id=9606 Gene_Symbol=OR4F16 OR4F28P OR4F29 OR4F2P OR4F3 DTR4F7P BPFR4F8P Gene_Accession=ENSG00000217874 bla bla bla'
</code></pre>
<p>I am trying to match all the Gene symbols. I tried using re, regex and their different modules but it doesn't work.</p>
|
<p>this works assuming Gene_Symbol and Gene_Accession are always in the order of you example. Otherwise the regular expression would need to be tweaked.</p>
<pre><code>import re
line = 'bla bla bla Tax_Id=9606 Gene_Symbol=OR4F16 OR4F28P OR4F29 OR4F2P OR4F3 DTR4F7P BPFR4F8P Gene_Accession=ENSG00000217874 bla bla bla'
regex = r"Gene_Symbol=(.*)Gene_Accession"
p = re.search(regex,line)
symbols = p.group(1).split()
for symbol in symbols:
print symbol
</code></pre>
<p>output:</p>
<pre><code>OR4F16
OR4F28P
OR4F29
OR4F2P
OR4F3
DTR4F7P
BPFR4F8P
</code></pre>
|
python|regex
| 0 |
1,904,228 | 54,495,590 |
How to simulate roll of a dice
|
<p>How to simulate the roll of an UNFAIR 6-sided die. Instead of each side having an even chance of coming up (1/6 = 16.7%), the middle numbers should be favored. There should be a 20% chance of rolling a 2, 3, 4, or 5, and only a 10% chance of rolling a 1 or a 6.
Thanks</p>
|
<p>Another possibility:</p>
<pre><code>import random
result = random.choices([1, 2, 3, 4, 5, 6], weights=[10, 20, 20, 20, 20, 10])[0]
</code></pre>
<p>See the <a href="https://docs.python.org/3.6/library/random.html#random.choices" rel="noreferrer">documentation</a>.</p>
|
python
| 6 |
1,904,229 | 54,405,408 |
Is it possible to ignore one single specific line with pylint, without changes to the source code?
|
<p><a href="https://stackoverflow.com/questions/28829236/is-it-possible-to-ignore-one-single-specific-line-with-pylint">Is it possible to ignore one single specific line with pylint?</a> has solutions that requires littering source code with comments what is undesirable for me.</p>
<p>Is there way to specify that given instance is false positive in arguments of the pylint command line tool?</p>
|
<p>I don't think it is possible to ignore a specific line without changing the source code. However, it is certainly possible to ignore warning types in the <code>.pylintrc</code> or at the top of file. </p>
<p>I'd go with the approach of creating a .pylintrc to suit your needs. For example, if you want to completely ignore <code>W0612: unused-variable</code> then you can <a href="https://stackoverflow.com/questions/22448731/how-do-i-create-a-pylintrc-file">create a .pylintrc</a> file and add message names to disable as noted in <a href="https://docs.pylint.org/en/1.6.0/faq.html#what-is-the-format-of-the-configuration-file" rel="nofollow noreferrer">pytest docs</a>. </p>
<h3>.pylintrc</h3>
<pre><code>disable=unused-variable,
...,
</code></pre>
<p>Alternatively, you can disable messages on a case by case basis <a href="https://docs.pylint.org/en/1.6.0/faq.html#is-there-a-way-to-disable-a-message-for-a-particular-module-only" rel="nofollow noreferrer">at the top of the file</a>, and just tell your students to ignore it: </p>
<h3>Top of file</h3>
<pre><code># pylint: disable=unused-variable, wildcard-import, method-hidden
# pylint: enable=too-many-lines
</code></pre>
|
python|command-line|configuration|pylint|false-positive
| 2 |
1,904,230 | 71,236,976 |
How to extract data from variable Path in JSON files using Python
|
<p>I have to extract variable data from a json file, where the path is not a constant.</p>
<p>Here's my code</p>
<pre><code>import json
JSONFILE="output.json"
jsonf = open(JSONFILE, 'r', encoding='utf-8')
with jsonf as json_file:
data = json.load(json_file)
print(data["x1"]["y1"][0])
</code></pre>
<p>The json file</p>
<pre><code>{
"x1" : {
"y1" : [
{
"value" : "v1",
"type" : "t1",
}
]
},
"x2" : {
"y2" : [
{
"value" : "v2",
"type" : "t2",
}
],
}
}
</code></pre>
<p>I want to extract all the values not only [x1][y1][value]</p>
|
<p>All the values should be stored in the <code>data</code>, and they datatype is a dictionary. It's up to you what you want to "index" and obtain. Learn more about dictionaries in Python 3: <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/datastructures.html#dictionaries</a></p>
<p>Feel free to ask further questions.</p>
|
python|json
| 0 |
1,904,231 | 47,977,600 |
Is there a way to get the color of a recognized object inside a picture?
|
<p>I am using <a href="https://www.tensorflow.org/" rel="noreferrer">Tensorflow</a> in order to recognize object in a provided picture , following this <a href="https://www.tensorflow.org/install/install_java" rel="noreferrer">tutorial</a> and using <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java" rel="noreferrer">this repo</a> I succeed to make my program return the object inside a picture .
For example this is the picture I used as input: </p>
<p><a href="https://i.stack.imgur.com/ua5iz.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ua5iz.jpg" alt="red-tshirt.jpg"></a></p>
<p>and here's the output of my program : </p>
<p><a href="https://i.stack.imgur.com/eQDtK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eQDtK.png" alt="enter image description here"></a></p>
<p>All I want is to get the color of the recognized item (red jersey for the last case),is that possible ?</p>
<p>Here's the code (from the last link just with small changes)</p>
<pre><code>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package com.test.sec.compoment;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import org.tensorflow.DataType;
import org.tensorflow.Graph;
import org.tensorflow.Output;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
import org.tensorflow.types.UInt8;
/** Sample use of the TensorFlow Java API to label images using a pre-trained model. */
public class ImageRecognition {
private static void printUsage(PrintStream s) {
final String url =
"https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip";
s.println(
"Java program that uses a pre-trained Inception model (http://arxiv.org/abs/1512.00567)");
s.println("to label JPEG images.");
s.println("TensorFlow version: " + TensorFlow.version());
s.println();
s.println("Usage: label_image <model dir> <image file>");
s.println();
s.println("Where:");
s.println("<model dir> is a directory containing the unzipped contents of the inception model");
s.println(" (from " + url + ")");
s.println("<image file> is the path to a JPEG image file");
}
public void index() {
String modelDir = "C:/Users/Admin/Downloads/inception5h";
String imageFile = "C:/Users/Admin/Desktop/red-tshirt.jpg";
byte[] graphDef = readAllBytesOrExit(Paths.get(modelDir, "tensorflow_inception_graph.pb"));
List<String> labels =
readAllLinesOrExit(Paths.get(modelDir, "imagenet_comp_graph_label_strings.txt"));
byte[] imageBytes = readAllBytesOrExit(Paths.get(imageFile));
try (Tensor<Float> image = constructAndExecuteGraphToNormalizeImage(imageBytes)) {
float[] labelProbabilities = executeInceptionGraph(graphDef, image);
int bestLabelIdx = maxIndex(labelProbabilities);
System.out.println(
String.format("BEST MATCH: %s (%.2f%% likely)",
labels.get(bestLabelIdx),
labelProbabilities[bestLabelIdx] * 100f));
}
}
private static Tensor<Float> constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
try (Graph g = new Graph()) {
GraphBuilder b = new GraphBuilder(g);
// Some constants specific to the pre-trained model at:
// https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
//
// - The model was trained with images scaled to 224x224 pixels.
// - The colors, represented as R, G, B in 1-byte each were converted to
// float using (value - Mean)/Scale.
final int H = 224;
final int W = 224;
final float mean = 117f;
final float scale = 1f;
// Since the graph is being constructed once per execution here, we can use a constant for the
// input image. If the graph were to be re-used for multiple input images, a placeholder would
// have been more appropriate.
final Output<String> input = b.constant("input", imageBytes);
final Output<Float> output =
b.div(
b.sub(
b.resizeBilinear(
b.expandDims(
b.cast(b.decodeJpeg(input, 3), Float.class),
b.constant("make_batch", 0)),
b.constant("size", new int[] {H, W})),
b.constant("mean", mean)),
b.constant("scale", scale));
try (Session s = new Session(g)) {
return s.runner().fetch(output.op().name()).run().get(0).expect(Float.class);
}
}
}
private static float[] executeInceptionGraph(byte[] graphDef, Tensor<Float> image) {
try (Graph g = new Graph()) {
g.importGraphDef(graphDef);
try (Session s = new Session(g);
Tensor<Float> result =
s.runner().feed("input", image).fetch("output").run().get(0).expect(Float.class)) {
final long[] rshape = result.shape();
if (result.numDimensions() != 2 || rshape[0] != 1) {
throw new RuntimeException(
String.format(
"Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
Arrays.toString(rshape)));
}
int nlabels = (int) rshape[1];
return result.copyTo(new float[1][nlabels])[0];
}
}
}
private static int maxIndex(float[] probabilities) {
int best = 0;
for (int i = 1; i < probabilities.length; ++i) {
if (probabilities[i] > probabilities[best]) {
best = i;
}
}
return best;
}
private static byte[] readAllBytesOrExit(Path path) {
try {
return Files.readAllBytes(path);
} catch (IOException e) {
System.err.println("Failed to read [" + path + "]: " + e.getMessage());
System.exit(1);
}
return null;
}
private static List<String> readAllLinesOrExit(Path path) {
try {
return Files.readAllLines(path, Charset.forName("UTF-8"));
} catch (IOException e) {
System.err.println("Failed to read [" + path + "]: " + e.getMessage());
System.exit(0);
}
return null;
}
// In the fullness of time, equivalents of the methods of this class should be auto-generated from
// the OpDefs linked into libtensorflow_jni.so. That would match what is done in other languages
// like Python, C++ and Go.
static class GraphBuilder {
GraphBuilder(Graph g) {
this.g = g;
}
Output<Float> div(Output<Float> x, Output<Float> y) {
return binaryOp("Div", x, y);
}
<T> Output<T> sub(Output<T> x, Output<T> y) {
return binaryOp("Sub", x, y);
}
<T> Output<Float> resizeBilinear(Output<T> images, Output<Integer> size) {
return binaryOp3("ResizeBilinear", images, size);
}
<T> Output<T> expandDims(Output<T> input, Output<Integer> dim) {
return binaryOp3("ExpandDims", input, dim);
}
<T, U> Output<U> cast(Output<T> value, Class<U> type) {
DataType dtype = DataType.fromClass(type);
return g.opBuilder("Cast", "Cast")
.addInput(value)
.setAttr("DstT", dtype)
.build()
.<U>output(0);
}
Output<UInt8> decodeJpeg(Output<String> contents, long channels) {
return g.opBuilder("DecodeJpeg", "DecodeJpeg")
.addInput(contents)
.setAttr("channels", channels)
.build()
.<UInt8>output(0);
}
<T> Output<T> constant(String name, Object value, Class<T> type) {
try (Tensor<T> t = Tensor.<T>create(value, type)) {
return g.opBuilder("Const", name)
.setAttr("dtype", DataType.fromClass(type))
.setAttr("value", t)
.build()
.<T>output(0);
}
}
Output<String> constant(String name, byte[] value) {
return this.constant(name, value, String.class);
}
Output<Integer> constant(String name, int value) {
return this.constant(name, value, Integer.class);
}
Output<Integer> constant(String name, int[] value) {
return this.constant(name, value, Integer.class);
}
Output<Float> constant(String name, float value) {
return this.constant(name, value, Float.class);
}
private <T> Output<T> binaryOp(String type, Output<T> in1, Output<T> in2) {
return g.opBuilder(type, type).addInput(in1).addInput(in2).build().<T>output(0);
}
private <T, U, V> Output<T> binaryOp3(String type, Output<U> in1, Output<V> in2) {
return g.opBuilder(type, type).addInput(in1).addInput(in2).build().<T>output(0);
}
private Graph g;
}
}
</code></pre>
|
<p>You are using a code which predicts the label of the given image, i.e. classifies the image from some trained classes So you don't know the exact pixels of your object.</p>
<p>So, I suggest you do any of the following,</p>
<ol>
<li>Use an <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">object detector</a> to detect the location of the object and get the bounding box. Then get the color of the most pixels.</li>
<li>Use a pixel-wise classification (segmentation) like <a href="https://github.com/arahusky/Tensorflow-Segmentation" rel="nofollow noreferrer">this</a> to get the exact pixels of your object.</li>
</ol>
<p>Note, you may need to manually train the network (or model) for your object</p>
<h1>Edit:</h1>
<p>For Java object detection examples, have a look at <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android" rel="nofollow noreferrer">this</a> project which is coded for <code>android</code>, but it should be straightforward to use them in desktop applications. More specifically look into <a href="https://github.com/tensorflow/tensorflow/blob/4a7bbb54f2841b9c871ac0dc0099ca690d9e1af2/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowObjectDetectionAPIModel.java#L111" rel="nofollow noreferrer">this</a> part.</p>
<p>You don't need both object detection and segmentation at the same time but if you want, I think first try to train a model for segmentation using python (the link is provided above) then use the model in java similarly as the object detection models.</p>
<h1>Edit 2:</h1>
<p>I have added a <a href="https://github.com/sumsuddin/TensorflowObjectDetectorJava" rel="nofollow noreferrer">simple object detection client</a> in <code>java</code> which uses Tensorflow Object detection API <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md" rel="nofollow noreferrer">models</a> just to show you that you can use any frozen model in java.</p>
<p>Also, check this beautiful <a href="https://github.com/karolmajek/Mask_RCNN" rel="nofollow noreferrer">repository</a> which uses pixel wise segmentation.</p>
<p><a href="https://i.stack.imgur.com/FXXkq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FXXkq.jpg" alt="enter image description here" /></a></p>
|
java|tensorflow|image-recognition
| 7 |
1,904,232 | 34,278,490 |
Efficiently filter windowed observations in a pandas dataframe if they contain a certain value
|
<p>I have a pandas dataframe that has windows/chains of string observations indexed at the point of their first observation. The window is of a variable size. For this example we can say they're chains of 4 observations. I want to know how to most efficiently eliminate certain values if they have a specific observation anywhere in their windows, knowing that if the nth window begins with the value I am looking for, I know I can get rid of it, and the three windows before it because they will also contain the same value later in their windows. It is possible for a window to contain multiple instances of the value I want to filter for. Here's some sample data. Starting with a simple series of events, ser:</p>
<pre><code>import pandas as pd
ser = pd.Series(['a','b','c','d','e','f','g','h','i','j','k'])
>>> ser
0 a
1 b
2 c
3 d
4 e
5 f
6 g
7 h
8 i
9 j
10 k
</code></pre>
<p>Then I turn this into a dataframe where each row is a window of n observations. Here n == 4.</p>
<pre><code>df = pd.concat([ser.shift(-x) for x in range(4)], axis=1)
>>> df
0 1 2 3
0 a b c d
1 b c d e
2 c d e f
3 d e f g
4 e f g h
5 f g h i
6 g h i j
7 h i j k
8 i j k NaN
9 j k NaN NaN
10 k NaN NaN NaN
</code></pre>
<p>Now I want to get rid of all the rows that include the value 'f' anywhere, i.e.:</p>
<p>desired_output</p>
<pre><code> 0 1 2 3
0 a b c d
1 b c d e
6 g h i j
7 h i j k
8 i j k NaN
9 j k NaN NaN
10 k NaN NaN NaN
</code></pre>
<p>I'd like to avoid searching the whole dataframe as it only contains repetition of the first column, and my value for n can be somewhat long. In this example, what would be the best way to drop the columns that start with 'c', 'd', 'e', and 'f', knowing that they will all include an 'f' somewhere. Later I join all the strings in each row into one value but it seems like it should be easier to manipulate the data at this stage where everything is in different columns. This is with pandas 0.16.0 and must work on python 2.76 and python 3.4. Thank you!</p>
|
<p>You can do, without searching the whole dataframe:</p>
<pre><code>import numpy as np
ind = -np.arange(0, df.shape[1])+pd.Index(ser).get_loc('f')
df.iloc[np.setdiff1d(ser.index, ind)]
#Out[48]:
# 0 1 2 3
#0 a b c d
#1 b c d e
#6 g h i j
#7 h i j k
#8 i j k NaN
#9 j k NaN NaN
#10 k NaN NaN NaN
</code></pre>
|
python|string|pandas|filter|window
| 2 |
1,904,233 | 66,129,793 |
Python 3.7 else statement not showing correct index?
|
<p>My goal here is to print lines from text files together. Some lines, however, are not together like they should be. I resolved the first problem where the denominator was on the line after. For the <code>else</code> statement, they all seem to have the same value/index.</p>
<pre><code>import fitz # this is pymupdf
with fitz.open("math-problems.pdf") as doc: #below converts pdf to txt
text = ""
for page in doc:
text += page.getText()
file_w = open("output.txt", "w") #save as txt file
file_w.write(text)
file_w.close()
file_r = open("output.txt", "r") #read txt file
word = 'f(x) = '
#--------------------------
list1 = file_r.readlines() # read each line and put into list
list2 = [k for k in list1 if word in k] # look for all elements with "f(x)" and put all in new list
list1_N = list1
list2_N = list2
list1 = [e[3:] for e in list1] #remove first three characters (the first three characters are always "1) " or "A) "
char = str('\n')
for char in list2:
index = list1.index(char)
def digitcheck(s):
isdigit = str.isdigit
return any(map(isdigit,s))
xx = digitcheck(list1[index])
if xx:
print(list1[index] + " / " + list1_N[index+1])
else:
print(list1[index] + list1[index+1]) # PROBLEM IS HERE, HOW COME EACH VALUE IS SAME HERE?
</code></pre>
<p><strong>Output from terminal:</strong></p>
<pre><code>f(x) = x3 + x2 - 20x
/ x2 - 3x - 18
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) = x2 + 3x - 10
/ x2 - 5x - 14
f(x) = x2 + 2x - 8
/ x2 - 3x - 10
f(x) = x - 1
/ x2 + 8
f(x) = 3x3 - 2x - 6
/ 8x3 - 7x + 4
f(x) =
2 + 5x
f(x) = x3 - 6x2 + 4x - 1
/ x2 + 8x
Process finished with exit code 0
</code></pre>
|
<p><strong>SOLVED</strong>
@copperfield was correct, I had repeating values so my index was repeating. I solved this using a solution by @Shonu93 in <a href="https://stackoverflow.com/questions/5419204/index-of-duplicates-items-in-a-python-list">here</a>. Essentially it locates all indices of duplicate values and puts these indices into one list <code>elem_pos</code> and then prints each index from <code>list1</code></p>
<pre><code>if empty in list1:
counter = 0
elem_pos = []
for i in list1:
if i == empty:
elem_pos.append(counter)
counter = counter + 1
xy = elem_pos
for i in xy:
print(list1[i] + list1_N[i+1])
</code></pre>
|
python|pymupdf
| 0 |
1,904,234 | 39,679,602 |
difference between GUI , Shell ,command line
|
<p>I am beginner and I tried to use python IDLE and make some functions and modules..
I do not understand very well : </p>
<p>1- GUI ,IDLE, Shell , interpreter , command line , console , API ,..
I do not know the difference and when to use each of them !! </p>
<p>2- Difference between library ,module and class !</p>
|
<ol>
<li>GUI = graphical user interface</li>
<li>API = Application programming interface. It contains a data contract and services contract(think how some websites let you sign in with Facebook, they use the Facebook API to use methods like get your Facebook profile and info)</li>
<li>The Shell is the interpretor that executes the lines of code.</li>
<li>IDLE a text editor for python, tools like this are usually referred as integrated development environments (IDE). Its is where you are gonna write your code. There are tons of IDE for all languages out there like Visual Studio, Eclipse, and more</li>
<li>A class regroups methods and attributes that defines an object. If i have a class CAR, inside i will have attributes like Wheels, Tires, Doors, etc and methods like Turn, Stop, Accelerate, etc. If you are not familiar with class i suggest you read more online because it is the very base of object-oriented programming. </li>
<li>A library is a collection of precompiled routines that a program can use. </li>
<li>A module is a routine (see 6)</li>
</ol>
<p>Hope this clarifies things for you :)</p>
|
python-2.7|user-interface
| 1 |
1,904,235 | 39,674,508 |
Python binary to multi- hex
|
<p>I am trying to read a file in binary and return for example "ffffff" a series of 6 hex codes. does this make sense? The code I have (below) only returns a list of 2 so it looks like "ff"</p>
<pre><code>fp = open(f, 'rb')
hex_list = ("{:02x}".format(ord(c)) for c in fp.read())
</code></pre>
<p>i am specifically looking to make this return something like</p>
<pre><code>['ab0012', 'ffbaf0']
</code></pre>
<p>not like</p>
<pre><code>['ab', '00', '12', 'ff', 'ba', 'f0']
</code></pre>
<p>any help would be appreciated thanks. </p>
|
<p>How about this:</p>
<pre><code>fp = open(f, 'rb')
hex_list = ["{:02x}".format(ord(c)) for c in fp.read()]
return [''.join(hex_list[n:n+3]) for n in range(0, len(hex_list), 3)]
</code></pre>
|
python|format|hex|bin|ord
| 1 |
1,904,236 | 16,315,622 |
Calculating difference in seconds between two dates not working above a day
|
<p>I have a function that accepts a date and returns the difference in time between then and the current time (in seconds). It works fine for everything less than a day. But when I even enter a date that's a year in the future, it still returns a number around 84,000 seconds (there are around 86,400 seconds in a day). </p>
<pre><code>def calc_time(date):
future_date = str(date)
t_now = str(datetime.utcnow())
t1 = datetime.strptime(t_now, "%Y-%m-%d %H:%M:%S.%f")
t2 = datetime.strptime(future_date, "%Y-%m-%d %H:%M:%S.%f")
return ((t2-t1).seconds)
</code></pre>
<p>Even when I run it with a parameter whose date is in 2014, i get a number way too low. </p>
<p>Anyone have any insight?</p>
|
<p>Reading the <a href="http://docs.python.org/2/library/datetime.html#datetime.timedelta" rel="noreferrer">datetime.timedelta</a> docs.</p>
<blockquote>
<p>All arguments are optional and default to 0. Arguments may be ints,
longs, or floats, and may be positive or negative.</p>
<p>Only days, seconds and microseconds are stored internally. Arguments
are converted to those units:</p>
<p>A millisecond is converted to 1000 microseconds. A minute is converted
to 60 seconds. An hour is converted to 3600 seconds. A week is
converted to 7 days. and days, seconds and microseconds are then
normalized so that the representation is unique, with</p>
<p>0 <= microseconds < 1000000 0 <= seconds < 3600*24 (the number of
seconds in one day)
-999999999 <= days <= 999999999</p>
</blockquote>
<p>The solution is to use <code>.total_seconds()</code> instead of <code>.seconds</code></p>
|
python|datetime
| 5 |
1,904,237 | 16,156,788 |
How can i convert images from scikit-image to opencv2 and other libraries?
|
<p>I tried to find contour with cv2 python library in a skeletonized image created with scikit-image and i got this error:</p>
<pre><code> contours, hierarchy = cv2.findContours(skel,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
TypeError: <unknown> data type = 0 is not supported
</code></pre>
<p>My question is: What i have to do to convert to cv2 and viceversa?</p>
<p>I know that opencv use numpy.uint8 type to represent binary images instead scikit-image numpy.float64</p>
<p>I used also mahotas (numpy.bool) and pymorph libraries.
How can i convert from scikit-image to these libraries and viceversa?</p>
|
<p><code>scikit-image</code> provides conversion routines between the different data-types that also correctly preserves scaling:</p>
<pre><code>from skimage import img_as_ubyte
cv_image = img_as_ubyte(any_skimage_image)
</code></pre>
<p>Update: the scikit-image user guide now has a more detailed section on this: <a href="http://scikit-image.org/docs/stable/user_guide/data_types.html#working-with-opencv" rel="noreferrer">http://scikit-image.org/docs/stable/user_guide/data_types.html#working-with-opencv</a></p>
|
python|opencv|image-processing|contour|scikit-image
| 19 |
1,904,238 | 38,620,316 |
Image analysis -- mapping two labeled Numpy arrays
|
<p>I have two Numpy arrays, array A and array B, with equal dimensions. Array A is a labelled array, where elements corresponding to the same "object" share the same value. Basically, what I'm trying to do is for each non-zero element in array B, if that element corresponds to a non-zero element in array A, re-label each element of that object (in array A) corresponding to the value from array B. </p>
<p>For example, if I have:</p>
<pre><code>array A = [[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 2],
[3, 0, 0, 2, 0],
[3, 3, 0, 2, 0]]
array B = [[0, 0, 4, 4, 4],
[4, 4, 4, 4, 4],
[0, 4, 4, 0, 0],
[0, 4, 4, 4, 4],
[0, 0, 4, 4, 4],
[5, 0, 0, 0, 0]]
</code></pre>
<p>I want the resulting array C to look like:</p>
<pre><code>array C = [[0, 0, 4, 0, 0],
[0, 4, 4, 4, 0],
[0, 0, 4, 0, 0],
[0, 0, 0, 0, 4],
[5, 0, 0, 4, 0],
[5, 5, 0, 4, 0]]
</code></pre>
<p>EDIT: For my purposes, an 'object' in A cannot belong to more than one 'object' in B. For example, each non-zero element in A (above) is mapped to either a 4 or a 5 in B, but never both. </p>
<p>Sorry if that explanation is a bit convoluted. I would be grateful for any help or guidance anyone can provide. </p>
|
<p>This works:</p>
<pre class="lang-py prettyprint-override"><code>C = np.zeros_like(A)
labels = set(A.flatten()) - {0}
for label in labels:
mask = (A == label)
value = set(B[mask].flatten()) - {0}
C[mask] = [*value][0]
</code></pre>
<p>Maybe somebody can point more elegant way to find <code>value</code>?</p>
|
numpy
| 0 |
1,904,239 | 63,099,465 |
Can you tell me the difference of using list with index and without index?
|
<p>Tell me the difference and benefits of u both using list with index and list without index?</p>
<pre><code>li=[1,2,'ayush',9,10,11,'yaman']
for i in range(len(li)):
print(li[i])
for ele in li:
print(ele)
</code></pre>
|
<p>The difference is that in first case you can modify the original list and in the second case you cannot:</p>
<pre><code>li=[1,2,'ayush',9,10,11,'yaman']
for ele in li:
ele = 1
print(li)
for i in range(len(li)):
li[i] = 1
print(li)
</code></pre>
<p>yields</p>
<pre><code>[1, 2, 'ayush', 9, 10, 11, 'yaman']
[1, 1, 1, 1, 1, 1, 1]
</code></pre>
<p>I suggest you read about Python <a href="https://thispointer.com/6-ways-to-get-the-last-element-of-a-list-in-python/" rel="nofollow noreferrer">lists</a>.</p>
|
python|arrays|list|loops
| 1 |
1,904,240 | 32,330,963 |
Voice Recognition using python 2.7 in windows 10
|
<p>I am using python2.7 in my 64 bit Windows10 system. I am working on SimpleCV framework and i want to implement voice recognition to control my vlc media player. Is there any module in SimpleCv or in python2.7 through which i can easily implement voice recognition.If so,please guide me through the produre. Thanks in advance!!</p>
|
<p>Let me begin by saying that I recommend using Python 3 and above, if possible.</p>
<p>Currently I'm developing a Python 3 open-source cross-platform virtual assistant program called Athena Voice: <a href="https://github.com/athena-voice/athena-voice-client" rel="nofollow">https://github.com/athena-voice/athena-voice-client</a></p>
<p>Users can use it much like Siri, Cortana, or Amazon Echo.</p>
<p>It also uses a very simple "module" system where users can easily write their own modules to enhance it's functionality. It would be easy to write a VLC module which lets you control VLC with your voice.</p>
<p>Otherwise, I recommend looking into Pocketsphinx. Pocketsphinx is an offline open-source voice recognition program. It's great for detecting key words/phrases (like commands).</p>
<p>However, I use it solely as a "wake-up-word" engine. I let pocketsphinx passively listen for the word "athena" to be woken up. Once activated, I use Google's Python speech-to-text engine to listen (more accurately) for a command. </p>
<p>I recommend looking into Google's Python speech-to-text and text-to-speech packages.</p>
<p>Both packages can be installed by using the command:</p>
<pre><code>pip install SpeechRecognition gTTS
</code></pre>
<p>Google STT: <a href="https://pypi.python.org/pypi/SpeechRecognition/" rel="nofollow">https://pypi.python.org/pypi/SpeechRecognition/</a></p>
<p>Google TTS: <a href="https://pypi.python.org/pypi/gTTS/1.0.2" rel="nofollow">https://pypi.python.org/pypi/gTTS/1.0.2</a></p>
<p>Pocketsphinx can be pretty complicated to set up. I'd try installing the dependencies listed here: <a href="https://github.com/cmusphinx/pocketsphinx-python" rel="nofollow">https://github.com/cmusphinx/pocketsphinx-python</a></p>
<p>Then try using:</p>
<pre><code>pip install pocketsphinx
</code></pre>
<p>Pocketsphinx and Google STT have PyAudio as a dependency which can be found here (unofficial): <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio</a></p>
|
windows|python-2.7|windows-10|voice-recognition|simplecv
| 1 |
1,904,241 | 28,180,013 |
Can you specify a timeout to git fetch?
|
<p>I have some git commands scripted in python and occasionally <code>git fetch</code> can hang for hours if there is no connectivity. Is there a way to time it out and report a failure instead?</p>
|
<p>I needed to change/set the timeout for this:</p>
<pre><code>$ time git fetch
fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Failed to connect to git.xfce.org port 443: Connection timed out
real 2m11.684s
user 0m0.002s
sys 0m0.005s
</code></pre>
<p>(the 2min11sec probably depends on my <a href="https://github.com/howaboutsynergy/q1q/tree/a0f5b9cda63494c575104a9943b1e6ff1db654b6/OSes/archlinux/etc/sysctl.d" rel="nofollow noreferrer">sysctl</a> settings)</p>
<p>and since this is stackoverflow, I had to patch <code>git</code>(instead of using the <a href="https://stackoverflow.com/a/52222800/11509478"><code>timeout</code></a> command/wrapper) as follows to gain these two variants of specifying a timeout:
<code>~/.gitconfig</code> specified timeout(in seconds):</p>
<pre><code>[http]
connecttimeout = 10
</code></pre>
<p>so,</p>
<pre><code>$ time git fetch
fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Connection timed out after 10009 milliseconds
real 0m10.031s
user 0m0.000s
sys 0m0.004s
</code></pre>
<p>and a way to override that <code>~/.gitconfig</code>-specified timeout via env. var:</p>
<pre><code>$ time GIT_HTTP_CONNECT_TIMEOUT=2 git fetch
fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Connection timed out after 2001 milliseconds
real 0m2.023s
user 0m0.000s
sys 0m0.004s
</code></pre>
<p>The patch in question(applied on latest git master commit 4c86140027f4a0d2caaa3ab4bd8bfc5ce3c11c8a Date: Wed Sep 18 11:55:13 2019 -0700) is:</p>
<pre><code>diff --git a/http.c b/http.c
index 938b9e55af..c46737e48d 100644
--- a/http.c
+++ b/http.c
@@ -83,6 +83,7 @@ static const char *ssl_pinnedkey;
static const char *ssl_cainfo;
static long curl_low_speed_limit = -1;
static long curl_low_speed_time = -1;
+static long curl_connecttimeout = -1; // in seconds, see man 3 CURLOPT_CONNECTTIMEOUT, default(for me, depending on sysctl setting probably!) is 2min10sec
static int curl_ftp_no_epsv;
static const char *curl_http_proxy;
static const char *http_proxy_authmethod;
@@ -354,6 +355,10 @@ static int http_options(const char *var, const char *value, void *cb)
curl_low_speed_time = (long)git_config_int(var, value);
return 0;
}
+ if (!strcmp("http.connecttimeout", var)) { // overriden by env var GIT_HTTP_CONNECT_TIMEOUT
+ curl_connecttimeout = (long)git_config_int(var, value);
+ return 0;
+ }
if (!strcmp("http.noepsv", var)) {
curl_ftp_no_epsv = git_config_bool(var, value);
@@ -935,6 +940,11 @@ static CURL *get_curl_handle(void)
curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
curl_low_speed_time);
}
+ if (curl_connecttimeout >= 0) {
+ //-1 or any negative means don't set a timeout which means (for me, depending on sysctl settings, no doubt) 2min10sec eg. 130sec and quits like: fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Failed to connect to git.xfce.org port 443: Connection timed out
+ //0 means set timeout to 0 which practically doesn't set a timeout and is the same as using a negative value! aka 2min10sec and quits like for -1 (see above)
+ curl_easy_setopt(result, CURLOPT_CONNECTTIMEOUT, curl_connecttimeout); //10L = timeout in 10 seconds instead of 2min10s eg. `git fetch` when: fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Failed to connect to git.xfce.org port 443: Connection timed out --- real 2m10.809s --- because git.xfce.org is down/not responding to ping! see $ man 3 CURLOPT_CONNECTTIMEOUT Setting a timeout quits like: fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Failed to connect to git.xfce.org port 443: Connection timed out
+ }
curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
#if LIBCURL_VERSION_NUM >= 0x071301
@@ -1061,6 +1071,7 @@ void http_init(struct remote *remote, const char *url, int proactive_auth)
{
char *low_speed_limit;
char *low_speed_time;
+ char *connecttimeout;
char *normalized_url;
struct urlmatch_config config = { STRING_LIST_INIT_DUP };
@@ -1151,6 +1162,9 @@ void http_init(struct remote *remote, const char *url, int proactive_auth)
low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
if (low_speed_time != NULL)
curl_low_speed_time = strtol(low_speed_time, NULL, 10);
+ connecttimeout = getenv("GIT_HTTP_CONNECT_TIMEOUT"); // man 3 CURLOPT_CONNECTTIMEOUT ; can also be set in ~/.gitconfig as http.connecttimeout aka [http]\n\tconnecttimeout=10
+ if (connecttimeout != NULL)
+ curl_connecttimeout = strtol(connecttimeout, NULL, 10); //10 is base
if (curl_ssl_verify == -1)
curl_ssl_verify = 1;
@@ -1903,6 +1917,7 @@ static int http_request(const char *url,
curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
+
ret = run_one_slot(slot, &results);
if (options && options->content_type) {
</code></pre>
<p>Extras:<br>
to override the <code>~/.gitconfig</code>-set timeout and either set the timeout to 0 (which means no timeout because of how libcurl acts when CURLOPT_CONNECTTIMEOUT is set to 0) or simply not set any timeout(which currently means the same: no timeout because git doesn't touch/set CURLOPT_CONNECTTIMEOUT), either of these values will work: 0, or any negative value, ie.</p>
<pre><code>$ time GIT_HTTP_CONNECT_TIMEOUT=0 git fetch
fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Failed to connect to git.xfce.org port 443: Connection timed out
real 2m11.255s
user 0m0.000s
sys 0m0.004s
$ time GIT_HTTP_CONNECT_TIMEOUT=-1 git fetch
fatal: unable to access 'https://git.xfce.org/xfce/xfce4-panel/': Failed to connect to git.xfce.org port 443: Connection timed out
real 2m8.710s
user 0m0.000s
sys 0m0.006s
</code></pre>
<p>Tested on archlinux:<br>
local/curl 7.66.0-1<br>
local/git 2.23.0.r256.g4c86140027-1 </p>
|
python|git|timeout
| 2 |
1,904,242 | 13,811,575 |
python scripts issue (no module named ...) when starting in rc.local
|
<p>I'm facing of a strange issue, and after a couple of hour of research I'm looking for help / explanation about the issue.
It's quite simple, I wrote a cgi server in python and I'm working with some libs including pynetlinux for instance.
When I'm starting the script from terminal with any user, it works fine, no bug, no dependency issue. But when I'm trying to start it using a script in rc.local, the following code produce an error.</p>
<p><code>
import sys, cgi, pynetlinux, logging
</code></p>
<p>it produce the following error :</p>
<pre>
Traceback (most recent call last):
File "/var/simkiosk/cgi-bin/load_config.py", line 3, in
import cgi, sys, json, pynetlinux, loggin
ImportError: No module named pynetlinux
</pre>
<p>Other dependencies produce similar issue.I suspect some few things like user who executing the script in rc.local (root normaly) and trying some stuff found on the web without success.</p>
<p>Somebody can help me ?</p>
<p>Thanx in advance.</p>
<p>Regards.</p>
<p>Ollie314</p>
|
<p>First of all, you need to make sure if the module you want to import is installed properly. You can check if the name of the module exists in <code>pip list</code></p>
<p><br>
Then, in a python shell, check what the paths are where Python is looking for modules:</p>
<pre><code> import sys
sys.path
</code></pre>
<p>In my case, the output is:</p>
<pre><code>['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
</code></pre>
<p><br>
Finally, append those paths to $PATH variable in /etc/rc.local. Here is an example of my rc.local:</p>
<pre><code> #!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing
export PATH="$PATH:/usr/lib/python3.4:/usr/lib/python3.4/plat-x86_64-linux-gnu:/usr/lib/python3.4/lib-dynload:/usr/local/lib/python3.4/dist-packages:/usr/lib/python3/dist-packages"
# Do stuff
exit 0
</code></pre>
|
python|dependency-management
| 4 |
1,904,243 | 34,560,324 |
SQLAlchemy/MySQL binary blob is being utf-8 encoded?
|
<p>I'm using <a href="http://www.sqlalchemy.org/" rel="nofollow noreferrer">SQLAlchemy</a> and MySQL, with a <code>files</code> table to store files. That table is defined as follows:</p>
<pre><code>mysql> show full columns in files;
+---------+--------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+---------+--------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| id | varchar(32) | utf8_general_ci | NO | PRI | NULL | | select,insert,update,references | |
| created | datetime | NULL | YES | | NULL | | select,insert,update,references | |
| updated | datetime | NULL | YES | | NULL | | select,insert,update,references | |
| content | mediumblob | NULL | YES | | NULL | | select,insert,update,references | |
| name | varchar(500) | utf8_general_ci | YES | | NULL | | select,insert,update,references | |
+---------+--------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
</code></pre>
<p>The content column of type <code>MEDIUMBLOB</code> is where the files are stored. In SQLAlchemy that column is declared as:</p>
<pre><code>__maxsize__ = 12582912 # 12MiB
content = Column(LargeBinary(length=__maxsize__))
</code></pre>
<p>I am not quite sure about the difference between SQLAlchemy's <a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.BINARY" rel="nofollow noreferrer"><code>BINARY</code></a> type and <a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.LargeBinary" rel="nofollow noreferrer"><code>LargeBinary</code></a> type. Or the difference between MySQL's <a href="http://dev.mysql.com/doc/refman/5.7/en/binary-varbinary.html" rel="nofollow noreferrer"><code>VARBINARY</code></a> type and <a href="http://dev.mysql.com/doc/refman/5.7/en/blob.html" rel="nofollow noreferrer"><code>BLOB</code></a> type. And I am not quite sure if that matters here.</p>
<p><strong>Question:</strong> Whenever I store an actual binary file in that table, i.e. a Python <a href="https://docs.python.org/3/library/functions.html#bytes" rel="nofollow noreferrer"><code>bytes</code></a> or <code>b''</code> object , then I get the following warning</p>
<pre><code>.../python3.4/site-packages/sqlalchemy/engine/default.py:451: Warning: Invalid utf8 character string: 'BCB121'
cursor.execute(statement, parameters)
</code></pre>
<p>I don't want to just ignore the warning, but it seems that the files are in tact. How do I handle this warning gracefully, how can I fix its cause?</p>
<p><strong>Side note:</strong> <a href="https://stackoverflow.com/questions/14734812/is-a-blob-converted-using-the-current-default-charset-in-mysql">This question</a> seems to be related, and it seems to be a MySQL bug that it tries to convert <em>all</em> incoming data to UTF-8 (<a href="https://stackoverflow.com/questions/14734812/is-a-blob-converted-using-the-current-default-charset-in-mysql#14745685">this answer</a>).</p>
|
<p>Turns out that this was a driver issue. Apparently the default MySQL driver stumbles with Py3 and utf8 support. Installing <a href="https://pypi.python.org/pypi/cymysql" rel="nofollow noreferrer">cymysql</a> into the virtual Python environment resolved this problem and the warnings disappear.</p>
<p><strong>The fix:</strong> Find out if MySQL connects through socket or port (see <a href="https://stackoverflow.com/questions/6885164/pymysql-cant-connect-to-mysql-on-localhost#14351678">here</a>), and then modify the connection string accordingly. In my case using a socket connection:</p>
<pre><code>mysql+cymysql://user:pwd@localhost/database?unix_socket=/var/run/mysqld/mysqld.sock
</code></pre>
<p>Use the <code>port</code> argument otherwise.</p>
<p><strong>Edit:</strong> While the above fixed the encoding issue, it gave rise to another one: blob size. Due to <a href="https://github.com/nakagami/CyMySQL/issues/13" rel="nofollow noreferrer">a bug in CyMySQL</a> blobs larger than 8M fail to commit. Switching to <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow noreferrer">PyMySQL</a> fixed that problem, although it seems to have a <a href="https://github.com/PyMySQL/PyMySQL/issues/397" rel="nofollow noreferrer">similar issue</a> with large blobs.</p>
|
mysql|python-3.x|utf-8|sqlalchemy|blob
| 1 |
1,904,244 | 27,363,230 |
python unittest with coverage report on (sub)processes
|
<p>I'm using <code>nose</code> to run my "unittest" tests and have <code>nose-cov</code> to include coverage reports. These all work fine, but part of my tests require running some code as a <code>multiprocessing.Process</code>. The <code>nose-cov</code> docs state that it can do <code>multiprocessing</code>, but I'm not sure how to get that to work.</p>
<p>I'm just running tests by running <code>nosetests</code> and using the following <code>.coveragerc</code>:</p>
<pre><code>[run]
branch = True
parallel = True
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
# Have to re-enable the standard pragma
pragma: no cover
# Don't complain about missing debug-only code:
def __repr__
#if self\.debug
# Don't complain if tests don't hit defensive assertion code:
raise AssertionError
raise NotImplementedError
# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
def __main__\(\):
omit =
mainserver/tests/*
</code></pre>
<h2>EDIT:</h2>
<p>I fixed the <code>parallel</code> switch in my ".coveragerc" file. I've also tried adding a <code>sitecustomize.py</code> like so in my site-packages directory:</p>
<pre><code>import os
import coverage
os.environ['COVERAGE_PROCESS_START']='/sites/metrics_dev/.coveragerc'
coverage.process_startup()
</code></pre>
<p>I'm pretty sure it's still not working properly, though, because <strong>the "missing" report still shows lines that I know are running (they output to the console)</strong>. I've also tried adding the environment variable in my test case file and also in the shell before running the test cases. I also tried explicitly calling the same things in the function that's called by <code>multiprocessing.Process</code> to start the new process.</p>
|
<p>Another thing to consider is if you see more than one coverage file while running coverage. Maybe it's only a matter of combining them afterwards.</p>
|
python|python-3.x|nose|nosetests|coverage.py
| 1 |
1,904,245 | 12,371,884 |
Ubuntu python-dateutil install/upgrade issue. dateutil.zoneinfo.gettz returning NoneType
|
<p>I am having trouble with python dateutil.zoneinfo module.
Note: </p>
<ul>
<li>Broken Ubuntu machine is ( Ubuntu 11.04 )</li>
<li>Working Ubuntu machine is ( Ubuntu 11.10 )</li>
</ul>
<p><em>Broken Ubuntu machine:</em></p>
<pre><code>In [1]: from dateutil import zoneinfo`
In [2]: from_zone = zoneinfo.gettz('UTC')
In [3]: from_zone
</code></pre>
<p><em>From a working Ubuntu machine:</em></p>
<pre><code>In [1]: from dateutil import zoneinfo
In [2]: from_zone = zoneinfo.gettz('UTC')
In [3]: from_zone
Out[3]: tzfile('Etc/UTC')
</code></pre>
<p>Some Python introspection.</p>
<p><em>Broken Ubuntu machine:</em></p>
<pre><code>In [5]: zoneinfo.ZONEINFOFILE
</code></pre>
<p><em>From a working Ubuntu machine:</em></p>
<pre><code>In [4]: zoneinfo.ZONEINFOFILE
Out[4]: '/usr/local/lib/python2.7/dist-packages/python_dateutil-1.5-py2.7.egg/dateutil/zoneinfo/zoneinfo-2010g.tar.gz'
</code></pre>
<p>More information:
the broken machine, has upgraded from python 2.6 to python 2.7.
Doing a </p>
<pre><code>$ locate zoneinfo
-- snip --
/usr/lib/pymodules/python2.6/dateutil/zoneinfo
/usr/lib/pymodules/python2.6/dateutil/zoneinfo/__init__.py
/usr/lib/pymodules/python2.6/dateutil/zoneinfo/__init__.pyc
/usr/lib/pymodules/python2.7/dateutil/zoneinfo
/usr/lib/pymodules/python2.7/dateutil/zoneinfo/__init__.py
/usr/lib/pymodules/python2.7/dateutil/zoneinfo/__init__.pyc
/usr/local/lib/python2.6/dist-packages/dateutil/zoneinfo
/usr/local/lib/python2.6/dist-packages/dateutil/zoneinfo/__init__.py
/usr/local/lib/python2.6/dist-packages/dateutil/zoneinfo/__init__.pyc
/usr/local/lib/python2.6/dist-packages/dateutil/zoneinfo/zoneinfo-2010g.tar.gz
/usr/local/lib/python2.6/dist-packages/dateutil/zoneinfo/zoneinfo-2011d.tar.gz
/usr/share/zoneinfo
/usr/share/pyshared/dateutil/zoneinfo
-- snip --
</code></pre>
<p>I can see the issue but I am unsure about what to do about it.
Note: I tried re-installing the python-dateutil with 'synaptic package manager' to no avail.</p>
|
<p>I know this is 8 months later, but I had the same issue. My solution was to uninstall the existing version via:</p>
<p><code>sudo pip uninstall python-dateutil</code></p>
<p>then reinstall via</p>
<p><code>sudo easy_install python-dateutil</code></p>
<p>I hope this helps someone.</p>
|
python|linux|ubuntu|ubuntu-11.04
| 6 |
1,904,246 | 7,969,746 |
annotate() adding more than needed
|
<p>I'm having a small issue with my annotate(sum()) function. Now what I want it to do is show a total for all maturities in the given plan, inside the list. Which for the first one it does. Code below:</p>
<pre><code>#get the invesments maturing this year
for p in plans:
cur_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = current_year)
nxt_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = next_yr)
thr_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = thr_yr)
fr_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = fr_yr)
fv_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = fv_yr)
for inv in cur_inv:
total += inv.amount or 0
for inv in cur_inv:
total_m += inv.maturity_amount or 0
for inv in nxt_inv:
total2 += inv.amount or 0
for inv in nxt_inv:
total_m2 += inv.maturity_amount or 0
for inv in thr_inv:
total3 += inv.amount or 0
for inv in thr_inv:
total_m3 += inv.maturity_amount or 0
for inv in fr_inv:
total4 += inv.amount or 0
for inv in fr_inv:
total_m4 += inv.maturity_amount or 0
for inv in fv_inv:
total5 += inv.amount or 0
for inv in fv_inv:
total_m5 += inv.maturity_amount or 0
#Calculate the holding totals with each company
total_list = p.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution__abbr').annotate(Sum('maturity_amount')).order_by('financial_institution__abbr')
gtotal = total_m + total_m2 + total_m3 + total_m4 + total_m5
plan_list.append({
'plan':p,
'investment': cur_inv,
'nxt_inv': nxt_inv,
'thr_inv': thr_inv,
'fr_inv': fr_inv,
'fv_inv': fv_inv,
'total_list': total_list,
'grand': gtotal,
})
</code></pre>
<p>My only issue now, is that when it goes to the next plan, it continues to add to the grand total, instead of going back to 0. </p>
<p>Am I missing something? </p>
<p>Any help would be appreciated.</p>
<p>Thanks</p>
|
<p>You're using <code>+=</code> with the <code>total_m*</code> vars but never resetting them to <code>0</code> in your loop. They don't automatically reset, just because a new iteration has started.</p>
<p>FWIW, you should try to optimize your code here. You're generating 6*len(plans) queries, which could be rather costly.</p>
|
python|django|django-views|annotate
| 1 |
1,904,247 | 41,850,605 |
Python 3.5 Lists management
|
<p>My question is not related to a problem, as such, but I looked at several python scripts, like the one below:</p>
<pre><code>''.join([i if ord(i) < 128 else '' for i in text])
</code></pre>
<p>The list is built on a loop and contains an IF statement. I tried to find in the documentation the structure of such formula (e.g why put the IF in front and the FOR at the end). I am trying to understand the logic behind, in order to be able to build and develop my own formula. Unfortunately, despite all the documentation I looked on the net and books I bought, the information was pretty basic (usually they use enumerated lists and that's it). Could any of you give me a link to a doc that would be a bit more explicit on this topic ?</p>
<p>I recently discovered the <code>dict(zip(a,b))</code>-way to build dictionary, but the lack of understanding of this topic keeps me behind...</p>
<p>Best Regards,</p>
|
<p>Those are List Comprehensions and are pretty much a condensed for loop to cover common loop patterns with less code. ( <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions</a> )</p>
|
list|python-3.x
| 1 |
1,904,248 | 47,413,359 |
Asyncio exception handler: not getting called until event loop thread stopped
|
<p>I am setting an exception handler on my asyncio event loop. However, it doesn't seem to be called until the event loop thread is stopped. For example, consider this code:</p>
<pre><code>def exception_handler(loop, context):
print('Exception handler called')
loop = asyncio.get_event_loop()
loop.set_exception_handler(exception_handler)
thread = Thread(target=loop.run_forever)
thread.start()
async def run():
raise RuntimeError()
asyncio.run_coroutine_threadsafe(run(), loop)
loop.call_soon_threadsafe(loop.stop, loop)
thread.join()
</code></pre>
<p>This code prints "Exception handler called", as we might expect. However, if I remove the line that shuts-down the event loop (<code>loop.call_soon_threadsafe(loop.stop, loop)</code>) it no longer prints anything.</p>
<p>I have a few questions about this:</p>
<ul>
<li><p>Am I doing something wrong here?</p></li>
<li><p>Does anyone know if this is the intended behaviour of asyncio exception handlers? I can't find anything that documents this, and it seems a little strange to me. </p></li>
</ul>
<p>I'd quite like to have a long-running event loop that logs errors happening in its coroutines, so the current behaviour seems problematic for me.</p>
|
<p>There are a few problems in the code above:</p>
<ul>
<li><code>stop()</code> does not need a parameter</li>
<li>The program ends before the coroutine is executed (<code>stop()</code> was called before it).</li>
</ul>
<p>Here is the fixed code (without exceptions and the exception handler):</p>
<pre><code>import asyncio
from threading import Thread
async def coro():
print("in coro")
return 42
loop = asyncio.get_event_loop()
thread = Thread(target=loop.run_forever)
thread.start()
fut = asyncio.run_coroutine_threadsafe(coro(), loop)
print(fut.result())
loop.call_soon_threadsafe(loop.stop)
thread.join()
</code></pre>
<p><code>call_soon_threadsafe()</code> returns a future object which holds the exception (it does not get to the default exception handler):</p>
<pre><code>import asyncio
from pprint import pprint
from threading import Thread
def exception_handler(loop, context):
print('Exception handler called')
pprint(context)
loop = asyncio.get_event_loop()
loop.set_exception_handler(exception_handler)
thread = Thread(target=loop.run_forever)
thread.start()
async def coro():
print("coro")
raise RuntimeError("BOOM!")
fut = asyncio.run_coroutine_threadsafe(coro(), loop)
try:
print("success:", fut.result())
except:
print("exception:", fut.exception())
loop.call_soon_threadsafe(loop.stop)
thread.join()
</code></pre>
<p>However, coroutines that are called using <code>create_task()</code> or <code>ensure_future()</code> will call the exception_handler:</p>
<pre><code>async def coro2():
print("coro2")
raise RuntimeError("BOOM2!")
async def coro():
loop.create_task(coro2())
print("coro")
raise RuntimeError("BOOM!")
</code></pre>
<p>You can use this to create a small wrapper:</p>
<pre><code>async def boom(x):
print("boom", x)
raise RuntimeError("BOOM!")
async def call_later(coro, *args, **kwargs):
loop.create_task(coro(*args, **kwargs))
return "ok"
fut = asyncio.run_coroutine_threadsafe(call_later(boom, 7), loop)
</code></pre>
<p>However, you should probably consider using a <a href="https://docs.python.org/3/library/queue.html" rel="noreferrer">Queue</a> to communicate with your thread instead.</p>
|
python|python-asyncio
| 6 |
1,904,249 | 47,264,636 |
Getting error while running exe created by cx_freeze
|
<p>I have converted my Python script into an exe file, it works perfectly on my machine, I installed it in a different machine which doesn't have Python in it.
I get this error message while running the exe.</p>
<pre><code>File "C:\ProgramData\Anaconda3\lib\site-packages\cx_Freeze\initscripts\__start
up__.py", line 12, in <module>
File "C:\ProgramData\Anaconda3\lib\site-packages\cx_Freeze\initscripts\Console
.py", line 24, in <module>
File "Text.py", line 9, in <module>
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\__init__.py", line 18,
in <module>
ImportError: Missing required dependencies ['numpy']
</code></pre>
<p>setup.py:</p>
<pre><code>import sys,os
from cx_Freeze import setup, Executable
import matplotlib
os.environ['TCL_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tk8.6'
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
setup( name = "Text Analyzer" , version = "0.1" , description = "Test Case Analyzer" , executables = [Executable("Text.py"),Executable("Text_Get.py")] )
</code></pre>
<p>The machine does not have Python so why it is referring to the <code>C:\ProgramData\Anaconda3</code> path. </p>
<p>Please help.</p>
|
<p>Since <em>init</em>.py in panda check for hard dependency it throws error.
to fix this add numpy in packages list.
build_exe_options = {"packages": ["os","numpy"], "excludes": ["tkinter"]}</p>
|
python|exe|cx-freeze
| 0 |
1,904,250 | 57,410,810 |
Speeding up data insertion from pandas dataframe to mysql
|
<p>I need to insert a 60000x24 dataframe into a mysql database (MariaDB) using sqlalchemy and python. The database runs locally and the data insertion runs locally as well. For now I have been using the LOAD DATA INFILE sql query, but this requires the dataframe to be dumped into a CSV file, which takes about 1.5-2 seconds. The problem is I have to insert 40 or more of these dataframes, so the time is critical.</p>
<p>If I use df.to_sql then the problem gets much worse. The data insertion takes at least 7 (up to 30) seconds per dataframe.</p>
<p>The code IΒ΄m using is provided here below:</p>
<pre><code>sql_query ="CREATE TABLE IF NOT EXISTS table(A FLOAT, B FLOAT, C FLOAT)"# 24 columns of type float
cursor.execute(sql_query)
data.to_sql("table", con=connection, if_exists="replace", chunksize=1000)
</code></pre>
<p>Which takes between 7 and 30 seconds to be executed. Using LOAD DATA, the code looks like:</p>
<pre><code>sql_query = "CREATE TABLE IF NOT EXISTS table(A FLOAT, B FLOAT, C FLOAT)"# 24 columns of type float
cursor.execute(sql_query)
data.to_csv("/tmp/data.csv")
sql_query = "LOAD DATA LOW_PRIORITY INFILE '/tmp/data.csv' REPLACE INTO TABLE 'table' FIELDS TERMINATED BY ','; "
cursor.execute(sql_query)
</code></pre>
<p>This takes 1.5 to 2 seconds, mainly due to dumping the file to CSV. I could improve this last one a bit by using LOCK TABLES, but then no data is added into the database. So, my questions here is, is there any method to speed this process up, either by tweaking LOAD DATA or to_sql?</p>
<p><strong>UPDATE:</strong>
By using an alternative function to dump the dataframes into CSV files given by this answer <a href="https://stackoverflow.com/questions/15417574/what-is-the-fastest-way-to-output-large-dataframe-into-a-csv-file/54617862#54617862">What is the fastest way to output large DataFrame into a CSV file?</a>
IΒ΄m able to improve a little bit of the performance, but not that significantly.
Best,</p>
|
<p>If you know the data format (I assume all floats), you can use <code>numpy.savetxt()</code> to drastically reduce time needed to create CSV:</p>
<pre><code>%timeit df.to_csv(csv_fname)
2.22 s Β± 21.3 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
from numpy import savetxt
%timeit savetxt(csv_fname, df.values, fmt='%f', header=','.join(df.columns), delimiter=',')
714 ms Β± 37.7 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
</code></pre>
<p>Please note that you may need to prepend</p>
<pre><code>df = df.reset_index()
</code></pre>
<p>to have lines numbered with unique keys and retain the <code>.to_csv()</code> formatting style.</p>
|
python|mysql|pandas|performance|mariadb
| 5 |
1,904,251 | 11,965,907 |
Call php from python over telnet
|
<p>I'm trying to call some php scripts from simple telnet-server written in python. Here it's a code.</p>
<pre><code> # -*- coding: utf8 -*-
#!/usr/bin/env python
# ΡΠΊΡΠΈΠΏΡ ΠΏΠ΅ΡΠ΅ΠΊΠΈΠ΄ΡΠ²Π°Π΅Ρ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ Π½ΡΠΆΠ½ΠΎΠ³ΠΎ ΡΠΊΡΠΈΠΏΡΠ° Π½Π° ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ½Π½ΡΠΉ ΠΏΠΎΡΡ
import socket
import os
from commands import *
import subprocess
#define server properties
host = ''
port = 5000
backlog = 5
size = 1024
# configure the server socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
# handle client requests
while 1:
client, address = s.accept()
data = client.recv(size)
print data
if data:
#Π½Π°Ρ
ΠΎΠ΄ΠΈΠΌ ΠΏΡΡΡ Π΄Π»Ρ Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΠΌΠΎΠ³ΠΎ ΡΠΊΡΠΈΠΏΡΠ°
recvCommand = data[5:]
print recvCommand
userCommand = u'' + recvCommand
#userCommand = u''+'/home/mechanic/python/forloop.php'
res = subprocess.call(["php", userCommand])
client.send(data)
35 client.close()
</code></pre>
<p>At the terminal I connect to localhost (telnet localhost 5000) and run command 'calc /home/mechanic/python/forloop.php'. The path is exist in system and I can run him manually.
But script returned me this error:</p>
<pre><code>Could not open input file: /home/mechanic/python/forloop.php
</code></pre>
<p>But if I write this path manually in python script </p>
<pre><code>userCommand = u''+'/home/mechanic/python/forloop.php'
</code></pre>
<p>All works fine. Where can I take the mistake?</p>
<p>P.S. Here it's a code of forloop.php</p>
<pre><code><?
for ( $i = 0 ; $i <= 1000000; $i++ )
echo "Welcome $i times\n";
?>
</code></pre>
|
<p>Have you tried using <code>recvCommand.strip()</code> instead of original? I think recvCommand contains newline and carriage return from telnet client.</p>
<p>Your command receiving may sometime fail, there is no guarantee all data will arrive in single recv call. You should concatenate data until you receive newline.
In some cases, your command might arrive in more than one buffers, your code won't be able to work with that.</p>
|
php|python|telnet
| 2 |
1,904,252 | 11,943,831 |
Python: how to put constructors in map() function?
|
<p>Say I have a class, with a constructor that takes an integer. I have a list of integers. How do I use <code>map()</code> to create a list of objects of this class, each constructed with its respective integer?</p>
|
<p>As any other function?</p>
<pre><code>>>> class Num(object):
... def __init__(self, i):
... self.i = i
...
>>> print map(Num, range(10))
[<__main__.Num object at 0x100493450>, <__main__.Num object at 0x100493490>, <__main__.Num object at 0x1004934d0>, <__main__.Num object at 0x100493510>, <__main__.Num object at 0x100493550>, <__main__.Num object at 0x100493590>, <__main__.Num object at 0x1004935d0>, <__main__.Num object at 0x100493610>, <__main__.Num object at 0x100493650>, <__main__.Num object at 0x100493690>]
</code></pre>
|
python|functional-programming
| 21 |
1,904,253 | 33,723,803 |
Dot product with shapes (x) and (x, y)
|
<p>I am really new to numpy, so I am having some troubles understanding the dot product.</p>
<p>I have this simple piece of code:</p>
<pre><code>import numpy as np
A = np.ones((5))
B = np.ones((5,10))
A.dot(B)
# array([ 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.])
A.dot(B).shape
# (10,)
</code></pre>
<p>I cannot understand what is happening in this code. I am a little confused, because it seems that a shape of <code>(10,)</code>is not a column vector, because the transpose is the same.</p>
<p>Is <code>A</code>being broadcasted? I thought that <code>A</code> should be broadcasted to the shape of <code>(5,5)</code>, so it could be multiplied with <code>B</code> and thus returning an array of shape <code>(5,10)</code>. What am I getting wrong? </p>
|
<p>Numpy makes a difference between 1d arrays (something of shape <code>(N,)</code>) and an 2d array (matrix) with one column (shape <code>(N, 1)</code>) or one row (shape <code>(1, N)</code> aka column- or row-vectors.</p>
<pre><code>>>> a = np.ones((5, 1))
>>> B = np.ones((5, 5))
>>> B.dot(a)
array([[ 5.],
[ 5.],
[ 5.],
[ 5.],
[ 5.]])
</code></pre>
<p>Or unsing python 3.5 with numpy 1.10:</p>
<pre><code>>>> a = np.ones((5, 1))
>>> B = np.ones((5, 5))
>>> B @ a
array([[ 5.],
[ 5.],
[ 5.],
[ 5.],
[ 5.]])
</code></pre>
<p>If you have a 1d array, you can use <code>np.newaxis</code> to make it a row or column vector:</p>
<pre><code>>>> a = np.ones(5)
>>> B = np.ones((5, 5))
>>> B @ a[:, np.newaxis]
array([[ 5.],
[ 5.],
[ 5.],
[ 5.],
[ 5.]])
</code></pre>
<p>Both new row and column:</p>
<pre><code>>>> x = np.arange(5)
>>> B = x[:, np.newaxis] @ x[np.newaxis, :]
>>> B
array([[ 0, 0, 0, 0, 0],
[ 0, 1, 2, 3, 4],
[ 0, 2, 4, 6, 8],
[ 0, 3, 6, 9, 12],
[ 0, 4, 8, 12, 16]])
</code></pre>
|
python|numpy|dot-product
| 0 |
1,904,254 | 27,591,786 |
Python BeautifulSoup - how to extract text between <a> tags
|
<p>i want to extract a number "371" from this source with BeautifulSoup4 in Python3.
I tried many times but i can not make it work, could You help me? Thank You.</p>
<pre><code><a href="/ProviderRedirect.ashx?key=0.16198127.422314246.13.PLN.1277906077&amp;saving=551&amp;source=1-0" id="TotalLink" target="_blank"><span class="hc_pr_cur">PLN</span> 371<span class="hc_pr_syb"></span></a>
</code></pre>
|
<p>Find the <code>span</code> tag and get the <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow"><code>.next_sibling</code></a>:</p>
<pre><code>soup.find('span', class_='hc_pr_cur').next_sibling.strip()
</code></pre>
<p>Demo:</p>
<pre><code>>>> from bs4 import BeautifulSoup
>>>
>>> data = '<a href="/ProviderRedirect.ashx?key=0.16198127.422314246.13.PLN.1277906077&amp;saving=551&amp;source=1-0" id="TotalLink" target="_blank"><span class="hc_pr_cur">PLN</span> 371<span class="hc_pr_syb"></span></a>'
>>>
>>> soup = BeautifulSoup(data)
>>> soup.find('span', class_='hc_pr_cur').next_sibling.strip()
u'371'
</code></pre>
|
python|html|beautifulsoup
| 0 |
1,904,255 | 65,670,259 |
Every Python-related executable broken: "Fatal Python error: init_import_size: Failed to import the site module"
|
<p>I'm very new to python and especially to its ecosystem. Today, I was trying to invoke a python command from my command line that worked perfectly yesterday, but today I got the following fatal error:</p>
<pre><code>Fatal Python error: init_import_size: Failed to import the site module
Python runtime state: initialized
ModuleNotFoundError: No module named 'site'
Current thread 0x00000cac (most recent call first):
<no Python frame>
</code></pre>
<p>While trying to find the problem, I soon realized that it was not special to my command. In fact, all python-related executables produce the same error when invoked from any command prompt, no matter where I am in my filesystem. <code>python</code>, <code>python3</code>, <code>anaconda</code> (and its prompt), <code>conda</code>, <code>pip</code>, <code>pip3</code>, ... All of these suddenly don't work anymore. They all fail with the same error message, only the thread is altering.</p>
<p>In my research I found a very similar error very often, but it was about the <code>encodings</code> module. Also I haven't read about issues where the entire python ecosystem just broke.</p>
<p>Solutions to said similar error seem to include doing something with the <code>PYTHONPATH</code> and <code>PYTHONHOME</code> envs <strong>if they exist</strong>. But I don't have them, neither as user variable nor as system var.</p>
<p>I installed python by installing anaconda3 via scoop. It should be the latest version (2020.11). I've been using the installation inside of <code>PyCharm</code> as well as via the command line.</p>
<p>Does anyone know what the problem here could be? I'm kinda stuck here because I can't even use conda or pip for diagnostics, like calling <code>conda list</code> to find out more about the <code>site</code> packages' status. So, if anyone could help me with this, I'd be very thankful!</p>
|
<p>I had this error.</p>
<p>For me, I had some project tree (fictitious):</p>
<pre><code>doc/
βββ project/
β βββ embedded/
| | βββ __init__.py
β β βββ deep_file
β β βββ utils/
β β βββ os.py # < This one! Look here!!
β β βββ deep/
β β βββ folder/
β β βββ very_deep_file
β βββ less_deep_file
|...
</code></pre>
<p>Within this tree, I had a file named <code>.../utils/os.py</code>.</p>
<p>Pycharm debug mode would find this <code>os.py</code> and use it in place of <a href="https://docs.python.org/3/library/os.html" rel="nofollow noreferrer">the default <code>os.py</code></a>. To solve this problem, I renamed <code>os.py</code> to something else.</p>
<p>What a dummy I am! Hopefully this saves other people time and headache!!</p>
|
python|pip|conda
| 2 |
1,904,256 | 43,103,069 |
Flask set_response for domain (not just subdomain)
|
<p>So when users of my site visit a.mysite.com, my flask server is setting the browser in their cookie via: </p>
<pre><code>@app.route('/safe')
def tag_browser():
response = redirect('/')
response.set_cookie('hello', 'world')
return response
</code></pre>
<p>This sets the cookie for <strong>a.mysite.com</strong>. However, I am interested to set the cookie for <strong>mysite.com</strong> </p>
<p>There is this thread: <a href="https://stackoverflow.com/questions/18492576/share-cookie-between-subdomain-and-domain/23086139#23086139">Share cookie between subdomain and domain</a> which talks about how I can achieve the same effect wth</p>
<pre><code>Set-Cookie: name=value; domain=mydomain.com
</code></pre>
<p>My problem is, how can I do so inside flask?</p>
|
<p>Looks like the <code>set_cookie</code> function can get <code>domain</code> as param. From the <a href="http://flask.pocoo.org/docs/0.12/api/" rel="nofollow noreferrer">documentation</a>:</p>
<pre><code>set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)
</code></pre>
<blockquote>
<p>domain β if you want to set a cross-domain cookie. For example,
domain=".example.com" will set a cookie that is readable by the domain
www.example.com, foo.example.com etc. Otherwise, a cookie will only be
readable by the domain that set it.</p>
</blockquote>
|
python|cookies|flask
| 2 |
1,904,257 | 43,468,794 |
Using gdal in canopy, hdf file is not supported
|
<p>I want to recreate this code in Canopy:</p>
<p><a href="https://jgomezdans.github.io/gdal_notes/ipython.html" rel="nofollow noreferrer">https://jgomezdans.github.io/gdal_notes/ipython.html</a></p>
<p>But if I do exactly the same I get the error:</p>
<pre><code>ERROR 4: `\Users\Lisa\Documents\Data1.hdf'
</code></pre>
<p>So I tried to import a couple of libraries that can help me, but I still get the same error.</p>
<pre><code>from osgeo import gdal
#import numpy as np?
# import pyhdf?
#import pandas as pd?
#import hdf5
g = gdal.Open("\Users\Lisa\Documents\Data1.hdf")
</code></pre>
<p>So I tried a few combinations with the different libraries, but it still doesn't work.</p>
<p>(NOTE: <code>import hdf5</code> hasn't work yet <a href="https://stackoverflow.com/questions/43466901/package-manager-canopy-error-import-hdf5">https://stackoverflow.com/questions/43466901/package-manager-canopy-error-import-hdf5</a>)</p>
<p>Has anybody an idea which library is necessary or why my code isn't working?</p>
|
<p>It looks like your path string contains unescaped backslashes by accident. Python interprets these as <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals" rel="nofollow noreferrer">escape sequences</a>.</p>
<p>Try doing <code>g = gdal.Open(r"\Users\Lisa\Documents\Data1.hdf")</code>. Note the <code>r</code>-prefix in front of the string literal which marks the string as "raw" and keeps the backslashes as is. </p>
|
python|gdal|canopy
| 1 |
1,904,258 | 43,137,781 |
Django 1.10.6 - MP3 Upload and player
|
<p>For a job interview I need to code a website consisting of at least 3 pages for a fictional band's website using Django.</p>
<p>My idea is to:</p>
<ul>
<li>have a front page with blog posts from the band, the most recent one on top.</li>
<li>have an admin page where I can upload the band's songs.</li>
<li>have a page with a list of songs that can be played by clicking on the song.</li>
</ul>
<p>I know very basic html and css (did some one codecademy).
I did the Django tutorial up until part 6 <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial06/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/1.10/intro/tutorial06/</a></p>
<p>I'm just not very sure how to go about doing this. (Would I use "static files" for the mp3's? How does one set up a blog format page?)</p>
<p>So I'm just hoping for a nudge in the right direction. Any links to tutorials or books or anything that might be useful would be much appreciated.</p>
|
<p>I believe this tutorial would be helpful for this project <a href="https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK" rel="nofollow noreferrer">https://www.youtube.com/watch?v=qgGIqRFvFFk&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK</a></p>
|
python|html|django
| 1 |
1,904,259 | 48,585,263 |
Pandas to_csv prefixing 'b' when doing .astype('|S') on column
|
<p>I'm following advice of <a href="https://www.dataquest.io/blog/pandas-big-data/" rel="nofollow noreferrer">this article</a> to reduce Pandas DataFrame memory usage, I'm using <code>.astype('|S')</code> on an object column like so:</p>
<pre><code>data_frame['COLUMN1'] = data_frame['COLUMN1'].astype('|S')
data_frame['COLUMN2'] = data_frame['COLUMN2'].astype('|S')
</code></pre>
<p>Performing this on the DataFrame cuts memory usage by 20-40% without negative impacts on processing the columns. However, when outputting the file using <code>.to_csv()</code>:</p>
<pre><code>data_frame.to_csv(filename, sep='\t', encoding='utf-8')
</code></pre>
<p>The columns with <code>.astype('|S')</code> are outputted with a prefix of b with single quotes:</p>
<pre><code>b'00001234' b'Source'
</code></pre>
<p>Removing the <code>.astype('|S')</code> call and outputting to csv gives the expected behavior:</p>
<pre><code>00001234 Source
</code></pre>
<p>Some googling on this issue does find GitHub issues, but I don't think they are related (looks like they were fixed as well): <a href="https://github.com/pandas-dev/pandas/issues/9712" rel="nofollow noreferrer">to_csv and bytes on Python 3</a>, <a href="https://github.com/pandas-dev/pandas/issues/9712" rel="nofollow noreferrer">BUG: Fix default encoding for CSVFormatter.save</a></p>
<p>I'm on Python 3.6.4 and Pandas 0.22.0. I tested the behavior is consistent on both MacOS and Windows. Any advice on how to output the columns without the b prefix and single quotes?</p>
|
<p>The 'b' prefix indicates a Python 3 <strong>bytes</strong> <a href="http://docs.python.org/py3k/reference/lexical_analysis.html#literals" rel="nofollow noreferrer">literal</a> that represents an object rather than an unicode string. So if you want to remove the prefix you could decode the bytes object using the string decode method before saving it to a csv file:</p>
<pre><code>data_frame['COLUMN1'] = data_frame['COLUMN1'].apply(lambda s: s.decode('utf-8'))
</code></pre>
|
python|pandas
| 3 |
1,904,260 | 66,803,215 |
Find the length of overalp in lists with binary values
|
<p>Assuming I have these two lists:</p>
<pre><code>a = [1,0,0,0,1,1,1,1,1,1,1,1,0,0]
b = [0,0,0,0,1,1,1,0,0,0,1,1,0,0]
</code></pre>
<p>I would like to know the number of times the number 1 appears in the same position, in this case it would be 5</p>
|
<p>Use bitwise operators and zip:</p>
<pre><code>sum([x&y for x,y in zip(a,b)])
</code></pre>
|
python|arrays|list
| 0 |
1,904,261 | 69,326,777 |
Is it better to use 'elif' or consecutive 'if' statements alongside return statements?
|
<p>This question is specifically regarding coding convention. I know that using if or elif in this case will produce the same results. Just wondering which is the "proper" way to construct this function:</p>
<p>With consecutive if:</p>
<pre><code>def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
if selectedCourse.getPrereqs() != 'none':
for prereq in selectedCourse.getPrereqs():
if not self.courses[prereq].hasPassed():
return False
return True
</code></pre>
<p>With elif:</p>
<pre><code>def can_take(self, selectedCourse):
if selectedCourse.hasPassed():
return False
elif selectedCourse.getPrereqs() != 'none':
for prereq in selectedCourse.getPrereqs():
if not self.courses[prereq].hasPassed():
return False
return True
</code></pre>
|
<p>If I had to choose between the two, I would probably use two <code>if</code> statements, but that's just a matter of personal preference.</p>
<p>If I had a <em>third</em> choice, I wouldn't have <em>any</em> <code>return</code> statements with Boolean literals. I would write a single <code>return</code> statement that uses <code>and</code> and <code>or</code>.</p>
<pre><code>return (not selected.hasPassed()
and (selected.getPrereqs() == 'none'
or all(x.hasPassed()
for x in selected.getPrereqs()))
</code></pre>
<p>This is close to how you would describe this in English: you can take the class if you have <strong>not</strong> passed it, <strong>and</strong> if the class either has no prerequisites <strong>or</strong> if you have passed <strong>all</strong> the prerequisites.</p>
<p>As John Kugelman points out, if <code>getPrereqs</code> returned an empty list instead of <code>'none'</code>, you could further reduce this to</p>
<pre><code>return (not selected.hasPassed()
or all(x.hasPassed()
for x in selected.getPrereqs())
</code></pre>
|
python|function|for-loop|object|if-statement
| 4 |
1,904,262 | 48,222,566 |
How can I impute the NA in a dataframe with values randomly selected from a specified normal distribution
|
<p>How can I impute the NA in a dataframe with values randomly selected from a specified normal distribution.
The dataframe df is defined as follows:</p>
<pre><code> A B C D
1 3 NA 4 NA
2 3.4 2.3 4.1 NA
3 2.3 0.1 0.2 6.3
4 3.1 4.5 2.1 0.2
5 4.1 2.5 NA 2.4
</code></pre>
<p>I want to fill the NA with the values randomly select from a generated normal distribution and the values are different.
The mean the normal distribution is the 1% quantile of the values of the given dataframe. The standard deviation is the median SD of the rows in dataframe.</p>
<p>My code is as follows:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import pandas as pd
import numpy as np
df = pd.read_csv('try.txt',sep="\t")
df.index = df['type']
del df['type']
sigma = median(df.std(axis=1))
mu = df.quantile(0.01)
# mean and standard deviation
df = df.fillna(np.random.normal(mu, sigma, 1))</code></pre>
</div>
</div>
</p>
<p>The mean is incorrect and the df can not fill with the simulated array.
How can I complete the work. Thank you.</p>
|
<p>There are a few problems with your code</p>
<pre><code>df.index = df['type']
del df['type']
</code></pre>
<p>can better be expressed as <code>df.set_index('type')</code></p>
<p><code>median(df.std(axis=1))</code> should be <code>df.std(axis=1).median()</code></p>
<p><code>df.quantile()</code> returns a series. If you want the quantile of all the values, you should do <code>df.stack().quantile(0.01)</code></p>
<pre><code>sigma = df.std(axis=1).median()
mu = df.stack().quantile(0.01)
print((sigma, mu))
</code></pre>
<blockquote>
<pre><code> (0.9539392014169454, 0.115)
</code></pre>
</blockquote>
<p>First you have to find the empty fields. Easiest is with <code>.stack</code> and <code>pd.isnull</code></p>
<pre><code>df2 = df.stack(dropna=False)
s = df2[pd.isnull(df2)]
</code></pre>
<p>Now you can impute the random values in 2 ways</p>
<pre><code>ran = np.random.normal(mu, sigma, len(s))
df3 = df.stack(dropna=False)
df3.loc[s.index] = ran
df3.unstack()
</code></pre>
<blockquote>
<pre><code> A B C D
1 3.0 0.38531116198179066 4.0 0.7070154252582993
2 3.4 2.3 4.1 -0.8651789931843614
3 2.3 0.1 0.2 6.3
4 3.1 4.5 2.1 0.2
5 4.1 2.5 -1.3176599584973157 2.4
</code></pre>
</blockquote>
<p>Or via a loop, overwriting the empty fields in the original <code>DataFrame</code></p>
<pre><code>for (row, column), value in zip(s.index.tolist(), np.random.normal(mu, sigma, len(s))):
df.loc[row, column] = value
</code></pre>
|
python|pandas|imputation
| 2 |
1,904,263 | 51,524,095 |
How to format dictionary keys in Python 3x
|
<p>I am trying to format the dictionary key so that I can ask the user for the value and add that to the dictionary.
so far my dictionary looks like this:</p>
<pre><code>{'admin': ' '}
</code></pre>
<p>Expected output:</p>
<pre><code>name: admin
admin's password: admin
</code></pre>
<p>Code:</p>
<pre><code>new dictionary = {'admin': 'admin'}
def example():
name= input("name: ")
#no value yet for the input key
value = ""
dict_users[name] = value
check(dict_users)
def check(name):
if name in dict_users.items():
password = input('{name}'.format(**dict_users) + "s"+ " Password: "))
#add password input to existing dictionary key
dict_users[name] = password
#Dictionary of Users
dict_users = {}
</code></pre>
|
<p>No need to use string formatting here.</p>
<p>Also, see how you have to test if a key exists in a dict</p>
<pre><code>def check(name):
if name in dict_users:
password = input(name + "'s"+ " password: "))
#add password input to existing dictionary key
dict_users[name] = password
</code></pre>
|
python
| 2 |
1,904,264 | 51,484,430 |
Associating numbers with different words python
|
<p>So I have a dataframe (df9), that has several columns, one of which is "ASSET_CLASS", and I also have a variable called "terms". ASSET_CLASS is made up of different names, whereas "terms" is numbers. I want to be able to create a new row in the dataframe that outputs different numbers per row based on the corresponding asset class and # of terms. For example, if Asset_Class is 'A' in a row, and #terms is between 30 and 60 for that row, I want my new column to output the number 5 for that row. Or if Asset_Class is 'A' and #terms is between 0 and 30, the new column shoots out 3 for that row. Or if Asset Class is 'B', and terms is between 30 and 60, then the output in the new column for that row is 8. Anyone have a good idea of how to do this? I was thinking maybe if, else statements, but I'm not sure.</p>
|
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="nofollow noreferrer">numpy.select</a>. To match your first two examples, the following code should add a new column called 'newcol' to your data frame, matching your first two cases, and putting a value of -1 everywhere not covered by explicitly defined cases.</p>
<pre><code>ac = df9.ASSET_CLASS
t = df9.terms
condlist = [(ac=='A') & (t>=30) & (t<60), (ac=='A') & (t>=0) & (t<30)]
choicelist = [5, 3]
df9['newcol'] = np.select(condlist, choicelist, default=-1)
</code></pre>
|
python|pandas
| 2 |
1,904,265 | 17,623,784 |
how to achieve for loop IronPython
|
<p>How to achieve this <code>C#</code> for-loop in <code>IronPython</code>, I can't seem to find a way to make <code>i - 10</code> in <code>IronPython</code></p>
<pre><code> int amount = 32;
int scrolls = 0;
int mets = 0;
if (amount >= 10) {
for (int i = amount; i >= 10; i -= 10) {
scrolls++;
if (i - 10 < 10)
mets = i - 10;
}
}
</code></pre>
|
<p>Your loop exit condition is <code>i >= 10</code>. Your loop entry condition is <code>amount >= 10</code>. <code>i</code> gets set to your <code>amount</code> on loop entry, which is already <code>>= 10</code>. Your loop will never execute.</p>
|
c#|for-loop|ironpython
| 1 |
1,904,266 | 70,429,685 |
Explanation for this no flux boundary code needed
|
<p>Im completely incompetent in programming! Can anyone help me understand what this code does exactly?</p>
<p>According to the notes, it should impose a no-flux boundary condition, but im completely baffled at what the terms indicate. Can anyone explain this to me?</p>
<pre><code> for Z in (U, V):
Z[0,:] = Z[1,:]
Z[-1,:] = Z[-2,:]
Z[:,0] = Z[:,1]
Z[:,-1] = Z[:,-2]
</code></pre>
|
<p><code>Z</code>, as a 2d list, is seemingly the grid representing the discrete state space of your problem. This snippet simply initializes the values corresponding to the boundary rows and columns of the grid as follows:</p>
<p><code>Z[0,:] = Z[1,:]</code>: initialize the leftmost column by the values of its next column;</p>
<p><code>Z[-1,:] = Z[-2,:]</code>: initialize the rightmost column by the values of its previous column;</p>
<p><code>Z[:,0] = Z[:,1]</code>: initialize the top row by the values of its immediate lower row;</p>
<p><code>Z[:,-1] = Z[:,-2]</code>: initialize the bottom row by the values of its immediate upper row.</p>
|
python
| 1 |
1,904,267 | 73,165,636 |
No module named 'importlib.metadata'
|
<p>I'm trying to install Odoo 15.0 on mac (python 3.7) when i come to run the command:
<code>pip3 install -r requirements.txt</code>
I got this error message:
<code> Traceback (most recent call last): File "/usr/local/opt/python@3.7/bin/pip3", line 10, in <module> from importlib.metadata import distribution ModuleNotFoundError: No module named 'importlib.metadata'</code></p>
|
<p>Try installing this lib manually, using :</p>
<p><code>pip install importlib-metadata</code></p>
<p>or</p>
<p><code>pip3 install importlib-metadata</code></p>
|
python|python-3.x|odoo|odoo-15
| 0 |
1,904,268 | 55,924,642 |
Get just the numbers from the dataframe
|
<p>I have this dataframe with one column:</p>
<pre><code> 0
UPB 2.260241e+08
Voluntary Payoffs 0.000000e+00
Involuntary Payoffs 3.169228e+06
Loan Loss 0.000000e+00
Cost Basis 2.221221e+08
Cost Basis Liquidated 3.149118e+06
Escrow Advances 0.000000e+00
Corp Advances 0.000000e+00
Loan Count 6.670000e+02
Loan Count of Paying Loans 5.510000e+02
</code></pre>
<p>I want to just get the numbers into a list. I tried using iloc, ix, etc... but I am not getting just the numbers.</p>
|
<pre><code>df.values.squeeze().tolist()
</code></pre>
<p>And if you want a better format:</p>
<pre><code>df.values.apply(lambda x: np.round(x, 2)).squeeze().tolist()
</code></pre>
|
python|pandas
| 1 |
1,904,269 | 50,219,452 |
Flask test fails with 200 != <Response streamed [200 OK]>
|
<p>I am currently writing a test that is supposed to test my Flask (actually connexion, which uses flask) API. In this test I have the following to statements:</p>
<pre><code>response_add_subscription_1 = self.app.post(
'/user/alice/data_source/{}/subscriptions/{}'.format(ds_uuid1, dp_uuid), content_type='application/json')
self.assertEqual(200, response_add_subscription_1._status_code, "Status code of response for subscription "
"registration of alice is not 200!")
</code></pre>
<p>However, when running the test, it throws on the assert statement, saying:</p>
<pre><code>AssertionError: 200 != <Response streamed [200 OK]>
</code></pre>
<p>When I change the assertion to</p>
<pre><code>self.assertEqual('<Response streamed [200 OK]>', response_add_subscription_1._status_code, "Status code of response for subscription registration of alice is not 200!")
</code></pre>
<p>It still throws, but this time the AssertionError is the other way around:</p>
<pre><code>AssertionError: '<Response streamed [200 OK]>' != 200
</code></pre>
<p>So it seems, my status code is <code>200</code> and <code>'<Response streamed [200 OK]>'</code> at the same time, but never what I assert. Can anyone give me a hint what I am doing wrong here? My assertion code works on other API resources...</p>
|
<p>I was using content-type application/json even though I did not pass any json with the post request...</p>
|
python|python-3.x|flask
| 0 |
1,904,270 | 66,713,626 |
How to create a list out of this for-loop code?
|
<p>This should not be too hard, I just really cannot figure it out. I have this set of code:</p>
<pre><code>file_open=open('mbox-short.txt','r')
counter=0
for line in file_open:
if line.startswith('From:') and line.find('localhost')==-1:
counter+=1
line.strip()[6:]
file_open.close()
</code></pre>
<p>I am wondering how I can save the results of this loop in a list. Thank you!</p>
|
<p>.append() to append eleman to list</p>
<pre><code>file_open=open('mbox-short.txt','r')
list = []
counter=0
for line in file_open:
if line.startswith('From:') and line.find('localhost')==-1:
counter+=1
list.append(line.strip()[6:])
file_open.close()
</code></pre>
<p><a href="https://docs.python.org/3/c-api/list.html" rel="nofollow noreferrer">https://docs.python.org/3/c-api/list.html</a></p>
|
python|list|for-loop
| 0 |
1,904,271 | 64,764,961 |
Using an Embedding layer in the Keras functional API
|
<p>Doing basic things with the Keras Functional API seems to produce errors. For example, the following fails:</p>
<pre><code>from keras.layers import InputLayer, Embedding
input = InputLayer(name="input", input_shape=(1, ))
embedding = Embedding(10000, 64)(input)
</code></pre>
<p>This produces the error:</p>
<blockquote>
<p>AttributeError: 'str' object has no attribute 'base_dtype'</p>
</blockquote>
<p>I can then "cheat" by using the <code>input_length</code> argument but this then fails when I try to concatenate two such embeddings:</p>
<pre><code>from keras.layers import InputLayer, Embedding, Concatenate
embedding1 = Embedding(10000, 64, input_length=1)
embedding2 = Embedding(10000, 64, input_length=1)
concat = Concatenate()([embedding1 , embedding2])
</code></pre>
<p>This gives the error:</p>
<blockquote>
<p>TypeError: 'NoneType' object is not subscriptable</p>
</blockquote>
<p>Same error when I use "concatenate" (lower case) instead (some sources seem to say that this should be used instead if using the functional API).</p>
<p>What am I doing wrong?</p>
<p>I am on tensorflow version <code>2.3.1</code>, keras version <code>2.4.3</code>, python version <code>3.6.7</code></p>
|
<p>I strongly suggest to use <code>tf.keras</code> and not <code>keras</code>.</p>
<p>It doesn't work because <code>InputLayer</code> is an instance of <code>keras.Layer</code>, whereas <code>keras.layers.Input</code> is an instance of <code>Tensor</code>. The argument to <code>layer.__call__()</code> should be <code>Tensor</code> and not <code>keras.Layer</code>.</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
inputs = tf.keras.layers.Input((1,))
print(type(inputs)) # <class 'tensorflow.python.framework.ops.Tensor'>
input_layer = tf.keras.layers.InputLayer(input_shape=(1,))
print(type(input_layer)) # <class 'tensorflow.python.keras.engine.input_layer.InputLayer'>
</code></pre>
<p>You use <code>InputLayer</code> with <code>Sequential</code> API. When you use functional API you should use <code>tf.keras.layers.Input()</code> instead:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
inputs = tf.keras.layers.Input((1, ), name="input", )
embedding = tf.keras.layers.Embedding(10000, 64)(inputs)
</code></pre>
<p>Same with the second example:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
inputs = tf.keras.layers.Input((1, ), name="input", )
embedding1 = tf.keras.layers.Embedding(10000, 64)(inputs)
embedding2 = tf.keras.layers.Embedding(10000, 64)(inputs)
concat = tf.keras.layers.Concatenate()([embedding1, embedding2])
</code></pre>
|
python-3.x|tensorflow|keras
| 3 |
1,904,272 | 71,953,123 |
PyQt5: Pass a value into QWidget
|
<p>how do you pass a value into a QWidget in PyQt5?
Let's say everytime the user runs the GUI, the widget shows today's date for example.</p>
<p>Appreciate the help!!</p>
|
<pre><code>from PyQt5.QtWidgets import QApplication
from PyQt5 import QtWidgets
from datetime import date
app = QApplication(['Show Date'])
today = date.today()
window = QtWidgets.QLabel(f'This QLabel shows the actual date: {today}')
window.show()
app.exec()
</code></pre>
|
python|pyqt5
| 1 |
1,904,273 | 68,746,654 |
Merging two dataframes of different sizes, as per some condition
|
<p><strong>SOLVED</strong>
(see comment by Unbridledscum below)</p>
<p>I am currently attempting to join the information of two dataframes together.</p>
<p>My initial dataframe contains the product ID (SKU_id) as well as the product name as follows:</p>
<p>(Pardon the truncation of SKU_id)</p>
<pre><code>df
Out[127]:
SKU_id Product Name
0 7.336012e+09 OLD STYLE BEER
1 1.820001e+09 BUDWEISER BEER LONG
2 1.820000e+09 BUDWEISER BEER
3 3.410018e+09 MILLER GENUINE DRAFT
4 3.410018e+09 MILLER GENUINE DRAFT
5 8.066096e+09 CORONA EXTRA BEER NR
</code></pre>
<p>My other dataframe contains all other product information such as unit sales etc (As well as SKU_id).</p>
<pre><code>data.head()
Out[159]:
Store_id SKU_id WEEK Units_Sold QTY PRICE Promotion
20462 5 1820000016 166 1 1 3.79 NaN
20463 5 1820000016 167 3 1 3.79 NaN
20464 5 1820000016 168 6 1 3.79 NaN
20465 5 1820000016 169 2 1 3.79 NaN
20466 5 1820000016 170 1 1 3.79 NaN
</code></pre>
<p>I now want to join these two dataframes. More specifically I want to add the name of the particular SKU_id, which is present in the first dataframe (df) and not the second (data).</p>
<p>Both dataframes include the particular SKU_id's. I want to find a way to look at what the SKU_id is in the second dataframe (data) and then add the corresponding name from the first dataframe (df)</p>
<p>The output I am looking for is something like this:</p>
<pre><code> Store_id SKU_id WEEK Units_Sold QTY PRICE Promotion Product Name
20462 5 1820000016 166 1 1 3.79 NaN BUDWEISER BEER LONG
20463 5 1820000016 167 3 1 3.79 NaN BUDWEISER BEER LONG
20464 5 1820000016 168 6 1 3.79 NaN BUDWEISER BEER LONG
20465 5 1820000016 169 2 1 3.79 NaN BUDWEISER BEER LONG
20466 5 1820000016 170 1 1 3.79 NaN BUDWEISER BEER LONG
</code></pre>
<p>The problem is the two dataframes are of different sizes and I have no clue how to code a way to look at the SKU_id and add the corresponding name.
Any suggestions?
Thanks in advance</p>
|
<p>Here is an example where <code>df1</code> dataframe from your question and <code>df2</code> is the second that you have provided</p>
<pre><code>for i,val in enumerate(df2['SKU_id']):
df2.loc[i,"Product"]=df1.loc[df['SKU_id'] ==val, 'Product Name'].iloc[0]
df2.head()
</code></pre>
<p><code>Dataframe1</code> that I used as an example:</p>
<pre><code> SKU_id Product Name
0 7336012000 OLD STYLE BEER
1 1820000016 BUDWEISER BEER LONG
</code></pre>
<p><code>Dataframe2</code> that I used as an example:</p>
<pre><code> Store_id SKU_id
0 5 1820000016
1 5 1820000016
2 5 7336012000
</code></pre>
<p>This will give you something like:</p>
<pre><code> Store_id SKU_id Product
0 5 1820000016 BUDWEISER BEER LONG
1 5 1820000016 BUDWEISER BEER LONG
2 5 7336012000 OLD STYLE BEER
</code></pre>
|
python|pandas|dataframe
| 2 |
1,904,274 | 62,694,142 |
Pycharm debugger, does not go deep enough : Django project. [ fairly new to python/Django ]
|
<p>I'm currently debugging my Django project [kind of first project in Django/python]. The debug 'Step Over' button in Pycharm seems to be going properly. However at a particular point, it does not go deep enough.</p>
<p>Below is the code with the debug point (commented that particular line).
<em><strong>Please note, it's a properly working project, although I have trimmed down the codes (like skipping import statements, class definitions etc) here to make it as simple as possible to represent my question.</strong></em></p>
<p>File: <code>create_report_view.py</code> Here is where I have set the debug point.</p>
<pre><code>from project.project_core.forms import BrandModelForm
def post(self, request):
brand_form = BrandModelForm(request.POST, request.FILES)
if brand_form.is_valid(): # Debug point
file_name_errors, csv_name_errors, file_name_alphanumeric_error = self._validate_data(brand_form)
print(" And debug step goes on... ")
</code></pre>
<p>So, the debugger skips what happens <strong>inside</strong> the <code>.is_valid()</code> call, where my validation runs, and jumps to next line in the above code. How do I force it to debug the <code>.is_valid()</code> method as well ?</p>
<h2>Dependent code blocks.</h2>
<p>Below is the definition of my model, where i mention the <code>validators</code> in it.</p>
<p>File : <code>models.py</code></p>
<pre><code>from django.db.models import Model
from project.project_core.validators import ReportTypeValidator
class BrandModel(Model):
report_model = models.ForeignKey(ReportModel, models.CASCADE)
name = models.CharField(max_length=256, db_index=True)
review_file = models.FileField(upload_to='reviews/', validators=[ReportReviewValidator])
number_of_reviews = models.IntegerField(blank=True, null=True)
</code></pre>
<p>File : <code>forms.py</code></p>
<pre><code>from project.project_core.models import BrandModel
class BrandModelForm(forms.ModelForm):
class Meta:
model = BrandModel
exclude = ('report_model',)
labels = {
'name': 'Brand Name'
}
</code></pre>
<p>File :<code>validators.py</code></p>
<pre><code>from django.utils.deconstruct import deconstructible
ReportReviewValidator = UploadFileValidator(REVIEW_FILE_COLUMNS, CHARACTER_LIMIT_CONFIGS)
@deconstructible
class UploadFileValidator:
def __init__(self, review_file_columns: List[str], character_limit_configs: List[CharacterLimitConfig]):
self.csv_column_validator = CsvColumnsValidator(self.review_file_columns)
self.char_limit_validator = CharLimitValidator(self.char_limit_configs)
def __call__(self, field_file: FieldFile) -> None:
row_list = self.csv_column_validator(field_file)
</code></pre>
<p>I want the debugger to reach the above block of code, i.e the class <code>UploadFileValidator</code></p>
<p>What should I be doing for that ?</p>
|
<p>To achieve this, you need to put your breakpoint one line above and use "step into" to get into it:</p>
<pre><code>def post(self, request):
brand_form = BrandModelForm(request.POST, request.FILES) # Debug point
if brand_form.is_valid(): # Step Into this
file_name_errors, csv_name_errors, file_name_alphanumeric_error = self._validate_data(brand_form)
</code></pre>
<p>Note that this will get you to the is_valid() method, which is django's way of checking if your form is valid. It is not going to instantly take you to your validator. You will have to navigate through the whole process of django's form validation, and at some point you will end up in your own validator. If you want to specifically get into your validator's code, put a breakpoint inside instead.</p>
|
python|django|pycharm
| 0 |
1,904,275 | 65,926,148 |
From a list of dicts, get a number N of dicts with highest values
|
<p>I have a list of dicts that looks like this:</p>
<pre><code>dict = [{'skill': A, 'importance': '4'}, {'skill': B, 'importance': '6'}, {'skill': C, 'importance': '5'}]
</code></pre>
<p>I would like to get the <strong>two</strong> keys with the highest values (two most important skills)</p>
<p>The result should be:</p>
<pre><code>['B', C']
</code></pre>
<p>I was able to get the maximum skill (B) with:</p>
<pre><code>most_important = max(dict, key=lambda x:x['importance'])
</code></pre>
<p>but I don't know how to specify more than one maximum, or an <strong>N number</strong> of maximums</p>
|
<p>Find multiple maximums -> sort and take biggest N.</p>
<pre><code>sorted(dict, key=lambda x:x['importance'])[:2]
</code></pre>
|
python|list|dictionary|max
| 1 |
1,904,276 | 68,899,630 |
Get links from RSS feed
|
<p>I'm trying to append all links in the RSS feed of this <a href="https://news.google.com/rss/search?q=best-refrigerator-2021&hl=en-US&gl=US&ceid=US:en" rel="nofollow noreferrer">Google News page</a> using Beautiful Soup. I'm probably doing too much, but I can't seem to do it with this loop that iterates through a list of search terms for which I want to scrape Google News.</p>
<pre><code>for t in terms:
raw_url = "https://news.google.com/rss/search?q=" + t + "&hl=en-US&gl=US&ceid=US%3Aen"
url = raw_url.replace(" ","-")
req = Request(url)
html_page = urlopen(req)
soup = BeautifulSoup(html_page, "lxml")
links = []
links.append(re.findall("href=[\"\'](.*?)[\"\']", str(html_page), flags=0))
print(links)
</code></pre>
<p>The list comes up empty every time. My regex is probably off...</p>
<p>Any ideas?</p>
|
<p>Let BeautifulSoup help you by extracting all of the <code><item></code> tags, but because the link is not part of an embedded tag, you need to do the rest by hand. This does what you want, I think.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
terms = ['abercrombie']
for t in terms:
url = f"https://news.google.com/rss/search?q={t}&hl=en-US&gl=US&ceid=US%3Aen"
html_page = requests.get(url)
soup = BeautifulSoup(html_page.text, "lxml")
for item in soup.find_all("item"):
link= str(item)
i = link.find("<link/>")
j = link.find("<guid")
print( link[i+7:j] )
</code></pre>
|
python|regex
| 0 |
1,904,277 | 59,343,479 |
Running python scripts with variable parser arguments from Jupyter Notebook
|
<p>I'm Working on <a href="https://github.com/huggingface/transformers" rel="nofollow noreferrer">transformers</a> .</p>
<p>I have a python script there, that takes arguments as input via argparse.</p>
<p>Here is part of it:</p>
<pre><code> parser = argparse.ArgumentParser()
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS))
</code></pre>
<p>I want to be able to call the script iteratively with different arguments.
I can call the script with %run or !python <<em>bash command</em>>, but can I cannot pass variables to it be interpreted as arguments, because it treats the variables as the actual string value:</p>
<pre><code>%run examples/run_lm_finetuning.py --gradient_accumulation_steps=1 --output_dir='output_medium' --model_type='gpt2' \
--model_name_or_path=model_load --do_train --train_data_file='/root/sharedfolder/omri/data/pieces/backup/{}'.format(file)\
--overwrite_output_dir --per_gpu_train_batch_size=1 --per_gpu_eval_batch_size=1 --save_total_limit=5
</code></pre>
<p>Returns:</p>
<pre><code>OSError: Model name 'model_load' was not found in
model name list (gpt2, gpt2-medium, gpt2-large, gpt2-xl, distilgpt2).
We assumed 'model_load' was a path or url to a configuration file named
config.json or a directory containing such a file but couldn't find any
such file at this path or url.
</code></pre>
|
<p>It looks like <code>{}</code> expands variables. I stumbled on it trying do the Python <code>f''</code> formatting. I don't see it in <code>%run</code> docs; it must be part of the %magic syntax.</p>
<p>Anyways, with a simple <code>echo</code> script:</p>
<pre><code>In [29]: cat echo.py
import sys
print(sys.argv)
In [30]: foo = "a string"
In [31]: run echo.py {foo} bar
['echo.py', 'a', 'string', 'bar']
In [32]: run echo.py "{foo}" bar
['echo.py', 'a string', 'bar']
</code></pre>
<p>===</p>
<p>With another magic</p>
<pre><code>In [71]: astr="*.h5"
In [72]: ls {astr}
abc_copy.h5 string.h5 testdate.h5 test_str.h5...
</code></pre>
<p>===</p>
<p><code>$</code> also does this:</p>
<pre><code>In [79]: foo = "a string"
In [80]: run echo.py $foo bar
['echo.py', 'a', 'string', 'bar']
</code></pre>
<p><a href="https://stackoverflow.com/questions/14409167/how-to-pass-a-variable-to-magic-%c2%b4run%c2%b4-function-in-ipython">How to pass a variable to magic ´run´ function in IPython</a></p>
<blockquote>
<p>IPython.core.magic.no_var_expand(magic_func)
Mark a magic function as not needing variable expansion</p>
<p>By default, IPython interprets {a} or $a in the line passed to magics as variables that should be interpolated from the interactive namespace before passing the line to the magic function. This is not always desirable, e.g. when the magic executes Python code (%timeit, %time, etc.). Decorate magics with @no_var_expand to opt-out of variable expansion.</p>
</blockquote>
<p><a href="https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.magic.html" rel="nofollow noreferrer">https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.magic.html</a></p>
|
python|jupyter-notebook|argparse
| 2 |
1,904,278 | 63,077,867 |
CNN predictions
|
<p>I have built and trained a model with Keras using both a training and validation sets.
I would like to make predictions on unlabelled data, I have one folder containing 300 images of dogs, cats and horses. In the predictions I get the probabilities for each class.</p>
<p>How to I get a final output that tells / shows me how many of those 300 images belong to each class?</p>
<p>I upload the model</p>
<pre><code>new_model = tf.keras.models.load_model('model')
</code></pre>
<p>I then reformat the testing images</p>
<pre><code>test_batches = train_datagen.flow_from_directory(
'test_images',
target_size=(224, 224),
batch_size=10,
classes = None,
class_mode= None)
</code></pre>
<p>and then I finally make a prediction</p>
<pre><code>predictions = new_model.predict(test_batches, steps=30, verbose=0)
</code></pre>
|
<pre><code>import collections, numpy
collections.Counter(np.argmax(predictions, axis = 1))
</code></pre>
|
tensorflow|keras|conv-neural-network|prediction
| 1 |
1,904,279 | 59,509,507 |
formating issue with list of integers [TypeError: not all arguments converted during string formatting]
|
<p>I have to sort an odd number without changing the position of even number
while considering zero as even.</p>
<p>I tried to solve using lazy way but there was a weird issue about formatting issue
please check code below:</p>
<pre><code>def sort_array(source_array):
result = source_array[:]
odd = []
for i in result :
if i % 2 == 0 or i == 0:
odd.append('even_number')
else:
odd.append(i)
result[i] = 'odd'
# this is not a complete implementation we need to sort odd then replace it
# string 'even_number' kind off merge
return source_array
#checking the out put below
print(sort_array([5, 3, 2, 8, 1, 4]))
print(sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4])
</code></pre>
<p>I got the output below</p>
<blockquote>
<p>File "sort_even_number.py", line 48, in </p>
<pre><code>print(sort_array([5, 3, 2, 8, 1, 4])) File "sort_even_number.py", line 40, in sort_array
if i % 2 == 0 or i == 0:
</code></pre>
<p>TypeError: not all arguments converted during string formatting</p>
</blockquote>
|
<p>In python we usually use <code>i</code> variable for index. Here you iterate over list and those are list elements, not indexes. <code>for i in result :</code></p>
<p>So each list element is an integer but not an index. It happens that it's a valid index as well, as indexes are integers.</p>
<p>At some point the variables are</p>
<pre><code>odd = [5, 3, 'even_number']
result = [5, 3, 2, 'odd', 1, 'odd']
</code></pre>
<p>There are a few problems with your script. The source of error is this. <code>result[i] = 'odd'
</code>
No idea if you do that on purpose but it would be easier if you didn't edit an iterable while you iterate over it. And you can't do modulo of a string (<code>'odd'</code>).</p>
<p>I think you will crack the rest of it yourself.</p>
|
python|python-3.x
| 0 |
1,904,280 | 49,138,297 |
Aligning Text boxes Django
|
<p>This is my registration form:</p>
<p><img src="https://i.stack.imgur.com/rLYms.png" alt="Registration Form "></p>
<p>I am trying to align all of the text boxes. This is my form code;</p>
<p>Forms.py </p>
<pre><code>class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True, label = "Email:")
username = forms.CharField(required=True, label = "Username:")
first_name = forms.CharField(required=True, label = "First Name:")
last_name = forms.CharField(required=True, label = "Last Name:")
password1 = forms.CharField(widget=forms.PasswordInput, required=True,
label = "Password:")
password2 = forms.CharField(widget=forms.PasswordInput, required=True,
label = "Confirm Password:")
class Meta:
model = User
fields = {
'password2',
'username',
'first_name',
'last_name',
'email',
'password1'
}
</code></pre>
<p>Any help is greatly appreciated.</p>
|
<p>You'll need to understand that the output that Django gave you here is html, and you'll have to style it with css.</p>
<p>So you'll need to understand how you can style your forms with html and css, it is not really something you do in Django. (Although you can give custom attributes to HTML elements in Django, and then use those attributes to reference those HTML elements in your css. The tutorial below talks about this under the heading: 'Using Custom HTML Attributes')</p>
<p>Below I'll share a link to a tutorial that has helped me understand how to customize how forms render. This should explain a lot of what I am trying to explain.</p>
<p><a href="https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html" rel="nofollow noreferrer">https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html</a></p>
|
python|django
| 4 |
1,904,281 | 60,207,821 |
Python/Pandas/Datetime: transform entire lists in a column to datetime
|
<p>I have a Pandas Dataframe with following structure:</p>
<pre><code> title zeiten
0 Anker der Liebe ['2020-02-17T19:15:00+01:00']
1 DarkroomTΓΆdliche Tropfen ['2020-02-17T21:45:00+01:00']
2 Das geheime Leben der BΓ€ume,['2020-02-13T16:45:00+01:00', '2020-02-14T16:45:00+01:00', '2020-02-15T16:45:00+01:00', '2020-02-16T16:45:00+01:00', '2020-02-17T16:45:00+01:00', '2020-02-18T16:45:00+01:00', '2020-02-19T16:45:00+01:00']
...
</code></pre>
<p>i want to transform the column 'zeiten' to datetime so i tride: </p>
<pre><code>df['zeiten'] = df['zeiten'].apply(lambda x: pd.to_datetime(x)[0])
</code></pre>
<p>This works for row 0 and 1, but not for row 2, since only the first date of the list is transformed, so the output looks like this:</p>
<pre><code> title zeiten
0 Anker der Liebe 2020-02-17 19:15:00+01:00
1 DarkroomTΓΆdliche Tropfen 2020-02-17 21:45:00+01:00
2 Das geheime Leben der BΓ€ume 2020-02-13 16:45:00+01:00
</code></pre>
<p>is there a way to transform entire lists in a column to Datetime?</p>
|
<p>Convert all values, not only first, so removed <code>[0]</code> and also if necessary converted DatetimeIndex for each value to <code>list</code>:</p>
<pre><code>df['zeiten'] = df['zeiten'].apply(lambda x: pd.to_datetime(x))
print (df)
title \
0 Anker der Liebe
1 DarkroomTodliche Tropfen
2 Das geheime Leben der Baume,
zeiten
0 DatetimeIndex(['2020-02-17 19:15:00+01:00'], d...
1 DatetimeIndex(['2020-02-17 21:45:00+01:00'], d...
2 DatetimeIndex(['2020-02-13 16:45:00+01:00', '2...
</code></pre>
<hr>
<pre><code>df['zeiten'] = df['zeiten'].apply(lambda x: pd.to_datetime(x).tolist())
print (df)
title \
0 Anker der Liebe
1 DarkroomTodliche Tropfen
2 Das geheime Leben der Baume,
zeiten
0 [2020-02-17 19:15:00+01:00]
1 [2020-02-17 21:45:00+01:00]
2 [2020-02-13 16:45:00+01:00, 2020-02-14 16:45:0...
</code></pre>
|
python|pandas|list|datetime|lambda
| 2 |
1,904,282 | 67,865,937 |
How to code and run lines while training a model on VS Code remote server connection?
|
<p>while I'm training a model and the interpreter busy, is there a way that I can run another file on a new window or something.</p>
<p><a href="https://i.stack.imgur.com/0P55f.png" rel="nofollow noreferrer">I'm training a model here and the interpreter is busy</a></p>
<p>I want to code and test things on the commandline/python interpreter while the server is busy training my model.</p>
<p>Thanks,
Chung</p>
<p>Additional img:
<a href="https://i.stack.imgur.com/XZdlc.png" rel="nofollow noreferrer">Trying to run 'import time' from the editor as training the model and the command is queued to the already-busy terminal instead of the split one</a></p>
|
<p>As you take the <code>Shift+Enter</code> shortcut to execute the <code>Run Selection/Line in Terminal</code> command.</p>
<p>The VSCode will create a Terminal named <code>Python</code> to execute all the commands from <code>Run Selection/Line in Terminal</code> command.</p>
<p>If you want to avoid it. You need to create a new terminal and execute the python file manually instead of the shortcut command.</p>
<p><a href="https://i.stack.imgur.com/vsAzb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vsAzb.png" alt="enter image description here" /></a></p>
|
python|visual-studio-code|deep-learning|remote-server|vscode-remote
| 1 |
1,904,283 | 72,215,624 |
Getting indices using conditional list comprehension
|
<p>I have the following np.array:</p>
<pre><code>my_array=np.array([False, False, False, True, True, True, False, True, False, False, False, False, True])
</code></pre>
<p>How can I make a list using list comprehension of the indices corresponding to the True elements. In this case the output I'm looking for would be [3,4,5,7,12]</p>
<p>I've tried the following:</p>
<pre><code>cols = [index if feature_condition==True for index, feature_condition in enumerate(my_array)]
</code></pre>
<p>But is not working</p>
|
<p>The order of if is not correct, should be in last -</p>
<pre><code>$more numpy_1.py
import numpy as np
my_array=np.array([False, False, False, True, True, True, False, True, False, False, False, False, True])
print (my_array)
cols = [index for index, feature_condition in enumerate(my_array) if feature_condition]
print (cols)
$python numpy_1.py
[False False False True True True False True False False False False
True]
[3, 4, 5, 7, 12]
</code></pre>
|
python-3.x|list|list-comprehension
| 1 |
1,904,284 | 50,463,731 |
Python has stopped working(APPCRASH) Anaconda
|
<p>When I try to build Linear Regression model with training data in Jupyter notebook, python has stopped working, with error as shown below. I am using Anaconda 3.5 on windows7, Python 3.6 version.</p>
<p>Problem signature:<br>
Problem Event Name: APPCRASH<br>
Application Name: python.exe<br>
Application Version: 3.6.4150.1013<br>
Application Timestamp: 5a5e439a<br>
Fault Module Name: mkl_core.dll<br>
Fault Module Version: 2018.0.1.1<br>
Fault Module Timestamp: 59d8a332<br><br>
Exception Code: c000001d<br>
Exception Offset: 0000000001a009a3<br>
OS Version: 6.1.7600.2.0.0.256.48<br>
Locale ID: 1033<br>
Additional Information 1: 7071<br>
Additional Information 2: 70718f336ba4ddabacde4b6b7fbe73e3<br>
Additional Information 3: de32<br>
Additional Information 4: de328b4df988a86fd2d750fb0942dbd1<br></p>
<p>I am not able to get any help from google when I search with this error, even I tried<br>
1 Uninstalled and again installed<br>
2. Ran below commands but no use<br>
conda update conda<br>
conda update ipython ipython-notebook ipython-qtconsole<br></p>
<p>I suspect this error related to Windows, but not sure how to fix it. </p>
<p>Thanks,<br>
Sagar.</p>
|
<p>Updated all the libraries to latest version in Anaconda and try.</p>
<p>I was facing a similar situation when I was running the code for Convolutional Neural Network in Spyder under Anaconda environment (Windows 7) I was getting following error</p>
<blockquote>
<p>Problem Event Name: APPCRASH<br>
Application Name: pythonw.exe<br>
Fault Module Name: StackHash<br>
Exception Code: c0000005<br>
OS Version: 6.1.7601.2.1.0.256.1 </p>
</blockquote>
<p>I updated all the libraries to latest version in Anaconda and the problem is resolved.</p>
|
python|anaconda
| 0 |
1,904,285 | 50,289,673 |
python sms store using class
|
<p>Im trying to get a basic sms program running within a python file.
The idea is that the program ask you a question of do you want to send or read an sms. each sms would have a from_number,message_body and read/unread tag. SO the idea is you start by seding an sms then you enter your source number and text body. it stores it in a list. then you can recall that massage later and when you read it the unread flag needs to change to read. </p>
<p>the parts i think is the biggest problem is understanding how to specify the class instance and using the functions inside the class when taking user input and passing it on to the program. </p>
<p>the SMS1 code is an attempt to generate a manual instance with its attributes. </p>
<p>maybe i have this whole structure wrong.
any assistance would be much appreciated.</p>
<pre><code>#An SMS Simulation
SMSStore = []
#start of the class
class SMSMessage:
def __init__(self,messageText,fromNumber):
global SMSStore
self.messageText = messageText
self.fromNumber = fromNumber
#self.originnumber = originnumber
#self.hasBeenRead = False
def MarkAsRead(self):
self.hasBeenRead = bool(True)
def add_sms(self,smses):
for number in range(smses):
soure_number = int(input("please enter source number..."))
message_body = str(input("please enter message body..."))
new_message = (soure_number,message_body)
SMSStore.append(new_message)
return print(SMSStore)
def get_count(self):
return print(SMSMessage.count())
def get_message(self):
return print(len(SMSStore))
def get_unread_messages(self): #still need to figure this out with a read or unread tag
pass
def remove_sms(self):
sms_to_del = int(input("which sms number do you want to delete: "))
del SMSStore[sms_to_del]
sms1 = SMSMessage("hello","123")
print(sms1.fromNumber)
print(sms1)
userchoice = None
while userchoice != "quit":
userchoice = input("what would you like to do - read/send/quit?")
if userchoice == "read":
SMSStore.get_count()
#place your logic here
elif userchoice == "send":
smses = int(input("number of smses to be added"))
SMSMessage.add_sms(smses)
#place your logic here
print(SMSStore)
elif userchoice == "quit":
print ("goodbye")
else:
print ("oops - incorrect input")
</code></pre>
|
<p>Here is my example, check it:</p>
<pre><code>class Messenger:
sms_store = [{'title': 'test', 'text': 'Some text here', 'readed': False}]
def __init__(self):
self.greeting()
self.prompt()
def greeting(self, *arg, **kw):
print('Hello there!')
print('In your inbox {} messeges, ({} is new)'.format(
len(self.sms_store), len(list(filter(bool, [not x.get('readed') for x in self.sms_store])))))
def prompt(self):
while True:
command, *args = input("\nWhat would you like to do?\n> ").split()
if command == 'quit':
break
elif hasattr(self, command):
getattr(self, command)(*args)
else:
print('>>> Wrong command! <<<')
def list(self, *arg, **kw):
print('Messeges:')
for n, sms in enumerate(self.sms_store):
print('Num:', n, 'Readed:', sms.get('readed'), 'Title:', sms.get('title'))
def get(self, sms_num, *arg, **kw):
if not sms_num or int(sms_num) >= len(self.sms_store):
print('>>> Wrong msg Number! <<<')
else:
sms = self.sms_store[int(sms_num)]
print(sms.get('title'))
print(sms.get('text'))
self.mark_readed(int(sms_num))
def mark_readed(self, sms_num, *arg, **kw):
self.sms_store[sms_num]['readed'] = True
def add_sms(self, title, *arg, **kw):
self.sms_store.append({'title': title, 'text': ' '.join(arg), 'readed': False})
print('Msg added!')
def remove_sms(self, sms_num, *arg, **kw):
if not sms_num or int(sms_num) >= len(self.sms_store):
print('>>> Wrong msg Number! <<<')
else:
self.sms_store.pop(int(sms_num))
if __name__ == "__main__":
m = Messenger()
</code></pre>
<p>Output:</p>
<pre><code>~ > $ python3 test.py
Hello there!
In your inbox 1 messeges, (1 is new)
What would you like to do?
> list
Messeges:
Num: 0 Readed: False Title: test
What would you like to do?
> add_sms New_sms Some text is here!
Msg added!
What would you like to do?
> list
Messeges:
Num: 0 Readed: False Title: test
Num: 1 Readed: False Title: New_sms
What would you like to do?
> get 1
New_sms
Some text is here!
What would you like to do?
> list
Messeges:
Num: 0 Readed: False Title: test
Num: 1 Readed: True Title: New_sms
What would you like to do?
> remove_sms 0
What would you like to do?
> list
Messeges:
Num: 0 Readed: True Title: New_sms
What would you like to do?
> close
>>> Wrong command! <<<
What would you like to do?
> quit
~ > $
</code></pre>
|
python-3.x|function|class
| 1 |
1,904,286 | 34,927,805 |
What to do next?
|
<p>This application will read roster data in JSON format, parse the file, and then produce an SQLite database that contains a User, Course, and Member table and populate the tables from the data file.</p>
<p>This code is incomplete as I need to modify the program to store the role column in the Member table to complete the problem. And I cannot understand how to do it.</p>
<pre><code>import json
import sqlite3
conn = sqlite3.connect('rosterdb.sqlite')
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS User;
DROP TABLE IF EXISTS Member;
DROP TABLE IF EXISTS Course;
CREATE TABLE User (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Course (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
title TEXT UNIQUE
);
CREATE TABLE Member (
user_id INTEGER,
course_id INTEGER,
role INTEGER,
PRIMARY KEY (user_id, course_id)
)
''')
fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'roster_data.json'
# [
# [ "Charley", "si110", 1 ],
# [ "Mea", "si110", 0 ],
str_data = open(fname).read()
json_data = json.loads(str_data)
for entry in json_data:
name = entry[0];
title = entry[1];
print name, title
cur.execute('''INSERT OR IGNORE INTO User (name)
VALUES ( ? )''', ( name, ) )
cur.execute('SELECT id FROM User WHERE name = ? ', (name, ))
user_id = cur.fetchone()[0]
cur.execute('''INSERT OR IGNORE INTO Course (title)
VALUES ( ? )''', ( title, ) )
cur.execute('SELECT id FROM Course WHERE title = ? ', (title, ))
course_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id) VALUES ( ?, ? )''',
( user_id, course_id ) )
conn.commit()
</code></pre>
<p>Once the necessary changes are made to the program and it has been run successfully reading the given JSON data, run the following SQL command:</p>
<pre><code>SELECT hex(User.name || Course.title || Member.role ) AS X FROM
User JOIN Member JOIN Course
ON User.id = Member.user_id AND Member.course_id = Course.id
ORDER BY X
</code></pre>
<p>Find the first row in the resulting record set and enter the long string that looks like 53656C696E613333.</p>
|
<p>On one hand, there are two changes you need to make in your code:</p>
<pre><code>name = entry[0];
title = entry[1];
role = entry[2];
print name, title, role
</code></pre>
<p>and</p>
<pre><code>cur.execute('''INSERT OR REPLACE INTO Member
(user_id, course_id, role) VALUES ( ?, ?, ? )''',
( user_id, course_id, role ) )
</code></pre>
<p>but on the other hand, if you're having problems with your Coursera homework, you should really be posting to the class discussion forums about it (after reading what people have already posted about it there, in case that answers your questions) rather than to Stack Overflow. Considering that your question is about an assignment that was due some time ago rather than a current one, I don't feel so bad about talking about it here, but yeah, in the future use the discussion forums instead, and look at what I posted here to understand what is going on.</p>
|
python|json|sqlite
| 0 |
1,904,287 | 35,325,439 |
Python Convert Fraction Inside String to Integer
|
<p>How can I convert an input entered as a fraction (eg, "4/2") into an integer in python 3.5? I have tried using both of the following codes:</p>
<pre><code>b = int(input("Please enter a value for b of the quadratic equation: "))
b = int(float(input("Please enter a value for b of the quadratic equation: ")))
</code></pre>
|
<p><strong>Use <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow noreferrer"><code>fractions</code></a>.</strong></p>
<pre><code>>>> from fractions import Fraction
>>> int(Fraction('4/2'))
2
</code></pre>
<p>Whatever you do, don't use <code>eval</code>.</p>
<p>Note that <code>int()</code> always rounds towards zero. Depending on the behaviour you want, you might want to check out <code>round()</code>, <code>math.floor()</code> or <code>math.ceil()</code>.</p>
|
python|python-3.x
| 20 |
1,904,288 | 35,256,903 |
Python Flask get item from HTML select form
|
<p>Im having trouble getting anything from the shown HTML form</p>
<p>I always get <code>"ValueError: View function did not return a response"</code></p>
<p>Can somebody help me out here please? I have tried every variation of request.get that I can find on the web. Also if I specify my form should use post it uses get anyway - anybody know why this is? </p>
<p>Im new to flask so forgive my ignorance! </p>
<p>Thanks in advance.</p>
<p>The python file (routes.py)</p>
<pre><code>from flask import Flask, render_template, request
import os
app = Flask(__name__)
musicpath = os.listdir(r"C:\Users\Oscar\Music\iTunes\iTunes Media\Music")
lsize = str(len(musicpath))
looper = len(musicpath)
@app.route('/')
def home():
return render_template('home.html', lsize=20, looper=looper, musicpath=musicpath)
@app.route('/pop', methods=['POST', 'GET'])
def pop():
if request.method == "GET":
text = request.args.get('som')
return text
#Have tried every variation of request.get
@app.route('/about')
def about():
name = "Hello!"
return render_template('about.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>The html file (home.html)</p>
<pre><code>{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>A Music app!<h2>
</div>
<div>
{% if lsize %}
<form action="/pop">
<select id="som" size="20">
{% for i in range(looper):%}
<option value="{{i}}">{{ musicpath[i] }}</option>
{% endfor %}
</select>
</form>
{% endif %}
</div>
<a href="{{ url_for('pop') }}">Select,</a>
{% endblock %}
</code></pre>
|
<p>The Problem is that your HTML form does not have a name.
<code>request.args.get("som")</code> needs an HTML form input with the name <code>"som"</code></p>
<pre><code><select name="som" id="som" size="20">
</code></pre>
<p>Just change that line and add a name. The form is not interested in the <code>id</code> attribute.</p>
|
python|html|flask
| 2 |
1,904,289 | 44,990,791 |
"Python has stopped Working" when training a convolution neural net in tensorflow gpu
|
<p>This is a tensorflow code I wrote to test convolution neural net with only 1 convolution and pooling layer with only 1 fully connected layer of 512 neurons.</p>
<p>My dataset is of only 2 images: <a href="https://imgur.com/et1Sn1k" rel="nofollow noreferrer">http://imgur.com/et1Sn1k</a> and <a href="https://imgur.com/ZWxOGgO" rel="nofollow noreferrer">http://imgur.com/ZWxOGgO</a></p>
<p>When I train my network windows gives an pop up saying "Python has stoped" (ss: <a href="https://imgur.com/tc5jWlA" rel="nofollow noreferrer">http://imgur.com/tc5jWlA</a> )</p>
<p>This is my code:</p>
<pre><code>from scipy.misc import imread
import matplotlib.pyplot as plt
import numpy as np
import PIL.Image as Image
base_image = imread("base_image.jpg")
subject_image = imread("subject_image.jpg")
base_image = np.resize(base_image, [1024, 768, 3])
subject_image = np.resize(subject_image, [1024, 768, 3])
images = []
images.append(base_image)
images.append(subject_image)
# hyper parameters
epochs = 10
batch_size = 2
learning_rate = 0.01
n_classes = 2
import tensorflow as tf
# Model
x = tf.placeholder('float', [2, 1024, 768, 3])
y = tf.placeholder('float', [2])
weights = {
"conv": tf.random_normal([10, 10, 3, 32]),
"fc": tf.random_normal([-1, 512]), #7*7*64
"out": tf.Variable(tf.random_normal([512, n_classes]))
}
conv = tf.nn.conv2d(x, filter=weights['conv'], strides=[1, 1, 1, 1], padding="SAME")
conv = tf.nn.max_pool(value=conv, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")
fc = tf.reshape(conv, shape=[2,-1])
fc = tf.nn.relu(tf.matmul(fc, weights['fc']))
output = tf.matmul(fc, weights['out'])
loss = tf.reduce_mean((output - y)**2)
train = tf.train.AdamOptimizer(learning_rate).minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(epochs):
sess.run(train, feed_dict={x: images, y: [0, 1]})
print(i)
</code></pre>
<p>Output:</p>
<pre><code>2017-07-09 02:29:43.688699: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689131: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689504: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.689998: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690380: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.690646: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691117: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:43.691436: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
2017-07-09 02:29:44.197766: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:940] Found device 0 with properties:
name: GeForce GTX 960M
major: 5 minor: 0 memoryClockRate (GHz) 1.176
pciBusID 0000:01:00.0
Total memory: 4.00GiB
Free memory: 3.35GiB
2017-07-09 02:29:44.198207: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:961] DMA: 0
2017-07-09 02:29:44.198391: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:971] 0: Y
2017-07-09 02:29:44.198643: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 960M, pci bus id: 0000:01:00.0)
2017-07-09 02:29:44.881448: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
2017-07-09 02:29:44.881875: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
[[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:44.882604: W c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\framework\op_kernel.cc:1158] Invalid argument: Dimension -1 must be >= 0
[[Node: random_normal_1/RandomStandardNormal = RandomStandardNormal[T=DT_INT32, dtype=DT_FLOAT, seed=0, seed2=0, _device="/job:localhost/replica:0/task:0/gpu:0"](random_normal_1/shape)]]
2017-07-09 02:29:45.362917: E c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\stream_executor\cuda\cuda_dnn.cc:352] Loaded runtime CuDNN library: 6021 (compatibility version 6000) but source was compiled with 5105 (compatibility version 5100). If using a binary install, upgrade your CuDNN library to match. If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration.
2017-07-09 02:29:45.364154: F c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\kernels\conv_ops.cc:671] Check failed: stream->parent()->GetConvolveAlgorithms(&algorithms)
[Finished in 22.7s with exit code 3221226505]
[shell_cmd: python -u "E:\workspace_py\convolotion_neural_net.py"]
[dir: E:\workspace_py]
[path: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\libnvvp;E:\Program Files\Python 3.5\Scripts\;E:\Program Files\Python 3.5\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Python27\Scripts;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;E:\Program Files\MATLAB\runtime\win64;E:\Program Files\MATLAB\bin;E:\Program Files\MATLAB\polyspace\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\guita\AppData\Local\Microsoft\WindowsApps;E:\Program Files\Python27\Scipts;e:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\guita\AppData\Local\atom\bin]
</code></pre>
<p>My pc specs (Lenovo Y50):
Nvidia GTX 960m 4 GB memory,
Intel I7 4th gen,
8 GB RAM</p>
<p>Python 3.5 + Tensorflow with GPU</p>
|
<p>So I managed to fix it on my own. This happened because my cuDNN version was 6.0 but tensorflow works best 5.1. Also there's some minute errors in the code but that irrelevant :p </p>
|
python|tensorflow
| 1 |
1,904,290 | 55,312,689 |
Is there a regular expression for finding all question sentences from a webpage?
|
<p>I am trying to extract some questions from a web site using BeautifulSoup, and want to use regular expression to get these questions from the web. Is my regular expression incorrect? And how can I combine soup.find_all with re.compile?</p>
<p>I have tried the following:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
from urllib.request import urlopen
import urllib
import re
url = "https://www.sanfoundry.com/python-questions-answers-variable-names/"
headers = {'User-Agent':'Mozilla/5.0'}
page = requests.get(url)
soup = BeautifulSoup(page.text, "lxml")
a = soup.find_all("p")
for m in a:
print(m.get_text())
</code></pre>
<p>Now I have some text containing the questions like "1. Is Python case sensitive when dealing with identifiers?". I want to use r"[^.!?]+\?" to filter out the unwanted text, but I have the following error:</p>
<pre><code>a = soup.find_all("p" : re.compile(r'[^.!?]+\?'))
a = soup.find_all("p" : re.compile(r'[^.!?]+\?'))
^
SyntaxError: invalid syntax
</code></pre>
<p>I checked my regular expression on <a href="https://regex101.com" rel="nofollow noreferrer">https://regex101.com</a>, it seems right. Is there a way to combine the regular expression and soup.find_all together?</p>
|
<p>Not a big regex fan, so tried this:</p>
<pre><code>for q in a:
for i in q:
if '?' in i:
print(i)
</code></pre>
<p>Output:</p>
<pre><code>1. Is Python case sensitive when dealing with identifiers?
2. What is the maximum possible length of an identifier?
3. Which of the following is invalid?
4. Which of the following is an invalid variable?
5. Why are local variable names beginning with an underscore discouraged?
6. Which of the following is not a keyword?
8. Which of the following is true for variable names in Python?
9. Which of the following is an invalid statement?
10. Which of the following cannot be a variable?
</code></pre>
|
regex|python-3.x|beautifulsoup
| 2 |
1,904,291 | 44,482,236 |
Beautiful Soup: parsing table row data returns an error
|
<p>I've tried a heap of different combinations of code to try and get the table data out of this table. Simply using <code>soup.table</code> doesn't return this specific table from the page, and I can't figure out why.</p>
<p>I've managed to find it by class by using <code>class_:'table assessment-item'</code> but when I try and parse individual rows or data, it throws an error.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.qut.edu.au/study/unit?unitCode=IFB104")
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find_all(class_='table assessment-item')
table_data = table.find_all('td')
</code></pre>
<p>The error:</p>
<pre><code>Traceback (most recent call last):
File "/Users/study/Desktop/QUT Final/demo.py", line 7, in <module>
table_data = table.find_all('td')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/bs4/element.py", line 1807, in __getattr__
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
</code></pre>
|
<p>There are three tables returned having class as <code>'table assessment-item'</code>.</p>
<p>You just need to iterate over them:</p>
<pre><code>table = soup.find_all(class_='table assessment-item')
table_data = [tbl.find_all('td') for tbl in table]
print table_data
</code></pre>
|
python|html|web-scraping|beautifulsoup
| 4 |
1,904,292 | 49,637,320 |
pandas groupby with a conditional
|
<p>I have this:</p>
<pre><code>IDS CR_EARNED TYPE TOT_ALL_TYPES
001 3 A 7
001 3 A 7
001 1 B 7
002 3 A 6
002 3 A 6
003 2 C 8
003 4 C 8
003 2 A 8
</code></pre>
<p>TOT_ALL_TYPES is a column I created to sum all TYPE of CR_EARNED for each ID by doing the following:</p>
<pre><code>df['TOT_ALL_TYPES'] = df['CR_EARNED'].groupby(df['IDS']).transform('sum')
</code></pre>
<p>Next, I want to create an new column that will sum CR_EARNED by ID where TYPE = A or B. The result would look like this:</p>
<pre><code>IDS CR_EARNED TYPE TOT_ALL_TYPES TOT_AB
001 3 A 7 7
001 3 A 7 7
001 1 B 7 7
002 3 C 6 3
002 3 A 6 3
003 2 C 8 2
003 4 C 8 2
003 2 A 8 2
</code></pre>
<p>How would I go about doing this?</p>
|
<p>IIUC </p>
<p>You can using <code>where</code></p>
<pre><code>df['CR_EARNED'].where(df.TYPE.isin(['A','B']),0).groupby(df['IDS']).transform('sum')
Out[887]:
0 7
1 7
2 7
3 6
4 6
5 2
6 2
7 2
Name: CR_EARNED, dtype: int64
</code></pre>
<p>More info</p>
<pre><code>df['CR_EARNED'].where(df.TYPE.isin(['A','B']),0)
Out[890]:
0 3
1 3
2 1
3 3
4 3
5 0
6 0
7 2
Name: CR_EARNED, dtype: int64
</code></pre>
|
python|pandas|pandas-groupby
| 3 |
1,904,293 | 54,896,407 |
BeautifulSoup4 Get "li a" with no text inside li
|
<p>I need help getting some specific anchors from a website. The website has this structure</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>
This has a link
<a href="#">1st link</a>
</li>
<li>
<a href="#">2nd link</a>
</li>
<li>
This also has a link
<a href="#">1st link</a>
</li></code></pre>
</div>
</div>
</p>
<p>I want to get only the anchors that have no text inside de <code>li</code>.
What is the easiest way to achieve this with BeautifulSoup?</p>
|
<p>You can analyze the elements of <code>soup.contents</code> to determine if only <code>soup</code> objects exist:</p>
<pre><code>from bs4 import BeautifulSoup as soup
d = soup(s, 'html.parser')
results = [i for i in d.find_all('li') if all(not isinstance(c, str) or c == '\n' for c in i.contents)]
</code></pre>
<p>Output:</p>
<pre><code>[<li>
<a href="#">2nd link</a>
</li>]
</code></pre>
|
python|html|beautifulsoup
| 0 |
1,904,294 | 54,971,340 |
Getting the URLs of image posts on Reddit
|
<p>I'm working on a reddit bot that's purpose is to find reposts when it detects a comment containing "!repostfinder". The bot is able to detect the string, but I don't know how to get the image that was commented on.</p>
<p>Here's the code I have so far:</p>
<pre><code>#subreddit to use
subreddit = reddit.subreddit('test')
#summoning the bot
keyphrase = '!repostfinder'
#find comments with keyphrase
for comment in subreddit.stream.comments():
if keyphrase in comment.body:
print('Found keyphrase')
comment.reply('Keyphrase detected')
print('Replied to comment')
</code></pre>
|
<p><strong>You should read the relevant docs of the <code>praw</code> library that you are using.</strong></p>
<p>Here are the docs of <code>praw.models.reddit.comment.Comment</code>: <a href="https://praw.readthedocs.io/en/latest/code_overview/models/comment.html?highlight=comment" rel="nofollow noreferrer">https://praw.readthedocs.io/en/latest/code_overview/models/comment.html?highlight=comment</a></p>
<p>You can get the comment's submission by using <code>comment.submission</code>. Then it is up to you what to do with the data.
Here are the docs of <code>praw.models.reddit.submission.Submission</code>: <a href="https://praw.readthedocs.io/en/latest/code_overview/models/submission.html?highlight=submission" rel="nofollow noreferrer">https://praw.readthedocs.io/en/latest/code_overview/models/submission.html?highlight=submission</a></p>
<p>Example:</p>
<pre><code># Fetch some comments
comments = []
for comment in subreddit.stream.comments():
# Stop after fetching some comments
if (len(comments) < 10):
comments.append(comment)
else:
break
# Select specific comment
comment = comments[0]
# Get the comment's submission
submission = comment.submission
</code></pre>
|
python|reddit|praw
| 1 |
1,904,295 | 40,051,163 |
Webpy: Variables not showing properly in html
|
<p>I'm getting an error while using webpy, my string is "No client", but when opening html in browser i get only 'No', the white space and rest of string is lost! What I'm doing wrong?</p>
<p>This is what is in the .html part:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder= $:name2 value= $:name2 name="name3" id="nome3" readonly></code></pre>
</div>
</div>
</p>
<p>I tried $:name2 and $name2, maybe because of some string format.</p>
|
<p>I think you just need to put quotes around the values. Your example should become:</p>
<pre><code><input type="text" placeholder="$:nome2" value="$:nome2" name="nome3" id="nome3" readonly>
</code></pre>
|
python|html|web.py
| 0 |
1,904,296 | 36,552,101 |
prediction in tensor flow for multiple labels
|
<p>How can I get a prediction vector in the tensorflow graph apart from
<code>predict = tf.argmax(y)</code> ? (since argmax only works for softmax classifiers)</p>
<p>I have a multilabel classification problem so therefore I need something like:</p>
<pre><code>predictions = [1. if prob > 0.5 else 0. for prob in y]
</code></pre>
|
<p>Hope this helps :</p>
<pre><code>import tensorflow as tf
import numpy as np
sess = tf.InteractiveSession()
prob = tf.constant(np.random.rand(10))
predictions = tf.select(prob > 0.5, tf.ones_like(prob), tf.zeros_like(prob))
print(predictions.eval())
</code></pre>
|
tensorflow
| 4 |
1,904,297 | 34,263,111 |
Where is pygame folder on mac if installed python and pygame via homebrew?
|
<p>I used this tutorial <a href="https://www.youtube.com/watch?v=L0Cl4Crg7FE" rel="nofollow noreferrer">here.</a> for pygame istallation on mac.
The tutorial is good and I installed it all using hombrew - git, mercurial, sgl dependencies and python, pygame.</p>
<p>The instructions were like this.</p>
<pre><code>brew install git
brew install sdl sdl_image sdl_mixer sdl_ttf portmidi
pip3 install hg+http://bitbucket.org/pygame/pygame
python3
</code></pre>
<p>At the prompt, type:</p>
<pre><code>import pygame
</code></pre>
<p>In terminal, i do <code>import pygame, pygame.init()</code> and it works, but how do I launch it through IDE?
<strong>The terminal just sits there, no any other program/IDE launches after init command.</strong></p>
<p>Where did homebrew install all those folders? I can't find them in my applications, documents. </p>
<p>I need to know where pygame files are placed, so that I can somehow connect it to other custom IDE - PyCharm etc.</p>
<p>What should serve as IDE in my case? probably xCode, because the tutorial mentions it?</p>
|
<p>You can run from pygame import jgsjfgjsdnfjg to find out, it will be included in the error message.</p>
|
python|macos|pygame|homebrew
| 0 |
1,904,298 | 32,061,467 |
Python - no clear XML - tags and values mixed
|
<p>In the following section, while parsing I am getting correct printing for title, price but not for book id. Thank you all in advance.</p>
<p>The following tries to read book id, title, price an print them
example structure of the booksExample.xml file</p>
<pre><code><book id="bk101">
<author>F-NAME, L-NAME</author>
<title>BOOK'S TITLE</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>ANALYTICAL INFORMATION ABOUT IT.</description>
</book>
</code></pre>
<p>Code:</p>
<pre><code>from xml.etree.ElementTree import parse
doc = parse('booksExample.xml')
for book in doc.findall('book'):
id = book.findtext('id')
title = book.findtext('title')
price = book.findtext('price')
print id, title, price
</code></pre>
|
<p><code>id</code> is an attribute of the book element so you have to use <code>book.get('id')</code>, not <code>book.findtext('id')</code></p>
<p><strong>parse.py:</strong></p>
<pre><code>from xml.etree.ElementTree import parse
doc = parse('booksExample.xml')
for book in doc.findall('book'):
id = book.get('id')
title = book.findtext('title')
price = book.findtext('price')
print id, title, price
</code></pre>
<p>Just for reference, using the following as <code>booksExample.xml</code>:
<a href="https://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx</a></p>
<p><strong>output:</strong></p>
<pre><code>(parsexml)macbook:parsexml joeyoung$ python parse.py
bk101 XML Developer's Guide 44.95
bk102 Midnight Rain 5.95
bk103 Maeve Ascendant 5.95
bk104 Oberon's Legacy 5.95
bk105 The Sundered Grail 5.95
bk106 Lover Birds 4.95
bk107 Splish Splash 4.95
bk108 Creepy Crawlies 4.95
bk109 Paradox Lost 6.95
bk110 Microsoft .NET: The Programming Bible 36.95
bk111 MSXML3: A Comprehensive Guide 36.95
bk112 Visual Studio 7: A Comprehensive Guide 49.95
</code></pre>
|
python|xml|parsing
| 1 |
1,904,299 | 31,948,958 |
Create Callback from Python
|
<p>I have a python script that gets called from some javascript code, that I have running. And when the python script is finished I want a call back to go to a Java program of mine, I was trying to make a html page and then check with that, but I am running the Java program locally and can't connect to the FTP?</p>
<p>How could this be accomplished?</p>
<p>Thanks</p>
<p><strong>EDIT</strong></p>
<p>Here is how the flow works</p>
<pre><code>Java calls a javascript function in browser on my local machine ->
Javascript calls python with POST Request on my Server ->
I want a callback to Java to know when Python is done ->
So that Java can move on
</code></pre>
<p>Do you see know how it works? </p>
|
<p>If you are running from the command line you could use pipes <code>|</code> which will call the next command in line with the standard out of the first command. As follows:</p>
<p><code>firstCommand | secondCommand</code></p>
<p>So if your Python script writes to standard out you could invoke it from the command line, and have the Java execute from the command line also as the second command receiving it's input from standard in.</p>
|
javascript|java|python
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.