qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
6,091,688 | I have a Tkinter program and running it like: `python myWindow.py` starts it all right, but the window is behind the terminal that I use to start it.
Is there a way to make it grab the focus and be the foreground application? Does it depend on the platform? | 2011/05/23 | [
"https://Stackoverflow.com/questions/6091688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/175461/"
] | This might be a feature of your particular window manager. One thing to try is for your app to call `focus_force` at startup, after all the widgets have been created. | Have you tried this at the end of your script ?
```
root.iconify()
root.update()
root.deiconify()
root.mainloop()
``` |
6,091,688 | I have a Tkinter program and running it like: `python myWindow.py` starts it all right, but the window is behind the terminal that I use to start it.
Is there a way to make it grab the focus and be the foreground application? Does it depend on the platform? | 2011/05/23 | [
"https://Stackoverflow.com/questions/6091688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/175461/"
] | This might be a feature of your particular window manager. One thing to try is for your app to call `focus_force` at startup, after all the widgets have been created. | Somewhat of a combination of various other methods found online, this works on OS X 10.11, and Python 3.5.1 running in a venv, and should work on other platforms too. On OS X, it also targets the app by process id rather than app name.
```
from tkinter import Tk
import os
import subprocess
import platform
def raise_app(root: Tk):
root.attributes("-topmost", True)
if platform.system() == 'Darwin':
tmpl = 'tell application "System Events" to set frontmost of every process whose unix id is {} to true'
script = tmpl.format(os.getpid())
output = subprocess.check_call(['/usr/bin/osascript', '-e', script])
root.after(0, lambda: root.attributes("-topmost", False))
```
You call it right before the `mainloop()` call, like so:
```
raise_app(root)
root.mainloop()
``` |
68,230,917 | this is what I did. The code is down bellow. I have the music.csv dataset.
The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code.
```py
# importing Data
import pandas as pd
music_data = pd.read_csv('music.csv')
music_data
# split into training and testing- nothing to clean
# genre = predictions
# Inputs are age and gender and output is genre
# method=drop
X = music_data.drop(columns=['genre']) # has everything but genre
# X= INPUT
Y = music_data['genre'] # only genre
# Y=OUTPUT
# now select algorithm
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier() # model
model.fit(X, Y)
prediction = model.predict([[21, 1]])
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2) # 20% of date=testing
# first two input other output
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, predictions)
```
Then this error comes. This error is a value error
```
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_28312/3992581865.py in <module>
5 model.fit(X_train, y_train)
6 from sklearn.metrics import accuracy_score
----> 7 score = accuracy_score(y_test, predictions)
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
61 extra_args = len(args) - len(all_args)
62 if extra_args <= 0:
---> 63 return f(*args, **kwargs)
64
65 # extra_args > 0
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\metrics\_classification.py in accuracy_score(y_true, y_pred, normalize,
sample_weight)
200
201 # Compute accuracy for each possible representation
--> 202 y_type, y_true, y_pred = _check_targets(y_true, y_pred)
203 check_consistent_length(y_true, y_pred, sample_weight)
204 if y_type.startswith('multilabel'):
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\metrics\_classification.py in _check_targets(y_true, y_pred)
81 y_pred : array or indicator matrix
82 """
---> 83 check_consistent_length(y_true, y_pred)
84 type_true = type_of_target(y_true)
85 type_pred = type_of_target(y_pred)
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
317 uniques = np.unique(lengths)
318 if len(uniques) > 1:
--> 319 raise ValueError("Found input variables with inconsistent numbers of"
320 " samples: %r" % [int(l) for l in lengths])
321
ValueError: Found input variables with inconsistent numbers of samples: [4, 1]
```
Pls help me. I dont know whats happening but I think it has to do with this score = accuracy\_score(y\_test, predictions). | 2021/07/02 | [
"https://Stackoverflow.com/questions/68230917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14672478/"
] | I don't have your tables so I'll demonstrate it on Scott's EMP.
```
SQL> select empno, ename, to_char(hiredate, 'dd.mm.yyyy, dy') hiredate
2 from emp
3 where to_char(hiredate, 'dy', 'nls_date_language = english') in ('sat', 'sun');
EMPNO ENAME HIREDATE
---------- ---------- ------------------------
7521 WARD 22.02.1981, sun
7934 MILLER 23.01.1982, sat
SQL>
```
So, literally fetch rows whose date values fall into sat(urday) and sun(day).
---
Your query would then be
```
select client_id, created_date
from dba_clientlist
where to_char(created_date, 'dy', 'nls_date_language = english') in ('sat', 'sun');
``` | You may use ISO week as a starting point, which is culture independent:
```
select *
from your_table
where trunc(created_date) - trunc(created_date, 'IW') in (5,6)
```
ISO week starts on Monday. |
68,230,917 | this is what I did. The code is down bellow. I have the music.csv dataset.
The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code.
```py
# importing Data
import pandas as pd
music_data = pd.read_csv('music.csv')
music_data
# split into training and testing- nothing to clean
# genre = predictions
# Inputs are age and gender and output is genre
# method=drop
X = music_data.drop(columns=['genre']) # has everything but genre
# X= INPUT
Y = music_data['genre'] # only genre
# Y=OUTPUT
# now select algorithm
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier() # model
model.fit(X, Y)
prediction = model.predict([[21, 1]])
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2) # 20% of date=testing
# first two input other output
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, predictions)
```
Then this error comes. This error is a value error
```
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_28312/3992581865.py in <module>
5 model.fit(X_train, y_train)
6 from sklearn.metrics import accuracy_score
----> 7 score = accuracy_score(y_test, predictions)
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
61 extra_args = len(args) - len(all_args)
62 if extra_args <= 0:
---> 63 return f(*args, **kwargs)
64
65 # extra_args > 0
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\metrics\_classification.py in accuracy_score(y_true, y_pred, normalize,
sample_weight)
200
201 # Compute accuracy for each possible representation
--> 202 y_type, y_true, y_pred = _check_targets(y_true, y_pred)
203 check_consistent_length(y_true, y_pred, sample_weight)
204 if y_type.startswith('multilabel'):
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\metrics\_classification.py in _check_targets(y_true, y_pred)
81 y_pred : array or indicator matrix
82 """
---> 83 check_consistent_length(y_true, y_pred)
84 type_true = type_of_target(y_true)
85 type_pred = type_of_target(y_pred)
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
317 uniques = np.unique(lengths)
318 if len(uniques) > 1:
--> 319 raise ValueError("Found input variables with inconsistent numbers of"
320 " samples: %r" % [int(l) for l in lengths])
321
ValueError: Found input variables with inconsistent numbers of samples: [4, 1]
```
Pls help me. I dont know whats happening but I think it has to do with this score = accuracy\_score(y\_test, predictions). | 2021/07/02 | [
"https://Stackoverflow.com/questions/68230917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14672478/"
] | I don't have your tables so I'll demonstrate it on Scott's EMP.
```
SQL> select empno, ename, to_char(hiredate, 'dd.mm.yyyy, dy') hiredate
2 from emp
3 where to_char(hiredate, 'dy', 'nls_date_language = english') in ('sat', 'sun');
EMPNO ENAME HIREDATE
---------- ---------- ------------------------
7521 WARD 22.02.1981, sun
7934 MILLER 23.01.1982, sat
SQL>
```
So, literally fetch rows whose date values fall into sat(urday) and sun(day).
---
Your query would then be
```
select client_id, created_date
from dba_clientlist
where to_char(created_date, 'dy', 'nls_date_language = english') in ('sat', 'sun');
``` | ```
select to_char(sysdate, 'DAY') full_name,
to_char(sysdate, 'DY') abbreviation,
to_char(sysdate, 'D') day_of_week
from dual
``` |
68,230,917 | this is what I did. The code is down bellow. I have the music.csv dataset.
The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code.
```py
# importing Data
import pandas as pd
music_data = pd.read_csv('music.csv')
music_data
# split into training and testing- nothing to clean
# genre = predictions
# Inputs are age and gender and output is genre
# method=drop
X = music_data.drop(columns=['genre']) # has everything but genre
# X= INPUT
Y = music_data['genre'] # only genre
# Y=OUTPUT
# now select algorithm
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier() # model
model.fit(X, Y)
prediction = model.predict([[21, 1]])
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2) # 20% of date=testing
# first two input other output
model.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
score = accuracy_score(y_test, predictions)
```
Then this error comes. This error is a value error
```
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_28312/3992581865.py in <module>
5 model.fit(X_train, y_train)
6 from sklearn.metrics import accuracy_score
----> 7 score = accuracy_score(y_test, predictions)
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
61 extra_args = len(args) - len(all_args)
62 if extra_args <= 0:
---> 63 return f(*args, **kwargs)
64
65 # extra_args > 0
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\metrics\_classification.py in accuracy_score(y_true, y_pred, normalize,
sample_weight)
200
201 # Compute accuracy for each possible representation
--> 202 y_type, y_true, y_pred = _check_targets(y_true, y_pred)
203 check_consistent_length(y_true, y_pred, sample_weight)
204 if y_type.startswith('multilabel'):
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\metrics\_classification.py in _check_targets(y_true, y_pred)
81 y_pred : array or indicator matrix
82 """
---> 83 check_consistent_length(y_true, y_pred)
84 type_true = type_of_target(y_true)
85 type_pred = type_of_target(y_pred)
c:\users\shrey\appdata\local\programs\python\python39\lib\site-
packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
317 uniques = np.unique(lengths)
318 if len(uniques) > 1:
--> 319 raise ValueError("Found input variables with inconsistent numbers of"
320 " samples: %r" % [int(l) for l in lengths])
321
ValueError: Found input variables with inconsistent numbers of samples: [4, 1]
```
Pls help me. I dont know whats happening but I think it has to do with this score = accuracy\_score(y\_test, predictions). | 2021/07/02 | [
"https://Stackoverflow.com/questions/68230917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14672478/"
] | You may use ISO week as a starting point, which is culture independent:
```
select *
from your_table
where trunc(created_date) - trunc(created_date, 'IW') in (5,6)
```
ISO week starts on Monday. | ```
select to_char(sysdate, 'DAY') full_name,
to_char(sysdate, 'DY') abbreviation,
to_char(sysdate, 'D') day_of_week
from dual
``` |
32,016,428 | I'm getting following error while running the script and the script is to get the SPF records for a list of domains from a file and i'm not sure about the error,Can any one please help me on this issue ?
```
#!/usr/bin/python
import sys
import socket
import dns.resolver
import re
def getspf (domain):
answers = dns.resolver.query(domain, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
if txt_string.startswith('v=spf1'):
return txt_string.replace('v=spf1','')
f=open('Input_Domains.txt','r')
a=f.readlines()
domain=a
print domain
x=0
while x<len(domain):
full_spf=getspf(domain)
print 'Initial SPF string : ', full_spf
x=x+1
f.close()
```
Input\_Domains.txt
```
box.com
bhah.com
cnn.com
....
```
Error Message:
```
['box.com\n']
Traceback (most recent call last):
File "sample.py", line 22, in <module>
full_spf=getspf(domain)
File "sample.py", line 10, in getspf
answers = dns.resolver.query(domain, 'TXT')
File "/usr/local/lib/python2.7/dist-packages/dns/resolver.py", line 1027, in query
raise_on_no_answer, source_port)
File "/usr/local/lib/python2.7/dist-packages/dns/resolver.py", line 817, in query
if qname.is_absolute():
AttributeError: 'list' object has no attribute 'is_absolute'
``` | 2015/08/14 | [
"https://Stackoverflow.com/questions/32016428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5093018/"
] | `domain` is a list, not a string. You want to pass *elements* of `domain` to `getspf`, not the entire list.
```
f=open('Input_Domains.txt','r')
a=f.readlines()
domain=a
print domain
x=0
while x<len(domain):
# domain[x], not domain
full_spf=getspf(domain[x])
print 'Initial SPF string : ', full_spf
x=x+1
f.close()
```
You also don't need to read the entire file into a list at once; you can iterate over the file one line at a time.
```
with open('Input_Domains.txt','r') as f:
for line in f:
full_spf = getspf(line.strip())
print 'Initial SPF string : ', full_spf
``` | When you run `getspf (domain)`, `domain` is the whole list of domains in your file.
Instead of
```
f=open('Input_Domains.txt','r')
a=f.readlines()
domain=a
print domain
x=0
while x<len(domain):
full_spf=getspf(domain)
print 'Initial SPF string : ', full_spf
x=x+1
f.close()
```
do
```
with open('Input_Domains.txt','r') as domains_file:
for domain in domains_file:
full_spf = getspf(domain)
print 'Initial SPF string : ', full_spf
``` |
56,026,352 | I created a Django (v. 2.1.5) model called Metric that has itself as an embed model, as you can see below:
```py
from djongo import models
class Metric(models.Model):
_id = models.ObjectIdField()
...
dependencies = models.ArrayModelField(
model_container='Metric',
blank=True,
)
def __str__(self):
return self.name
class Meta:
db_table = 'metric'
```
But, when I try to execute the code:
```py
for metric in Metric.objects.all():
```
I get the following error:
```py
File "/.../python3.6/site-packages/djongo/models/fields.py", line 235, in to_python
if isinstance(mdl_dict, self.model_container):
TypeError: isinstance() arg 2 must be a type or tuple of types
```
I imagine that this error was caused by the use of single quotation marks on model\_container assignment, but I can't remove it, since the model\_container is the class itself. Also, I'm not sure if that is the reason.
In any case, what I can do to fix this error? | 2019/05/07 | [
"https://Stackoverflow.com/questions/56026352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11465606/"
] | You can create this filter:
```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import lombok.Getter;
import lombok.Setter;
public class Oauth2ClientGatewayFilter2 extends AbstractGatewayFilterFactory<Oauth2ClientGatewayFilter2.Config> {
@Autowired
private ReactiveClientRegistrationRepository clientRegistrations;
@Autowired
private ReactiveOAuth2AuthorizedClientService clientService;
public Oauth2ClientGatewayFilter2() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
OAuth2AuthorizeRequest oAuth2AuthorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("myClient")
.principal("myPrincipal").build();
ReactiveOAuth2AuthorizedClientManager manager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegistrations,clientService);
return manager.authorize(oAuth2AuthorizeRequest)
.map(client -> client.getAccessToken().getTokenValue())
.map(bearerToken -> {
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
builder.header(HttpHeaders.AUTHORIZATION, "Bearer " + bearerToken);
ServerHttpRequest request = builder.build();
return exchange.mutate().request(request).build();
}).defaultIfEmpty(exchange).flatMap(chain::filter);
};
}
@Getter
@Setter
public static class Config {
private String clientRegistrationId;
}
}
```
and define your OAuth2 configuration in application.yaml:
```
spring:
security:
oauth2:
client:
registration:
myClient:
client-name: myClient
client-id: amiga-client
client-secret: ee073dec-869d-4e8d-8fa9-9f0ec9dfd8ea
authorization-grant-type: client_credentials
provider:
myClient:
token-uri: https://myserver.com/auth/oauth/v2/token
```
You just ask the OAuth2 bearer access token to the **ReactiveOAuth2AuthorizedClientManager** and set its value in the **Authorization** header of current request. | This [sample](https://github.com/spring-cloud-samples/sample-gateway-oauth2login) shows how to set up Spring Cloud Gateway with Spring Security OAuth2. |
34,841,822 | I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as `python file.py` The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, the script might get stopped when my Internet Connection is off or at Night. So i couldn't keep running the Script Whole day on my PC..
So is there any way or website or Method where i could deploy my Script and make it Execute forever there ? I have heard about CRON JOBS before in Cpanel which can Help repeated Tasks but here in my case i want to keep running my Script on the Machine till i don't close the script .
Are their any such solutions. Because most of twitter bots i see are running forever, meaning their Script is getting executed somewhere 24x7 . This is what i want to know, How is that Task possible? | 2016/01/17 | [
"https://Stackoverflow.com/questions/34841822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5676841/"
] | I have installed it from github with the command `bower install git@github.com:angular/angular.git`:
```
$ bower install git@github.com:angular/angular.git
bower angular#* not-cached git@github.com:angular/angular.git#*
bower angular#* resolve git@github.com:angular/angular.git#*
bower angular#* checkout 2.0.0-build.ffbcb26.js
bower angular#* invalid-meta angular is missing "main" entry in bower.json
bower angular#* invalid-meta angular is missing "ignore" entry in bower.json
bower angular#* resolved git@github.com:angular/angular.git#2.0.0-build.ffbcb26.js
bower angular#~2.0.0-build.ffbcb26.js install angular#2.0.0-build.ffbcb26.js
angular#2.0.0-build.ffbcb26.js bower_components/angular
``` | I advise you not to use Bower. Bower is used to get your packages in your project folder, that's it.
Try to look up JSPM (<http://jspm.io>). It does a lot more than getting packages in your project. It takes care of ES6 to ES5. And loads all your packages in one time using SystemJS in your browser with just a couple lines of code.
you can install jspm using npm:
```
npm init
npm install (-g) jspm // -g only if you want jspm globally installed
jspm init
``` |
34,841,822 | I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as `python file.py` The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, the script might get stopped when my Internet Connection is off or at Night. So i couldn't keep running the Script Whole day on my PC..
So is there any way or website or Method where i could deploy my Script and make it Execute forever there ? I have heard about CRON JOBS before in Cpanel which can Help repeated Tasks but here in my case i want to keep running my Script on the Machine till i don't close the script .
Are their any such solutions. Because most of twitter bots i see are running forever, meaning their Script is getting executed somewhere 24x7 . This is what i want to know, How is that Task possible? | 2016/01/17 | [
"https://Stackoverflow.com/questions/34841822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5676841/"
] | I have installed it from github with the command `bower install git@github.com:angular/angular.git`:
```
$ bower install git@github.com:angular/angular.git
bower angular#* not-cached git@github.com:angular/angular.git#*
bower angular#* resolve git@github.com:angular/angular.git#*
bower angular#* checkout 2.0.0-build.ffbcb26.js
bower angular#* invalid-meta angular is missing "main" entry in bower.json
bower angular#* invalid-meta angular is missing "ignore" entry in bower.json
bower angular#* resolved git@github.com:angular/angular.git#2.0.0-build.ffbcb26.js
bower angular#~2.0.0-build.ffbcb26.js install angular#2.0.0-build.ffbcb26.js
angular#2.0.0-build.ffbcb26.js bower_components/angular
``` | This worked for me, for Angular 2 `bower install angular2-build` |
23,952,821 | I am making a dabian binary package for local use. `dpkg-buildpackage -rfakeroot` is failed due to below error.
```
find /home/dwft78/project/CoreScanner/cscore-1.0/lib -name "libcs*" -type f -exec cp -f {} /home/dwft78/project/CoreScanner/cscore-1.0/debian/cscore/opt/motorola-scanner//bin \;
find /home/dwft78/project/CoreScanner/cscore-1.0/lib -name "libcs*" -type l -exec cp -Rf {} /home/dwft78/project/CoreScanner/cscore-1.0/debian/cscore/opt/motorola-scanner//bin \;
make[1]: Leaving directory `/home/dwft78/project/CoreScanner/cscore-1.0'
dh_install
dh_installdocs
dh_installchangelogs
dh_installexamples
dh_installman
dh_installcatalogs
dh_installcron
dh_installdebconf
dh_installemacsen
dh_installifupdown
dh_installinfo
dh_pysupport
dh_pysupport: This program is deprecated, you should use dh_python2 instead. Migration guide: http://deb.li/dhs2p
dh_installinit
dh_installmenu
dh_installmime
dh_installmodules
dh_installlogcheck
dh_installlogrotate
dh_installpam
dh_installppp
dh_installudev
dh_installwm
dh_installxfonts
dh_installgsettings
dh_bugfiles
dh_ucf
dh_lintian
dh_gconf
dh_icons
dh_perl
dh_usrlocal
dh_link
dh_compress
dh_fixperms
dh_strip
dh_makeshlibs
dh_shlibdeps
dpkg-shlibdeps: warning: debian/cscore/opt/motorola-scanner/bin/libcs-common.so.1.0.0 contains an unresolvable reference to symbol g_CoreScannerLoggingContext: it's probably a plugin.
dpkg-shlibdeps: warning: 1 similar warning has been skipped (use -v to see it).
dpkg-shlibdeps: error: couldn't find library libcs-comm.so.1.0.0 needed by debian/cscore/opt/motorola-scanner/bin/libcscl-snapi.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: couldn't find library libcs-client.so.1.0.0 needed by debian/cscore/opt/motorola-scanner/bin/libcs-jni.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: warning: debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-common.so.1.0.0 contains an unresolvable reference to symbol g_CoreScannerLoggingContext: it's probably a plugin.
dpkg-shlibdeps: warning: 1 similar warning has been skipped (use -v to see it).
dpkg-shlibdeps: error: couldn't find library libcs-comm.so.1.0.0 needed by debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcscl-snapi.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: couldn't find library libcs-common.so.1.0.0 needed by debian/cscore/opt/motorola-scanner/bin/libcs-comm.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: couldn't find library libcs-common.so.1.0.0 needed by debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-comm.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: couldn't find library libcs-common.so.1.0.0 needed by debian/cscore/opt/motorola-scanner/bin/libcs-client.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: couldn't find library libcs-common.so.1.0.0 needed by debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-client.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: couldn't find library libcs-client.so.1.0.0 needed by debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-jni.so.1.0.0 (ELF format: 'elf64-x86-64'; RPATH: '').
dpkg-shlibdeps: error: Cannot continue due to the errors listed above.
Note: libraries are not searched in other binary packages that do not have any shlibs or symbols file.
To help dpkg-shlibdeps find private libraries, you might need to set LD_LIBRARY_PATH.
dh_shlibdeps: dpkg-shlibdeps -Tdebian/cscore.substvars debian/cscore/debian/cscore/opt/motorola-scanner/bin/cscore debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcscl-snapi.so.1.0.0 debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-client.so.1.0.0 debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-common.so.1.0.0 debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-jni.so.1.0.0 debian/cscore/debian/cscore/opt/motorola-scanner/bin/libcs-comm.so.1.0.0 debian/cscore/opt/motorola-scanner/bin/cscore debian/cscore/opt/motorola-scanner/bin/libcscl-snapi.so.1.0.0 debian/cscore/opt/motorola-scanner/bin/libcs-client.so.1.0.0 debian/cscore/opt/motorola-scanner/bin/libcs-common.so.1.0.0 debian/cscore/opt/motorola-scanner/bin/libcs-jni.so.1.0.0 debian/cscore/opt/motorola-scanner/bin/libcs-comm.so.1.0.0 returned exit code 2
make: *** [binary] Error 2
dpkg-buildpackage: error: fakeroot debian/rules binary gave error exit status 2
```
all these libraries are generating to "**/home/dwft78/project/CoreScanner/cscore-1.0/lib/Linux/x86\_64**"
Contents of debian/rules is
```
#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by Joey Hess and Craig Small.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by Craig Small in version 0.37 of dh-make.
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
export DH_COMPAT=5
%:
dh $@
```
As the error message indicates "**To help dpkg-shlibdeps find private libraries, you might need to set LD\_LIBRARY\_PATH**" how can I load those inside `debian/rules` file ? or otherwise is this occurred due to an another reason ? | 2014/05/30 | [
"https://Stackoverflow.com/questions/23952821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458841/"
] | Something like that could just do the trick:
```
#!/usr/bin/make -f
export DH_COMPAT=5 # though I don't know what for...
%:
dh $@
override_dh_shlibdeps:
dh_shlibdeps -l$(shell pwd)/lib/Linux/$(DEB_BUILD_GNU_CPU)
```
**Edit**
I just remembered there was an option to dh\_shlibdeps which even [got attention regarding problems with setting LD\_LIBRARY\_PATH in cross-builds](https://bugs.debian.org/698881), so this should be the option of choice. Disclaimer: I didn't test it. (I'm curious if it works out, though.) See the [dh\_shlibdeps manual page](http://manpages.ubuntu.com/manpages/trusty/man1/dh_shlibdeps.1.html). | how about just exporting `LD_LIBRARY_PATH` in `debian/rules`?
```
#!/usr/bin/make -f
export LD_LIBRARY_PATH=$(shell pwd)/lib/Linux/$(DEB_BUILD_GNU_CPU)
%:
dh $@
```
note
----
i'm using `$(DEB_BUILD_GNU_CPU)` here to calculate the value of *x86\_64*.
this might give the correct result (it will return *i386* on 32bit systems), but is most likely *not* what the build-system of your package uses to determine the architecture specific part of the path, and thus might fail.
another option (and again a wild guess) would be to use `$(shell uname -m)` (which will return *i686* on most modern 32bit systems, and *x86\_64* on 64bit systems).
in order to find out what you really should use here, you might want to inspect the build-system of your package.
sidenote
--------
you probably should *not* set the `DH_COMPAT` level in `debian/rules` but instead use the `debian/compat` file:
```
$ echo 5 > debian/compat
``` |
21,500,062 | Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far:
```
numprimes = raw_input('Prime Numbers ')
count = 0
potentialprime = 2
def primetest(potentialprime):
divisor = 2
while divisor <= potentialprime:
if potentialprime == 2:
return True
elif potentialprime % divisor == 0:
return False
break
while potentialprime % divisor != 0:
if potentialprime - divisor > 1:
divisor += 1
else:
return True
while count < int(numprimes):
if primetest(potentialprime) == True:
print potentialprime
count += 1
potentialprime += 1
else:
potentialprime += 1
```
But I get the result in a single column. How can I get it in 5 rows? | 2014/02/01 | [
"https://Stackoverflow.com/questions/21500062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3260697/"
] | ```
col=0 #add this line
while count < int(numprimes):
if primetest(potentialprime) == True:
print "%5d"%potentialprime, #and this line
col += 1 #and this block
if col==5: #
print "\n" #
col=0 #
count += 1
potentialprime += 1
else:
potentialprime += 1
``` | Add a variable for the number of the current column `currentCol` initialized to 0 and change the line `print potentialprime` to the following 5 lines:
```
print str(potentialprime).ljust(5),
currentCol += 1
if currentCol==5:
print ""
currentCol=0
```
Take notice of the call to [`ljust`](http://docs.python.org/2/library/string.html#string.ljust) and the `,` at the end of the `print` line that prevents a newline at the end of printed number. After the 5 columns printed (`if currentCol==5`) you print a newline and reset `currentCol` to 0.
See <http://ideone.com/WsLnDK> for the whole modified program with your intended output. |
21,500,062 | Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far:
```
numprimes = raw_input('Prime Numbers ')
count = 0
potentialprime = 2
def primetest(potentialprime):
divisor = 2
while divisor <= potentialprime:
if potentialprime == 2:
return True
elif potentialprime % divisor == 0:
return False
break
while potentialprime % divisor != 0:
if potentialprime - divisor > 1:
divisor += 1
else:
return True
while count < int(numprimes):
if primetest(potentialprime) == True:
print potentialprime
count += 1
potentialprime += 1
else:
potentialprime += 1
```
But I get the result in a single column. How can I get it in 5 rows? | 2014/02/01 | [
"https://Stackoverflow.com/questions/21500062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3260697/"
] | ```
col=0 #add this line
while count < int(numprimes):
if primetest(potentialprime) == True:
print "%5d"%potentialprime, #and this line
col += 1 #and this block
if col==5: #
print "\n" #
col=0 #
count += 1
potentialprime += 1
else:
potentialprime += 1
``` | ```py
while count < int(numprimes):
if primetest(potentialprime) == True:
print "%5d" % potentialprime, #and this line
col += 1 #and this block
if col == 5: #
print "\n" #
col = 0 #
count += 1
potentialprime += 1
else:
potentialprime += 1
``` |
21,500,062 | Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far:
```
numprimes = raw_input('Prime Numbers ')
count = 0
potentialprime = 2
def primetest(potentialprime):
divisor = 2
while divisor <= potentialprime:
if potentialprime == 2:
return True
elif potentialprime % divisor == 0:
return False
break
while potentialprime % divisor != 0:
if potentialprime - divisor > 1:
divisor += 1
else:
return True
while count < int(numprimes):
if primetest(potentialprime) == True:
print potentialprime
count += 1
potentialprime += 1
else:
potentialprime += 1
```
But I get the result in a single column. How can I get it in 5 rows? | 2014/02/01 | [
"https://Stackoverflow.com/questions/21500062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3260697/"
] | ```
col=0 #add this line
while count < int(numprimes):
if primetest(potentialprime) == True:
print "%5d"%potentialprime, #and this line
col += 1 #and this block
if col==5: #
print "\n" #
col=0 #
count += 1
potentialprime += 1
else:
potentialprime += 1
``` | ```
# The below code will print 1 prime number or a range of prime numbers if passed
# in the range.
def primeNumber(num):
for i in range(2,num):
if num%i==0:
return f"{num} - not a prime number"
break
else:
return f"{num} - is a prime number"
mylist = [i for i in range(1,100)]
for i in mylist:
print(primeNumber(i))
``` |
52,967,071 | I'm trying to do django api.
In models.py
```
class Receipt(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=100)
created_at = models.DateTimeField(default=datetime.datetime.now(),null=True,blank=True)
updated_at = models.DateTimeField(auto_now=True,editable=False)
```
I got error if I add in `auto_now =True`,`editable=False`. Here is my error message.
```
django.core.exceptions.FieldError: 'updated_at' cannot be specified for Receipt model form as it is a non-editable field
```
Traceback:
```
Traceback (most recent call last):
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/urls/resolvers.py", line 256, in check
for pattern in self.url_patterns:
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/urls/resolvers.py", line 407, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/urls/resolvers.py", line 400, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/uadmin/django/project/project/urls.py", line 18, in <module>
from apps import views
File "/home/uadmin/django/project/apps/views.py", line 14, in <module>
from .forms import ReceiptForm
File "/home/uadmin/django/project/apps/forms.py", line 4, in <module>
class ReceiptForm(ModelForm):
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/forms/models.py", line 266, in __new__
apply_limit_choices_to=False,
File "/home/uadmin/django/env/lib/python2.7/site-packages/django/forms/models.py", line 159, in fields_for_model
f.name, model.__name__)
django.core.exceptions.FieldError: 'updated_at' cannot be specified for Receipt model form as it is a non-editable field
```
What should I do to solve this error? | 2018/10/24 | [
"https://Stackoverflow.com/questions/52967071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10455023/"
] | The error as you could see in traceback is in you form `ReceiptForm`. `DateTimeField` with `auto_now` are `editable=False` and `blank=True` automatically, therefore could not be included in a form unless it's readonly. You could remove `auto_now` and use a custom save method to set `updated_at`.
See these questions for more info:
* [Django auto\_now and auto\_now\_add](https://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add)
* [Overriding Django auto\_now in datefiled](https://stackoverflow.com/questions/50191848/overriding-django-auto-now-in-datefiled)
* [Can't display DateField on form with auto\_now = True](https://stackoverflow.com/questions/10033422/cant-display-datefield-on-form-with-auto-now-true) | What you're trying to achieve?
[`auto_now`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField.auto_now) is to set field value for *every save*. You can't override this.
[`auto_now_add`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField.auto_now_add) is to make this once object is *created*.
[`default`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#default) is to have default value to use, when you don't provide anything.
My guess is that you simply need `default`. If not, please describe what you're solving |
61,045,138 | I have following test.bat file:
```
:begin
@echo off
python -c "from datetime import datetime;import sys;sys.stdout.write(datetime.strptime('20200220', '%Y%m%d').replace(day = 1).strftime('%Y%m%d'))"
```
When I run it from cmd, I get:
```
ValueError: time data '20200220' does not match format 'mYd'
```
Please ignore my style of writing, am I missing something? | 2020/04/05 | [
"https://Stackoverflow.com/questions/61045138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9005202/"
] | Not sure why but you need to escape the `%`. This works.
```
...
python -c "from datetime import datetime;import sys;sys.stdout.write(datetime.strptime('20200220', '%%Y%%m%%d').replace(day = 1).strftime('%%Y%%m%%d'))"
``` | See the message of error:
```
ValueError: time data '20200220' does not match format 'mYd'
```
2020 is a year 02 month and 20 the day and you try to parse with **mYd**, you need parse with **Ymd**. Set correctly position of the date format. |
62,471,080 | I am trying to rank a large dataset using python. I do not want duplicates and rather than using the 'first' method, I would instead like it to look at another column and rank it based on that value.
It should only look at the second column if the rank in the first column has duplicates.
```
Name CountA CountB
Alpha 15 3
Beta 20 52
Delta 20 31
Gamma 45 43
```
I would like the ranking to end up
```
Name CountA CountB Rank
Alpha 15 3 4
Beta 20 52 2
Delta 20 31 3
Gamma 45 43 1
```
Currently, I am using `df.rank(ascending=False, method='first')` | 2020/06/19 | [
"https://Stackoverflow.com/questions/62471080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1824972/"
] | Maybe use sort and pull out the index:
```
import pandas as pd
df = pd.DataFrame({'Name':['A','B','C','D'],'CountA':[15,20,20,45],'CountB':[3,52,31,43]})
df['rank'] = df.sort_values(['CountA','CountB'],ascending=False).index + 1
Name CountA CountB rank
0 A 15 3 4
1 B 20 52 2
2 C 20 31 3
3 D 45 43 1
``` | You can take the counts of the values in CountA and then filter the DataFrame rows based on the count of CountA being greater than 1. Where the count is greater than 1, take CountB, otherwise CountA.
```
df = pd.DataFrame([[15,3],[20,52],[20,31],[45,43]],columns=['CountA','CountB'])
colAcount = df['CountA'].value_counts()
#then take the indices where colACount > 1 and use them in a where
df['final'] = df['CountA'].where(~df['CountA'].isin(colAcount[colAcount>1].index),df['CountB'])
df = df.sort_values(by='final', ascending=False).reset_index(drop=True)
# the rank is the index
CountA CountB final
0 20 52 52
1 45 43 45
2 20 31 31
3 15 3 15
```
See [this](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.where.html) for more details. |
61,385,291 | I'm working on Express with NodeJS to build some custom APIs.
I've successfully build some APIs.
Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
```
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
```
Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData.
How am i supposed to it using POST calls?
I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785631/"
] | In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app.
Then you have to add the POST route and the methods to your app.js file. Then hit the route with by parsing data through the body. I have edited your code and posted it below. I have commented on the places where I added the methods and middleware.
```
const express = require('express');
const app = express();
// require body parser middleware
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Create user data.
const userData = [
{
id: 673630,
firstName: 'Prasanta',
lastName: 'Banerjee',
age: 24,
hobby: [
{
coding: ['java', 'python', 'javascript'],
movies: ['action', 'comedy', 'suspense'],
sports: "basketball"
}
],
oper_sys: ['Mac', 'Windows']
},
{
id: 673631,
firstName: 'Neha',
lastName: 'Bharti',
age: 23
},
{
id: 673651,
firstName: 'Priyanka',
lastName: 'Moharana',
age: 24
},
{
id: 673649,
firstName: 'Shreyanshu',
lastName: 'Jena',
age: 25
},
{
id: 673632,
firstName: 'Priyanka',
lastName: 'Sonalia',
age: 23
},
{
id: 673653,
firstName: 'Bhupinder',
lastName: 'Singh',
age: 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if (user) {
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({ Error: ['ID Not Found'] });
}
});
// POST emplyee data
app.post('/api/employees/', function (req, res) {
// catch request body data, break it down and assign it to a variable
// you can just parse req.body as well
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
res.status(200).json(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});
``` | It would be something like this assuming your passing json in the post request:
Your request body would be like this:
```
{
"id": "1",
"firstName": "First Name",
"lastName": "Last Name"
}
```
```
app.post('/api/employees', function(req, res) {
if(req.body) {
userData.push(req.body)
}
else {
res.statusCode = 500
return res.json({Error: ['Object Missing']});
}
});
``` |
61,385,291 | I'm working on Express with NodeJS to build some custom APIs.
I've successfully build some APIs.
Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
```
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
```
Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData.
How am i supposed to it using POST calls?
I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785631/"
] | In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app.
Then you have to add the POST route and the methods to your app.js file. Then hit the route with by parsing data through the body. I have edited your code and posted it below. I have commented on the places where I added the methods and middleware.
```
const express = require('express');
const app = express();
// require body parser middleware
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Create user data.
const userData = [
{
id: 673630,
firstName: 'Prasanta',
lastName: 'Banerjee',
age: 24,
hobby: [
{
coding: ['java', 'python', 'javascript'],
movies: ['action', 'comedy', 'suspense'],
sports: "basketball"
}
],
oper_sys: ['Mac', 'Windows']
},
{
id: 673631,
firstName: 'Neha',
lastName: 'Bharti',
age: 23
},
{
id: 673651,
firstName: 'Priyanka',
lastName: 'Moharana',
age: 24
},
{
id: 673649,
firstName: 'Shreyanshu',
lastName: 'Jena',
age: 25
},
{
id: 673632,
firstName: 'Priyanka',
lastName: 'Sonalia',
age: 23
},
{
id: 673653,
firstName: 'Bhupinder',
lastName: 'Singh',
age: 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if (user) {
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({ Error: ['ID Not Found'] });
}
});
// POST emplyee data
app.post('/api/employees/', function (req, res) {
// catch request body data, break it down and assign it to a variable
// you can just parse req.body as well
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
res.status(200).json(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});
``` | ```
const express = require('express');
const app = express();
//including the body-parser
app.use(express.json()).use(express.urlencoded({ extended: false }));
//Create user data.
//your get routes
//post route
app.post('/api/employees',function(req,res) {
//posted data is available in req.body
//do any validations if required
userData.push(req.body);
res.send("success")
}
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit
the APIs.');
});
```
you can check the post method for express [here](http://expressjs.com/en/api.html#app.post.method) |
61,385,291 | I'm working on Express with NodeJS to build some custom APIs.
I've successfully build some APIs.
Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
```
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
```
Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData.
How am i supposed to it using POST calls?
I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785631/"
] | In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app.
Then you have to add the POST route and the methods to your app.js file. Then hit the route with by parsing data through the body. I have edited your code and posted it below. I have commented on the places where I added the methods and middleware.
```
const express = require('express');
const app = express();
// require body parser middleware
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Create user data.
const userData = [
{
id: 673630,
firstName: 'Prasanta',
lastName: 'Banerjee',
age: 24,
hobby: [
{
coding: ['java', 'python', 'javascript'],
movies: ['action', 'comedy', 'suspense'],
sports: "basketball"
}
],
oper_sys: ['Mac', 'Windows']
},
{
id: 673631,
firstName: 'Neha',
lastName: 'Bharti',
age: 23
},
{
id: 673651,
firstName: 'Priyanka',
lastName: 'Moharana',
age: 24
},
{
id: 673649,
firstName: 'Shreyanshu',
lastName: 'Jena',
age: 25
},
{
id: 673632,
firstName: 'Priyanka',
lastName: 'Sonalia',
age: 23
},
{
id: 673653,
firstName: 'Bhupinder',
lastName: 'Singh',
age: 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if (user) {
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({ Error: ['ID Not Found'] });
}
});
// POST emplyee data
app.post('/api/employees/', function (req, res) {
// catch request body data, break it down and assign it to a variable
// you can just parse req.body as well
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
res.status(200).json(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});
``` | This is my full code snippet (index.js)
As you can see, i have created a post call function which takes data from 'data' const and sends to the server. But still it doesn't work.
```
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false })); //support encoded bodies.
app.use(bodyParser.json()); //support json encoded bodies.
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display a message.
app.get('/api/info', function(req, res) {
res.send('Welcome to Employees API !!! Get access to free APIs.');
});
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
//Retrieve the 'id' param from endpoint.
const id = req.params.id;
//Search for that 'id' param in the 'userdata'.
const user = userData.find(user => user.id == id)
//If found, then display the data to the user.
if(user){
res.statusCode = 200
res.json(user)
}
//Else, display error message.
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
//res.send("Oops !!! No User with ID:" + id + " was found.")
}
});
const data = [ {
id : 12345,
firstName : 'new',
lastName : 'data',
age : 29
}]
// POST employee data
app.post('/api/employees/', function (req, res) {
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
``` |
61,385,291 | I'm working on Express with NodeJS to build some custom APIs.
I've successfully build some APIs.
Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
```
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
```
Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData.
How am i supposed to it using POST calls?
I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785631/"
] | In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app.
Then you have to add the POST route and the methods to your app.js file. Then hit the route with by parsing data through the body. I have edited your code and posted it below. I have commented on the places where I added the methods and middleware.
```
const express = require('express');
const app = express();
// require body parser middleware
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Create user data.
const userData = [
{
id: 673630,
firstName: 'Prasanta',
lastName: 'Banerjee',
age: 24,
hobby: [
{
coding: ['java', 'python', 'javascript'],
movies: ['action', 'comedy', 'suspense'],
sports: "basketball"
}
],
oper_sys: ['Mac', 'Windows']
},
{
id: 673631,
firstName: 'Neha',
lastName: 'Bharti',
age: 23
},
{
id: 673651,
firstName: 'Priyanka',
lastName: 'Moharana',
age: 24
},
{
id: 673649,
firstName: 'Shreyanshu',
lastName: 'Jena',
age: 25
},
{
id: 673632,
firstName: 'Priyanka',
lastName: 'Sonalia',
age: 23
},
{
id: 673653,
firstName: 'Bhupinder',
lastName: 'Singh',
age: 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if (user) {
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({ Error: ['ID Not Found'] });
}
});
// POST emplyee data
app.post('/api/employees/', function (req, res) {
// catch request body data, break it down and assign it to a variable
// you can just parse req.body as well
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
res.status(200).json(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});
``` | I am considering you will push this data from any UI Front-End or via Postman and you know how to use it. The below solution will store data in an array, but for production, you must use a database as a solution to persist data.
Since you have not mentioned which Express version you are using, I recommend to firstly do install a package called `body-parser`.
For More Info: <https://www.npmjs.com/package/body-parser>
```
const bodyParser = require("body-parser"); // require it
app.use(bodyParser()); // you may also use Express' built-in app.use(express.json()); as an alterative
app.post('/api/employees', (req, res) => { //ES6 Feature: Arrow Syntax
const { id, firstName, lastName } = req.body; //ES6 Feature: Object Destructuring
const newUserData = {
id, // when playing with arrays, try userData.length + 1 to auto-generate an id. Omit this field then; while passing from UI/Postman
firstName, // pass a string from the UI/Postman. "Michael" in your case
lastName // pass a string from the UI/Postman. "Andrews" in your case
}; // ES6 Feature: Equivalent to {id: id, firstName: firstName, lastName: lastName}
userData.push(newUserData); // use unshift(); instead of push() if you want to add it at the start of an array
res.status(201).send(newUserData); // 201 = response code for creation. Instead of send(), json() can also be used.
});
```
Please Note: *I have included comments in every line of my code to make you understand it fully and will be helpful for others as well.* |
61,385,291 | I'm working on Express with NodeJS to build some custom APIs.
I've successfully build some APIs.
Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
```
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
```
Let's say i want to add id:12345 firstName:Michael lastName:Andrews to my userData.
How am i supposed to it using POST calls?
I'm looking for code using which i can add new data to my userData, so that every time i do GET on it, i get the updated dataset. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785631/"
] | In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app.
Then you have to add the POST route and the methods to your app.js file. Then hit the route with by parsing data through the body. I have edited your code and posted it below. I have commented on the places where I added the methods and middleware.
```
const express = require('express');
const app = express();
// require body parser middleware
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Create user data.
const userData = [
{
id: 673630,
firstName: 'Prasanta',
lastName: 'Banerjee',
age: 24,
hobby: [
{
coding: ['java', 'python', 'javascript'],
movies: ['action', 'comedy', 'suspense'],
sports: "basketball"
}
],
oper_sys: ['Mac', 'Windows']
},
{
id: 673631,
firstName: 'Neha',
lastName: 'Bharti',
age: 23
},
{
id: 673651,
firstName: 'Priyanka',
lastName: 'Moharana',
age: 24
},
{
id: 673649,
firstName: 'Shreyanshu',
lastName: 'Jena',
age: 25
},
{
id: 673632,
firstName: 'Priyanka',
lastName: 'Sonalia',
age: 23
},
{
id: 673653,
firstName: 'Bhupinder',
lastName: 'Singh',
age: 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if (user) {
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({ Error: ['ID Not Found'] });
}
});
// POST emplyee data
app.post('/api/employees/', function (req, res) {
// catch request body data, break it down and assign it to a variable
// you can just parse req.body as well
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
res.status(200).json(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});
``` | **Sending POST data**
You need to specify *Accept* and *Content-Type* headers and stringify the JSON object in the POST request.
```
var userData = {
id : 42069,
firstName : 'Bob',
lastName : 'Ross',
age : 69
}
fetch('/api/employees', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
})
.then(res => res.json())
.then(data => {
console.log(data);
})
```
**How to receive POST on express**
```
app.post('/api/employees', function (req, res) {
console.log(req.body);
//req.body will have your new user data. append that to exsisting userData array
var newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName,
age: req.body.age
}
userData.push(newUser);
res.json({status: 'New user added'})
})
```
you need to declare the userData array globally or better use a database. |
14,095,023 | I created a custom paster command as described in <http://pythonpaste.org/script/developer.html#what-do-commands-look-like>. In my setup.py I have defined the entry point like this:
```
entry_points={
'paste.global_paster_command' : [
'xxx_new = xxxconf.main:NewXxx'
]
}
```
I'm inside an activated virtualenv and have installed my package via
```
python setup.py develop
```
If I run `paster` while inside my package folder, I see my custom command and I can run it via `paster xxx ...`. But if I leave my package folder `paster` does not display my command anymore. I checked `which paster` and it's the version of my virtualenv. I also started a python interpreter and imported `xxxconf` and it works fine.
I have no idea why my global command is not recognized when I'm outside my package folder!? | 2012/12/30 | [
"https://Stackoverflow.com/questions/14095023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110963/"
] | You are doing something wrong, it should work. This is the minimal working example, you can test it with your virtualenv:
`blah/setup.py`:
```
from setuptools import setup, find_packages
setup(name='blah',
version='0.1',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
entry_points={'paste.global_paster_command': [ "xxx_new = blah.xxx:NewXxx", ] },
)
```
`blah/blah/xxx.py`:
```
from paste.script import command
class NewXxx(command.Command):
usage = "PREFIX"
summary = "some command"
group_name = "my group"
```
`blah/blah/__init__.py`: empty.
Now testing:
```
$ pwd
/tmp
$ virtualenv paster
New python executable in paster/bin/python
Installing setuptools............done.
Installing pip...............done.
$ . paster/bin/activate
(paster)$ pip install PasteScript
Downloading/unpacking PasteScript
[... skipping long pip output here ...]
(paster)$ paster
[...]
Commands:
create Create the file layout for a Python distribution
help Display help
make-config Install a package and create a fresh config file/directory
points Show information about entry points
post Run a request for the described application
request Run a request for the described application
serve Serve the described application
setup-app Setup an application, given a config file
(paster)$ cd blah/
(paster)$ python setup.py develop
running develop
[... skipping setup.py output...]
(paster)$ paster
[...]
Commands:
create Create the file layout for a Python distribution
help Display help
make-config Install a package and create a fresh config file/directory
points Show information about entry points
post Run a request for the described application
request Run a request for the described application
serve Serve the described application
setup-app Setup an application, given a config file
my group:
xxx_new some command
(paster)$ cd ~
(paster)$ paster
[...]
Commands:
[...]
setup-app Setup an application, given a config file
my group:
xxx_new some command
``` | You should install your paster\_script in the active virtualenv. Then you can use it anywhere. |
51,601,502 | I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code
```
import tensorflow as tf
from tensorflow.data import Dataset
import os
def enumerate_all_files(rootdir):
for subdir, dir, files in os.walk(rootdir):
for file in files:
# return path to the file and its label
# label is simply a 1 or 0 depending on whether an image is in the "Genuine" folder or not
yield os.path.join(subdir, file), int(subdir.split(os.path.sep)[-1] == "Genuine")
def input_parser(img_path, label):
# convert the label to one-hot encoding
one_hot = tf.one_hot(label, 2)
# read the img from file
img_file = tf.read_file(img_path)
img_decoded = tf.image.decode_png(img_file, channels=3)
return img_decoded, one_hot
def get_dataset():
generator = lambda: enumerate_all_files("/tmp/images/training/")
dataset = Dataset.from_generator(generator, (tf.string, tf.int32)).shuffle(1000).batch(100)
dataset = dataset.map(input_parser)
return dataset
```
However, when I run it in my terminal with
```
tf.enable_eager_execution()
# all the code above
d = get_dataset()
for f in d.make_one_shot_iterator():
print(f)
```
it crashes with an error
```
W tensorflow/core/framework/op_kernel.cc:1306] Unknown: SystemError: <weakref at 0x7ff8232f0620; to 'function' at 0x7ff8233c9048 (generator_py_func)> returned a result with an error set
TypeError: expected bytes, str found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "lcnn.py", line 29, in <module>
for f in d.make_one_shot_iterator():
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 487, in __next__
return self.next()
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 518, in next
return self._next_internal()
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 508, in _next_internal
output_shapes=self._flat_output_shapes)
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 1848, in iterator_get_next_sync
"output_types", output_types, "output_shapes", output_shapes)
SystemError: <built-in function TFE_Py_FastPathExecute> returned a result with an error set
```
What am I doing wrong here?
**EDIT**
I tried running the code without calling `map`, `shuffle` and `batch` as well as commenting out the `input_parser` merthod but the error still appears.
**EDIT 2**
I changed `Dataset.from_generator` to `Dataset.from_tensor_slices` to see if the code for opening the pictures works. So the changed code looks like
```
def input_parser(img_path):
# convert the label to one-hot encoding
# one_hot = tf.one_hot(label, 2)
# read the img from file
img_file = tf.read_file(img_path)
img_decoded = tf.image.decode_png(img_file, channels=3)
return img_decoded
def get_dataset():
dataset = Dataset.from_tensor_slices(["/tmp/images/training/1000010.png"]).map(input_parser).shuffle(1000).batch(100)
return dataset
```
This works fine though | 2018/07/30 | [
"https://Stackoverflow.com/questions/51601502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | Counterexample
==============
Using the assumptions below about the statement of the problem (times are effectively given as values such as .06 for 60 milliseconds), if we convert .06 to `float` and add it 1800 times, the computed result is 107.99884796142578125. This differs from the mathematical result, 108.000, by more than .001. Therefore, the computed result will sometimes differ from the mathematical result by more than 1 millisecond, so the goal desired in the question is not achievable in these conditions. (Further refinement of the problem statement and alternate means of computation may be able to achieve the goal.)
Original Analysis
=================
Suppose we have 1800 integer values in [1, 60] that are converted to `float` using `float y = x / 1000.f;`, where all operations are implemented using IEEE-754 basic 32-bit binary floating-point with correct rounding.
The conversions of 1 to 60 to `float` are exact. The division by 1000 has an error of at most ½ ULP(.06), which is ½ • 2−5 • 2−23 = 2−29. 1800 such errors amount to at most 1800 • 2−29.
As the resulting `float` values are added, there may be an error of at most ½ ULP in each addition, where the ULP is that of the current result. For a loose analysis, we can bound this with the ULP of the final result, which is at most around 1800 • .06 = 108, which has an ULP of 26 • 2−23 = 2−17. So each of the 1799 additions has an error of at most 2−17, so the total errors in the additions is at most 1799 • 2−18.
Thus, the total error during divisions and additions is at most 1800 • 2−29 + 1799 • 2−18, which is about .006866.
That is a problem. I expect a better analysis of the errors in the additions would halve the error bound, as it is an arithmetic progression from 0 to the total, but that still leaves a potential error above .003, which means there is a possibility the sum could be off by several milliseconds.
Note that if the times are added as integers, the largest potential sum is 1800•60 = 108,000, which is well below the first integer not representable in `float` (16,777,217). Addition of these integers in `float` would be error-free.
This bound of .003 is small enough that some additional constraints on the problem and some additional analysis might, just might, push it below .0005, in which case the computed result will always be close enough to the correct mathematical result that rounding the computed result to the nearest millisecond would produce the correct answer.
For example, if it were known that, while the times range from 1 to 60 milliseconds, the total is always less than 7.8 seconds, that could suffice. | ### As much as possible, reduce the errors caused by floating point calculations
Since you've already described measuring your individual timings in milliseconds, it's far better if you accumulate those timings using integer values before you finally divide them:
```
std::milliseconds duration{};
for(Timing const& timing : timings) {
//Lossless integer accumulation, in a scenario where overflow is extremely unlikely
//or possibly even impossible for your problem domain
duration += std::milliseconds(timing.getTicks());
}
//Only one floating-point calculation performed, error is minimal
float averageTiming = duration.count() / float(timings.size());
```
### The Errors that accumulate are highly particular to the scenario
Consider these two ways of accumulating values:
```
#include<iostream>
int main() {
//Make them volatile to prevent compilers from optimizing away the additions
volatile float sum1 = 0, sum2 = 0;
for(float i = 0.0001; i < 1000; i += 0.0001) {
sum1 += i;
}
for(float i = 1000; i > 0; i -= 0.0001) {
sum2 += i;
}
std::cout << "Sum1: " << sum1 << std::endl;
std::cout << "Sum2: " << sum2 << std::endl;
std::cout << "% Difference: " << (sum2 - sum1) / (sum1 > sum2 ? sum1 : sum2) * 100 << "%" << std::endl;
return 0;
}
```
Results may vary on some machines (particularly machines that don't have IEEE754 `float`s), but in my tests, the second value was 3% different than the first value, a difference of 13 million. That can be pretty significant.
Like before, the best option is to minimize the number of calculations performed using floating point values until the last possible step before you need them as floating point values. That will minimize accuracy losses. |
51,601,502 | I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code
```
import tensorflow as tf
from tensorflow.data import Dataset
import os
def enumerate_all_files(rootdir):
for subdir, dir, files in os.walk(rootdir):
for file in files:
# return path to the file and its label
# label is simply a 1 or 0 depending on whether an image is in the "Genuine" folder or not
yield os.path.join(subdir, file), int(subdir.split(os.path.sep)[-1] == "Genuine")
def input_parser(img_path, label):
# convert the label to one-hot encoding
one_hot = tf.one_hot(label, 2)
# read the img from file
img_file = tf.read_file(img_path)
img_decoded = tf.image.decode_png(img_file, channels=3)
return img_decoded, one_hot
def get_dataset():
generator = lambda: enumerate_all_files("/tmp/images/training/")
dataset = Dataset.from_generator(generator, (tf.string, tf.int32)).shuffle(1000).batch(100)
dataset = dataset.map(input_parser)
return dataset
```
However, when I run it in my terminal with
```
tf.enable_eager_execution()
# all the code above
d = get_dataset()
for f in d.make_one_shot_iterator():
print(f)
```
it crashes with an error
```
W tensorflow/core/framework/op_kernel.cc:1306] Unknown: SystemError: <weakref at 0x7ff8232f0620; to 'function' at 0x7ff8233c9048 (generator_py_func)> returned a result with an error set
TypeError: expected bytes, str found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "lcnn.py", line 29, in <module>
for f in d.make_one_shot_iterator():
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 487, in __next__
return self.next()
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 518, in next
return self._next_internal()
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 508, in _next_internal
output_shapes=self._flat_output_shapes)
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 1848, in iterator_get_next_sync
"output_types", output_types, "output_shapes", output_shapes)
SystemError: <built-in function TFE_Py_FastPathExecute> returned a result with an error set
```
What am I doing wrong here?
**EDIT**
I tried running the code without calling `map`, `shuffle` and `batch` as well as commenting out the `input_parser` merthod but the error still appears.
**EDIT 2**
I changed `Dataset.from_generator` to `Dataset.from_tensor_slices` to see if the code for opening the pictures works. So the changed code looks like
```
def input_parser(img_path):
# convert the label to one-hot encoding
# one_hot = tf.one_hot(label, 2)
# read the img from file
img_file = tf.read_file(img_path)
img_decoded = tf.image.decode_png(img_file, channels=3)
return img_decoded
def get_dataset():
dataset = Dataset.from_tensor_slices(["/tmp/images/training/1000010.png"]).map(input_parser).shuffle(1000).batch(100)
return dataset
```
This works fine though | 2018/07/30 | [
"https://Stackoverflow.com/questions/51601502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | Counterexample
==============
Using the assumptions below about the statement of the problem (times are effectively given as values such as .06 for 60 milliseconds), if we convert .06 to `float` and add it 1800 times, the computed result is 107.99884796142578125. This differs from the mathematical result, 108.000, by more than .001. Therefore, the computed result will sometimes differ from the mathematical result by more than 1 millisecond, so the goal desired in the question is not achievable in these conditions. (Further refinement of the problem statement and alternate means of computation may be able to achieve the goal.)
Original Analysis
=================
Suppose we have 1800 integer values in [1, 60] that are converted to `float` using `float y = x / 1000.f;`, where all operations are implemented using IEEE-754 basic 32-bit binary floating-point with correct rounding.
The conversions of 1 to 60 to `float` are exact. The division by 1000 has an error of at most ½ ULP(.06), which is ½ • 2−5 • 2−23 = 2−29. 1800 such errors amount to at most 1800 • 2−29.
As the resulting `float` values are added, there may be an error of at most ½ ULP in each addition, where the ULP is that of the current result. For a loose analysis, we can bound this with the ULP of the final result, which is at most around 1800 • .06 = 108, which has an ULP of 26 • 2−23 = 2−17. So each of the 1799 additions has an error of at most 2−17, so the total errors in the additions is at most 1799 • 2−18.
Thus, the total error during divisions and additions is at most 1800 • 2−29 + 1799 • 2−18, which is about .006866.
That is a problem. I expect a better analysis of the errors in the additions would halve the error bound, as it is an arithmetic progression from 0 to the total, but that still leaves a potential error above .003, which means there is a possibility the sum could be off by several milliseconds.
Note that if the times are added as integers, the largest potential sum is 1800•60 = 108,000, which is well below the first integer not representable in `float` (16,777,217). Addition of these integers in `float` would be error-free.
This bound of .003 is small enough that some additional constraints on the problem and some additional analysis might, just might, push it below .0005, in which case the computed result will always be close enough to the correct mathematical result that rounding the computed result to the nearest millisecond would produce the correct answer.
For example, if it were known that, while the times range from 1 to 60 milliseconds, the total is always less than 7.8 seconds, that could suffice. | Just for what it's worth, here's some code to demonstrate that yes, after 1800 items, a simple accumulation can be incorrect by more than 1 millisecond, but Kahan summation maintains the required level of accuracy.
```
#include <iostream>
#include <iterator>
#include <iomanip>
#include <vector>
#include <numeric>
template <class InIt>
typename std::iterator_traits<InIt>::value_type accumulate(InIt begin, InIt end)
{
typedef typename std::iterator_traits<InIt>::value_type real;
real sum = real();
real running_error = real();
for (; begin != end; ++begin)
{
real difference = *begin - running_error;
real temp = sum + difference;
running_error = (temp - sum) - difference;
sum = temp;
}
return sum;
}
int main()
{
const float addend = 0.06f;
const float count = 1800.0f;
std::vector<float> d;
std::fill_n(std::back_inserter(d), count, addend);
float result = std::accumulate(d.begin(), d.end(), 0.0f);
float result2 = accumulate(d.begin(), d.end());
float reference = count * addend;
std::cout << " simple: " << std::setprecision(20) << result << "\n";
std::cout << " Kahan: " << std::setprecision(20) << result2 << "\n";
std::cout << "Reference: " << std::setprecision(20) << reference << "\n";
}
```
For this particular test, it appears that double precision is sufficient, at least for the input values I tried--but to be honest, I'm still a bit leery of it, especially when exhaustive testing isn't reasonable, and better techniques are easily available. |
51,601,502 | I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code
```
import tensorflow as tf
from tensorflow.data import Dataset
import os
def enumerate_all_files(rootdir):
for subdir, dir, files in os.walk(rootdir):
for file in files:
# return path to the file and its label
# label is simply a 1 or 0 depending on whether an image is in the "Genuine" folder or not
yield os.path.join(subdir, file), int(subdir.split(os.path.sep)[-1] == "Genuine")
def input_parser(img_path, label):
# convert the label to one-hot encoding
one_hot = tf.one_hot(label, 2)
# read the img from file
img_file = tf.read_file(img_path)
img_decoded = tf.image.decode_png(img_file, channels=3)
return img_decoded, one_hot
def get_dataset():
generator = lambda: enumerate_all_files("/tmp/images/training/")
dataset = Dataset.from_generator(generator, (tf.string, tf.int32)).shuffle(1000).batch(100)
dataset = dataset.map(input_parser)
return dataset
```
However, when I run it in my terminal with
```
tf.enable_eager_execution()
# all the code above
d = get_dataset()
for f in d.make_one_shot_iterator():
print(f)
```
it crashes with an error
```
W tensorflow/core/framework/op_kernel.cc:1306] Unknown: SystemError: <weakref at 0x7ff8232f0620; to 'function' at 0x7ff8233c9048 (generator_py_func)> returned a result with an error set
TypeError: expected bytes, str found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "lcnn.py", line 29, in <module>
for f in d.make_one_shot_iterator():
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 487, in __next__
return self.next()
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 518, in next
return self._next_internal()
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 508, in _next_internal
output_shapes=self._flat_output_shapes)
File "/opt/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 1848, in iterator_get_next_sync
"output_types", output_types, "output_shapes", output_shapes)
SystemError: <built-in function TFE_Py_FastPathExecute> returned a result with an error set
```
What am I doing wrong here?
**EDIT**
I tried running the code without calling `map`, `shuffle` and `batch` as well as commenting out the `input_parser` merthod but the error still appears.
**EDIT 2**
I changed `Dataset.from_generator` to `Dataset.from_tensor_slices` to see if the code for opening the pictures works. So the changed code looks like
```
def input_parser(img_path):
# convert the label to one-hot encoding
# one_hot = tf.one_hot(label, 2)
# read the img from file
img_file = tf.read_file(img_path)
img_decoded = tf.image.decode_png(img_file, channels=3)
return img_decoded
def get_dataset():
dataset = Dataset.from_tensor_slices(["/tmp/images/training/1000010.png"]).map(input_parser).shuffle(1000).batch(100)
return dataset
```
This works fine though | 2018/07/30 | [
"https://Stackoverflow.com/questions/51601502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | ### As much as possible, reduce the errors caused by floating point calculations
Since you've already described measuring your individual timings in milliseconds, it's far better if you accumulate those timings using integer values before you finally divide them:
```
std::milliseconds duration{};
for(Timing const& timing : timings) {
//Lossless integer accumulation, in a scenario where overflow is extremely unlikely
//or possibly even impossible for your problem domain
duration += std::milliseconds(timing.getTicks());
}
//Only one floating-point calculation performed, error is minimal
float averageTiming = duration.count() / float(timings.size());
```
### The Errors that accumulate are highly particular to the scenario
Consider these two ways of accumulating values:
```
#include<iostream>
int main() {
//Make them volatile to prevent compilers from optimizing away the additions
volatile float sum1 = 0, sum2 = 0;
for(float i = 0.0001; i < 1000; i += 0.0001) {
sum1 += i;
}
for(float i = 1000; i > 0; i -= 0.0001) {
sum2 += i;
}
std::cout << "Sum1: " << sum1 << std::endl;
std::cout << "Sum2: " << sum2 << std::endl;
std::cout << "% Difference: " << (sum2 - sum1) / (sum1 > sum2 ? sum1 : sum2) * 100 << "%" << std::endl;
return 0;
}
```
Results may vary on some machines (particularly machines that don't have IEEE754 `float`s), but in my tests, the second value was 3% different than the first value, a difference of 13 million. That can be pretty significant.
Like before, the best option is to minimize the number of calculations performed using floating point values until the last possible step before you need them as floating point values. That will minimize accuracy losses. | Just for what it's worth, here's some code to demonstrate that yes, after 1800 items, a simple accumulation can be incorrect by more than 1 millisecond, but Kahan summation maintains the required level of accuracy.
```
#include <iostream>
#include <iterator>
#include <iomanip>
#include <vector>
#include <numeric>
template <class InIt>
typename std::iterator_traits<InIt>::value_type accumulate(InIt begin, InIt end)
{
typedef typename std::iterator_traits<InIt>::value_type real;
real sum = real();
real running_error = real();
for (; begin != end; ++begin)
{
real difference = *begin - running_error;
real temp = sum + difference;
running_error = (temp - sum) - difference;
sum = temp;
}
return sum;
}
int main()
{
const float addend = 0.06f;
const float count = 1800.0f;
std::vector<float> d;
std::fill_n(std::back_inserter(d), count, addend);
float result = std::accumulate(d.begin(), d.end(), 0.0f);
float result2 = accumulate(d.begin(), d.end());
float reference = count * addend;
std::cout << " simple: " << std::setprecision(20) << result << "\n";
std::cout << " Kahan: " << std::setprecision(20) << result2 << "\n";
std::cout << "Reference: " << std::setprecision(20) << reference << "\n";
}
```
For this particular test, it appears that double precision is sufficient, at least for the input values I tried--but to be honest, I'm still a bit leery of it, especially when exhaustive testing isn't reasonable, and better techniques are easily available. |
58,088,175 | This is similar to [this question](https://stackoverflow.com/questions/45221014/python-exif-cant-find-date-taken-information-but-exists-when-viewer-through-wi), except that the solution there doesn't work for me.
Viewing a HEIC file in Windows Explorer, I can see several dates. The one that matches what I know is the date I took the photo is headed 'Date' and 'Date taken'. The other dates aren't what I want.
[Image in Windows Explorer](https://i.stack.imgur.com/c4aqc.png)
I've tried two methods to get EXIF data from this file in Python:
```
from PIL import Image
_EXIF_DATE_TAG = 36867
img = Image.open(fileName)
info = img._getexif()
c.debug('info is', info)
# If info != None, search for _EXIF_DATE_TAG
```
This works for lots of other images, but for my HEIC files info is None.
I found the question linked above, and tried the answer there (exifread):
```
import exifread
with open(filename, 'rb') as image:
exif = exifread.process_file(image)
```
and exif here is None. So I wondered if the dates are encoded in the file in some other way, not EXIF, but these two tools seem to show otherwise:
<http://exif.regex.info/exif.cgi> shows:
[EXIF Site](https://i.stack.imgur.com/Jxn9M.png)
and [exiftool](https://www.sno.phy.queensu.ca/~phil/exiftool/) shows:
[exiftool](https://i.stack.imgur.com/C7T22.png)
So I'm thoroughly confused! Am I seeing EXIF data in Windows Explorer and these tools? And if so, why is neither Python tool seeing it?
Thanks for any help!
Windows 10, Python 2.7.16. The photos were taken on an iPhone XS, if that's relevant.
**Update:** Converting the HEIC file to a jpg, both methods work fine. | 2019/09/24 | [
"https://Stackoverflow.com/questions/58088175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123047/"
] | It's a HEIC file issue - it's not supported apparently, some difficulties around licensing I think. | While doing it with `mdls`, it's better (performance-wise) to give it a whole bunch of filenames separated by space at once.
I tested with 1000 files: works fine, 20 times performance gain. |
58,088,175 | This is similar to [this question](https://stackoverflow.com/questions/45221014/python-exif-cant-find-date-taken-information-but-exists-when-viewer-through-wi), except that the solution there doesn't work for me.
Viewing a HEIC file in Windows Explorer, I can see several dates. The one that matches what I know is the date I took the photo is headed 'Date' and 'Date taken'. The other dates aren't what I want.
[Image in Windows Explorer](https://i.stack.imgur.com/c4aqc.png)
I've tried two methods to get EXIF data from this file in Python:
```
from PIL import Image
_EXIF_DATE_TAG = 36867
img = Image.open(fileName)
info = img._getexif()
c.debug('info is', info)
# If info != None, search for _EXIF_DATE_TAG
```
This works for lots of other images, but for my HEIC files info is None.
I found the question linked above, and tried the answer there (exifread):
```
import exifread
with open(filename, 'rb') as image:
exif = exifread.process_file(image)
```
and exif here is None. So I wondered if the dates are encoded in the file in some other way, not EXIF, but these two tools seem to show otherwise:
<http://exif.regex.info/exif.cgi> shows:
[EXIF Site](https://i.stack.imgur.com/Jxn9M.png)
and [exiftool](https://www.sno.phy.queensu.ca/~phil/exiftool/) shows:
[exiftool](https://i.stack.imgur.com/C7T22.png)
So I'm thoroughly confused! Am I seeing EXIF data in Windows Explorer and these tools? And if so, why is neither Python tool seeing it?
Thanks for any help!
Windows 10, Python 2.7.16. The photos were taken on an iPhone XS, if that's relevant.
**Update:** Converting the HEIC file to a jpg, both methods work fine. | 2019/09/24 | [
"https://Stackoverflow.com/questions/58088175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123047/"
] | On `macOS` you can use the native `mdls` (meta-data list, credit to [Ask Dave Taylor](https://www.askdavetaylor.com/can-i-analyze-exif-information-on-the-mac-os-x-command-line/)) through a shell to get the data from HEIC. Note that calling a shell like this is not good programming, so use with care.
```py
import datetime
import subprocess
class DateNotFoundException(Exception):
pass
def get_photo_date_taken(filepath):
"""Gets the date taken for a photo through a shell."""
cmd = "mdls '%s'" % filepath
output = subprocess.check_output(cmd, shell = True)
lines = output.decode("ascii").split("\n")
for l in lines:
if "kMDItemContentCreationDate" in l:
datetime_str = l.split("= ")[1]
return datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S +0000")
raise DateNotFoundException("No EXIF date taken found for file %s" % filepath)
``` | While doing it with `mdls`, it's better (performance-wise) to give it a whole bunch of filenames separated by space at once.
I tested with 1000 files: works fine, 20 times performance gain. |
24,456,735 | I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this
```
void isPrime(int n)
{
int a=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
a++;
}
if(a==2)
{
printf("\n%d is prime",n);
}
else
{
printf("\n%d is not prime",n);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=2;i<=20;i++)
{
isPrime(i);
}
return 0;
}
```
The above code runs perfectly when I compile. I am a beginner in python and I have converted the same code into python, which looks like this.
```
def isPrime(n):
a=0
for x in range(1,n):
if n%x==0:
a=a+1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2,20):
isPrime(n)
```
But I get a wrong output in python. The output is somewhat weird which says
```
2 is not prime
3 is not prime
4 is prime
5 is not prime
6 is not prime
7 is not prime
8 is not prime
9 is prime
10 is not prime
11 is not prime
12 is not prime
13 is not prime
14 is not prime
15 is not prime
16 is not prime
17 is not prime
18 is not prime
19 is not prime
```
I have found out that the count of 'a' is 1 less than the actual count required. For example, in case of n=8, a should be 4. But its getting counted as 3.
What could be the reason? | 2014/06/27 | [
"https://Stackoverflow.com/questions/24456735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2947110/"
] | Why don't you add some `print` statements so you can see where the code fails? Adding some prints should be your first reflex when debugging.
```
def isPrime(n):
a=0
for x in range(1,n):
print('x,a', x,a)
if n%x==0:
print('incrementing a...')
a=a+1
print('a after loop:', a)
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
```
Output for `isPrime(2)`:
```
x,a 1 0
incrementing a...
a after loop: 1
2 is not prime
```
Output for `isPrime(7)`:
```
x,a 1 0
incrementing a...
x,a 2 1
x,a 3 1
x,a 4 1
x,a 5 1
x,a 6 1
a after loop: 1
7 is not prime
```
As you can see, `a` is never 2 because the `n%n` test is never executed, because with `x in range(1,n)`, the last value for `x` is `n-1`. However, if you change your `range` to `range(1,n+1)`, the test will be made:
```
x,a 1 0
incrementing a...
x,a 2 1
x,a 3 1
x,a 4 1
x,a 5 1
x,a 6 1
x,a 7 1
incrementing a...
a after loop: 2
7 is prime
``` | The issue you have is that the last value produced `range(start, stop)` is `stop-1`; see [the docs](https://docs.python.org/2/library/functions.html#range). Thus, `isPrime` should have the following `for` loop:
```
for x in range(1, n+1):
```
This will faithfully replicate the C code, and produce the correct output. (Note that this is also why you are only checking the numbers [2, 19] for whether they're prime, as opposed to [2, 20].) |
24,456,735 | I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this
```
void isPrime(int n)
{
int a=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
a++;
}
if(a==2)
{
printf("\n%d is prime",n);
}
else
{
printf("\n%d is not prime",n);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=2;i<=20;i++)
{
isPrime(i);
}
return 0;
}
```
The above code runs perfectly when I compile. I am a beginner in python and I have converted the same code into python, which looks like this.
```
def isPrime(n):
a=0
for x in range(1,n):
if n%x==0:
a=a+1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2,20):
isPrime(n)
```
But I get a wrong output in python. The output is somewhat weird which says
```
2 is not prime
3 is not prime
4 is prime
5 is not prime
6 is not prime
7 is not prime
8 is not prime
9 is prime
10 is not prime
11 is not prime
12 is not prime
13 is not prime
14 is not prime
15 is not prime
16 is not prime
17 is not prime
18 is not prime
19 is not prime
```
I have found out that the count of 'a' is 1 less than the actual count required. For example, in case of n=8, a should be 4. But its getting counted as 3.
What could be the reason? | 2014/06/27 | [
"https://Stackoverflow.com/questions/24456735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2947110/"
] | Why don't you add some `print` statements so you can see where the code fails? Adding some prints should be your first reflex when debugging.
```
def isPrime(n):
a=0
for x in range(1,n):
print('x,a', x,a)
if n%x==0:
print('incrementing a...')
a=a+1
print('a after loop:', a)
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
```
Output for `isPrime(2)`:
```
x,a 1 0
incrementing a...
a after loop: 1
2 is not prime
```
Output for `isPrime(7)`:
```
x,a 1 0
incrementing a...
x,a 2 1
x,a 3 1
x,a 4 1
x,a 5 1
x,a 6 1
a after loop: 1
7 is not prime
```
As you can see, `a` is never 2 because the `n%n` test is never executed, because with `x in range(1,n)`, the last value for `x` is `n-1`. However, if you change your `range` to `range(1,n+1)`, the test will be made:
```
x,a 1 0
incrementing a...
x,a 2 1
x,a 3 1
x,a 4 1
x,a 5 1
x,a 6 1
x,a 7 1
incrementing a...
a after loop: 2
7 is prime
``` | I think the problem was with your range as mentioned above. Can I give you some short tips to make your code more "Pythonic"? :)
Instead of
`if n%x==0`
you would simply write
`if not n%x`
and instead of
`a=a+1`
you could use the in-place operator, e.g.,
`a += 1`
Here, it wouldn't make much of a difference, but if you are working with mutable objects (due to the `__iadd__` method, I have more details [here](http://nbviewer.ipython.org/github/rasbt/One-Python-benchmark-per-day/blob/master/ipython_nbs/day14_inplace_operators.ipynb?create=1)) you would gain a significant performance increase, e.g.,
```
def slow(a):
for i in range(1000):
a = a + [1,2]
def fast(a):
for i in range(1000):
a += [1,2]
a = []
b = []
%timeit -r 3 -n 1000 slow(a)
%timeit -r 3 -n 1000 fast(b)
```
```
1000 loops, best of 3: 2.94 ms per loop
1000 loops, best of 3: 181 µs per loop
```
Same for the binary operator instead of the `format()` method, however, I like the latter one better (due to its more powerful minilanguange and I would recommend it if you don't care about speed in certain computations)
```
%timeit -r 3 -n 1000 '{} World'.format('Hello')
%timeit -r 3 -n 1000 '%s World' %('Hello')
1000 loops, best of 3: 472 ns per loop
1000 loops, best of 3: 27.3 ns per loop
```
```
def isPrime(n):
a = 0
for x in range(1, n+1):
if not n%x:
a += 1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2, 20):
isPrime(n)
``` |
24,456,735 | I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this
```
void isPrime(int n)
{
int a=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
a++;
}
if(a==2)
{
printf("\n%d is prime",n);
}
else
{
printf("\n%d is not prime",n);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=2;i<=20;i++)
{
isPrime(i);
}
return 0;
}
```
The above code runs perfectly when I compile. I am a beginner in python and I have converted the same code into python, which looks like this.
```
def isPrime(n):
a=0
for x in range(1,n):
if n%x==0:
a=a+1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2,20):
isPrime(n)
```
But I get a wrong output in python. The output is somewhat weird which says
```
2 is not prime
3 is not prime
4 is prime
5 is not prime
6 is not prime
7 is not prime
8 is not prime
9 is prime
10 is not prime
11 is not prime
12 is not prime
13 is not prime
14 is not prime
15 is not prime
16 is not prime
17 is not prime
18 is not prime
19 is not prime
```
I have found out that the count of 'a' is 1 less than the actual count required. For example, in case of n=8, a should be 4. But its getting counted as 3.
What could be the reason? | 2014/06/27 | [
"https://Stackoverflow.com/questions/24456735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2947110/"
] | The issue you have is that the last value produced `range(start, stop)` is `stop-1`; see [the docs](https://docs.python.org/2/library/functions.html#range). Thus, `isPrime` should have the following `for` loop:
```
for x in range(1, n+1):
```
This will faithfully replicate the C code, and produce the correct output. (Note that this is also why you are only checking the numbers [2, 19] for whether they're prime, as opposed to [2, 20].) | I think the problem was with your range as mentioned above. Can I give you some short tips to make your code more "Pythonic"? :)
Instead of
`if n%x==0`
you would simply write
`if not n%x`
and instead of
`a=a+1`
you could use the in-place operator, e.g.,
`a += 1`
Here, it wouldn't make much of a difference, but if you are working with mutable objects (due to the `__iadd__` method, I have more details [here](http://nbviewer.ipython.org/github/rasbt/One-Python-benchmark-per-day/blob/master/ipython_nbs/day14_inplace_operators.ipynb?create=1)) you would gain a significant performance increase, e.g.,
```
def slow(a):
for i in range(1000):
a = a + [1,2]
def fast(a):
for i in range(1000):
a += [1,2]
a = []
b = []
%timeit -r 3 -n 1000 slow(a)
%timeit -r 3 -n 1000 fast(b)
```
```
1000 loops, best of 3: 2.94 ms per loop
1000 loops, best of 3: 181 µs per loop
```
Same for the binary operator instead of the `format()` method, however, I like the latter one better (due to its more powerful minilanguange and I would recommend it if you don't care about speed in certain computations)
```
%timeit -r 3 -n 1000 '{} World'.format('Hello')
%timeit -r 3 -n 1000 '%s World' %('Hello')
1000 loops, best of 3: 472 ns per loop
1000 loops, best of 3: 27.3 ns per loop
```
```
def isPrime(n):
a = 0
for x in range(1, n+1):
if not n%x:
a += 1
if a==2:
print("{} is prime".format(n))
else:
print("{} is not prime".format(n))
for n in range(2, 20):
isPrime(n)
``` |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help | Sorry. I'm not able to try this as I'm not in a PC.
Have you tried:
```
os.listdir("\\\\remotehost\\")
``` |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help | Maybe the following script will help you. See <http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b> |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help | I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation:
<http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories>
In case anybody else happens along this problem, like I did. |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help | For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module:
```
import win32net
shares, _, _ = win32net.NetShareEnum('remotehost',0)
```
The integer controls the type of information returned but if you just want a list of the shares then 0 will do.
This works where os.listdir('\\remotehost') fails as '\\remotehost' isn't a real folder although windows can display it like one. |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | Maybe the following script will help you. See <http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b> | Sorry. I'm not able to try this as I'm not in a PC.
Have you tried:
```
os.listdir("\\\\remotehost\\")
``` |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation:
<http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories>
In case anybody else happens along this problem, like I did. | Sorry. I'm not able to try this as I'm not in a PC.
Have you tried:
```
os.listdir("\\\\remotehost\\")
``` |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module:
```
import win32net
shares, _, _ = win32net.NetShareEnum('remotehost',0)
```
The integer controls the type of information returned but if you just want a list of the shares then 0 will do.
This works where os.listdir('\\remotehost') fails as '\\remotehost' isn't a real folder although windows can display it like one. | Sorry. I'm not able to try this as I'm not in a PC.
Have you tried:
```
os.listdir("\\\\remotehost\\")
``` |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module:
```
import win32net
shares, _, _ = win32net.NetShareEnum('remotehost',0)
```
The integer controls the type of information returned but if you just want a list of the shares then 0 will do.
This works where os.listdir('\\remotehost') fails as '\\remotehost' isn't a real folder although windows can display it like one. | Maybe the following script will help you. See <http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b> |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remote host, python fails, an example of which is shown in the following code snippet:
```
os.listdir("\\\\remotehost")
```
Is anyone aware of why this doesn't work?, any help/workaround is appreciated. | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | For anyone still wondering how to list network shares at the top level on windows, you can use the win32net module:
```
import win32net
shares, _, _ = win32net.NetShareEnum('remotehost',0)
```
The integer controls the type of information returned but if you just want a list of the shares then 0 will do.
This works where os.listdir('\\remotehost') fails as '\\remotehost' isn't a real folder although windows can display it like one. | I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation:
<http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories>
In case anybody else happens along this problem, like I did. |
73,279,102 | I have the following sentence:
```
text="The weather is extremely severe in England"
```
I want to perform a custom `Name Entity Recognition (NER)` procedure
First a normal `NER` procedure will output `England` with a `GPE` label
```
pip install spacy
!python -m spacy download en_core_web_lg
import spacy
nlp = spacy.load('en_core_web_lg')
doc = nlp(text)
for ent in doc.ents:
print(ent.text+' - '+ent.label_+' - '+str(spacy.explain(ent.label_)))
Result: England - GPE - Countries, cities, states
```
However, I want the whole sentence to take the tag `High-Severity`.
So I am doing the following procedure:
```
from spacy.strings import StringStore
new_hash = StringStore([u'High_Severity']) # <-- match id
nlp.vocab.strings.add('High_Severity')
from spacy.tokens import Span
# Get the hash value of the ORG entity label
High_Severity = doc.vocab.strings[u'High_Severity']
# Create a Span for the new entity
new_ent = Span(doc, 0, 7, label=High_Severity)
# Add the entity to the existing Doc object
doc.ents = list(doc.ents) + [new_ent]
```
I am taking the following error:
```
ValueError: [E1010] Unable to set entity information for token 6 which is included in more than one span in entities, blocked, missing or outside.
```
From my understanding, this is happening because `NER` has already recognised `England` as `GRE` and cannot add a label over the existing label.
I tried to execute the custom `NER` code (i.e, without first running the normal `NER` code) but this did not solve my problem.
Any ideas on how to Solve this problem? | 2022/08/08 | [
"https://Stackoverflow.com/questions/73279102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17465901/"
] | Indeed it looks like NER do not allow overlapping, and that is your problem, your second part of the code tries to create a ner containing another ner, hence, it fails.
see in:
<https://github.com/explosion/spaCy/discussions/10885>
and therefore spacy has spans categorization.
I did not find yet the way to characterized a predefined span (not coming from a trained model) | Why do you need the new hash in the string store? Due to the underscore? Thx |
2,407,872 | I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more or less) thing.
Let's have an look at an arbitrary exemplary UI widget that makes up a tiny part of the application: The widget may be a part of a window and the window may be a part of a window manager:
1. The eventhandlers use DOM elements as parameters. The DOM element represents a widget in the browser.
2. A lot of times I use jQuery objects (Basically wrappers around DOM elements) to do something with the widget. Sometimes they are used transiently, sometimes they are stored in a variable for later purposes.
3. The AJAX function calls use string identifiers for these widgets. They are processed server side.
4. Beside that I have a widget class whose instances represent a widget. It is instantiated through the new operator.
Now I have somehow four different object identifiers for the same thing, which needs to be kept in sync until the page is loaded anew. This seems not to be a good thing.
### Any advice?
**EDIT:**
\*@Will Morgan\*: It's a form designer that allows to create web forms within the browser. The backend is Zope, a python web application server. It's difficult to get more explicit as this is a general problem I observe all the time when doing Javascript development with the trio jQuery, DOM tree and my own prototyped class instances.
**EDIT2:**
I think it would helpful to make an example, albeit an artificial one. Below you see a logger widget that can be used to add a block element to a web page in which logged items are displayed.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
return {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
};
// Usage
var logger = makeLogger();
var foo = document.getElementById('foo');
foo.appendChild(logger.getRootEl());
logger.log('What\'s up?');
```
At this point I have a wrapper around the HTMLDivElement (the hosted object). With having the logger instance (the native object) at hand I can easily work with it through the function *logger.getRootEl()*.
Where I get stuck is when I only have the DOM element at hand and need to do something with the public API returned by function *makeLogger* (e.g. in event handlers). And this is where the mess starts. I need to hold all the native objects in a repository or something so that I can retrieve again. It would be so much nicer to have a connection (e.g. a object property) from the hosted object back to my native object.
I know it can be done, but it has some drawbacks:
* These kind of (circular) references are potentially memory leaking up to IE7
* When to pass the *hosted object* and when to pass the *native object* (in functions)?
For now, I do the back referencing with jQuery's data() method. But all in all I don't like the way I have to keep track of the relation between the hosted object and its native counterpart.
### How do you handle this scenario?
**EDIT3:**
After some insight I've gained from Anurag's example..
\*@Anurag:\* If I've understood your example right, the critical point is to set up the correct (what's correct depends on your needs, though) ***execution context*** for the event handlers. And this is in your case the presentation object instance, which is done with Mootool's bind() function. So you ensure that you're \*ALWAYS\* dealing with the wrapper object (I've called it the native object) instead of the DOM object, right?
***A note for the reader:*** You're not forced to use Mootools to achieve this. In jQuery, you would setup your event handlers with the \*$.proxy()\* function, or if you're using plain old Javascript, you would utilize the \*apply\* property that every function exposes. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2407872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49628/"
] | You could use a global registry:
```
window.WidgetRegistry = {};
window.WidgetRegistry['foowidget'] = new Widget('#myID');
```
and when AJAX calls return, they can get the widget like this:
```
var widgetID = data.widgetID;
if (widgetID in window.WidgetRegistry) {
var widget = window.WidgetRegistry[widgetID];
}
```
For your jQuery calls: I'd guess they are relatively inexpensive, since jQuery caches objects for later use. But you could extend the above suggested `WidgetRegistry` by using [`.data()`](http://api.jquery.com/data/):
```
var $widget = $('#myWidget');
var widgetID = 'foo';
$widget.data('widget', widgetID);
```
In this way, you can store the widget ID attached to each jQuery object and re-access it from the global registry.
Testing, if an jQuery object has an existing widget:
```
return $('#test').data('widget') &&
($('#test').data('widget') in window.WidgetRegistry);
```
Note, that these are just suggestions. Actually, there are dozens of ways to achieve a consolidation like this. If you want to combine your code deeper with jQuery, you could [extend the jQuery object](http://docs.jquery.com/Plugins/Authoring), so that you could write something like:
```
$('#widget').widget({'foo':'bar'});
// and/or
var allWidgets = $('*:widget');
// ...
``` | I'm not sure I've fully understood your question, but I'll try to point some ideas.
In my opinion, you should make base widget class, which contains common functionality for widgets.
Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and function as values. That way each class defines the events for this widget, and you can easily bind them in the constructor. As for the string identifiers, the easiest way is to use toString().
Example:
```
namespace('AppName.Widgets'); // you can find implementations easy
AppName.Widgets.base = function() {
if (!this._type) return;
this._dom = $('div.widget.'+this._type);
for (var e in this._events) {
this._dom.bind(e, this._events[e]);
}
this.toString = function() { return this._type; };
}
AppName.Widgets.example = function() { // extends AppName.Widgets.base
this._type = 'example';
this._events = { 'click' : function(e) { alert('click'); } };
AppName.Widgets.base.call(this);
}
``` |
2,407,872 | I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more or less) thing.
Let's have an look at an arbitrary exemplary UI widget that makes up a tiny part of the application: The widget may be a part of a window and the window may be a part of a window manager:
1. The eventhandlers use DOM elements as parameters. The DOM element represents a widget in the browser.
2. A lot of times I use jQuery objects (Basically wrappers around DOM elements) to do something with the widget. Sometimes they are used transiently, sometimes they are stored in a variable for later purposes.
3. The AJAX function calls use string identifiers for these widgets. They are processed server side.
4. Beside that I have a widget class whose instances represent a widget. It is instantiated through the new operator.
Now I have somehow four different object identifiers for the same thing, which needs to be kept in sync until the page is loaded anew. This seems not to be a good thing.
### Any advice?
**EDIT:**
\*@Will Morgan\*: It's a form designer that allows to create web forms within the browser. The backend is Zope, a python web application server. It's difficult to get more explicit as this is a general problem I observe all the time when doing Javascript development with the trio jQuery, DOM tree and my own prototyped class instances.
**EDIT2:**
I think it would helpful to make an example, albeit an artificial one. Below you see a logger widget that can be used to add a block element to a web page in which logged items are displayed.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
return {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
};
// Usage
var logger = makeLogger();
var foo = document.getElementById('foo');
foo.appendChild(logger.getRootEl());
logger.log('What\'s up?');
```
At this point I have a wrapper around the HTMLDivElement (the hosted object). With having the logger instance (the native object) at hand I can easily work with it through the function *logger.getRootEl()*.
Where I get stuck is when I only have the DOM element at hand and need to do something with the public API returned by function *makeLogger* (e.g. in event handlers). And this is where the mess starts. I need to hold all the native objects in a repository or something so that I can retrieve again. It would be so much nicer to have a connection (e.g. a object property) from the hosted object back to my native object.
I know it can be done, but it has some drawbacks:
* These kind of (circular) references are potentially memory leaking up to IE7
* When to pass the *hosted object* and when to pass the *native object* (in functions)?
For now, I do the back referencing with jQuery's data() method. But all in all I don't like the way I have to keep track of the relation between the hosted object and its native counterpart.
### How do you handle this scenario?
**EDIT3:**
After some insight I've gained from Anurag's example..
\*@Anurag:\* If I've understood your example right, the critical point is to set up the correct (what's correct depends on your needs, though) ***execution context*** for the event handlers. And this is in your case the presentation object instance, which is done with Mootool's bind() function. So you ensure that you're \*ALWAYS\* dealing with the wrapper object (I've called it the native object) instead of the DOM object, right?
***A note for the reader:*** You're not forced to use Mootools to achieve this. In jQuery, you would setup your event handlers with the \*$.proxy()\* function, or if you're using plain old Javascript, you would utilize the \*apply\* property that every function exposes. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2407872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49628/"
] | You could use a global registry:
```
window.WidgetRegistry = {};
window.WidgetRegistry['foowidget'] = new Widget('#myID');
```
and when AJAX calls return, they can get the widget like this:
```
var widgetID = data.widgetID;
if (widgetID in window.WidgetRegistry) {
var widget = window.WidgetRegistry[widgetID];
}
```
For your jQuery calls: I'd guess they are relatively inexpensive, since jQuery caches objects for later use. But you could extend the above suggested `WidgetRegistry` by using [`.data()`](http://api.jquery.com/data/):
```
var $widget = $('#myWidget');
var widgetID = 'foo';
$widget.data('widget', widgetID);
```
In this way, you can store the widget ID attached to each jQuery object and re-access it from the global registry.
Testing, if an jQuery object has an existing widget:
```
return $('#test').data('widget') &&
($('#test').data('widget') in window.WidgetRegistry);
```
Note, that these are just suggestions. Actually, there are dozens of ways to achieve a consolidation like this. If you want to combine your code deeper with jQuery, you could [extend the jQuery object](http://docs.jquery.com/Plugins/Authoring), so that you could write something like:
```
$('#widget').widget({'foo':'bar'});
// and/or
var allWidgets = $('*:widget');
// ...
``` | A lot of what you can or can't do will depend on how much control you have over the javascript. Personally I often have to use libraries built by others so I might only get a DOM node to work with, but I really need my object instead. In these cases I find using the data feature in jQuery is very handy. By using the data feature, you can 'store' your object inside the DOM node to retrieve it later.
Given your example above, here's how you could use the data feature to get back your widget after having functions that only use the DOM node.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
var self = {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
// Save a copy to the domNode
$(rootEl).data("logger", self);
return self;
};
// Example of only getting the dom node
function whatsUp (domNode){
// Get the logger from the domNode
$(domNode).data('logger').log('What\'s up?');
}
// Usage
var logger = makeLogger();
var loggerNode = logger.getRootEl();
var foo = document.getElementById('foo');
foo.appendChild(loggerNode);
whatsUp(loggerNode);
``` |
2,407,872 | I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more or less) thing.
Let's have an look at an arbitrary exemplary UI widget that makes up a tiny part of the application: The widget may be a part of a window and the window may be a part of a window manager:
1. The eventhandlers use DOM elements as parameters. The DOM element represents a widget in the browser.
2. A lot of times I use jQuery objects (Basically wrappers around DOM elements) to do something with the widget. Sometimes they are used transiently, sometimes they are stored in a variable for later purposes.
3. The AJAX function calls use string identifiers for these widgets. They are processed server side.
4. Beside that I have a widget class whose instances represent a widget. It is instantiated through the new operator.
Now I have somehow four different object identifiers for the same thing, which needs to be kept in sync until the page is loaded anew. This seems not to be a good thing.
### Any advice?
**EDIT:**
\*@Will Morgan\*: It's a form designer that allows to create web forms within the browser. The backend is Zope, a python web application server. It's difficult to get more explicit as this is a general problem I observe all the time when doing Javascript development with the trio jQuery, DOM tree and my own prototyped class instances.
**EDIT2:**
I think it would helpful to make an example, albeit an artificial one. Below you see a logger widget that can be used to add a block element to a web page in which logged items are displayed.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
return {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
};
// Usage
var logger = makeLogger();
var foo = document.getElementById('foo');
foo.appendChild(logger.getRootEl());
logger.log('What\'s up?');
```
At this point I have a wrapper around the HTMLDivElement (the hosted object). With having the logger instance (the native object) at hand I can easily work with it through the function *logger.getRootEl()*.
Where I get stuck is when I only have the DOM element at hand and need to do something with the public API returned by function *makeLogger* (e.g. in event handlers). And this is where the mess starts. I need to hold all the native objects in a repository or something so that I can retrieve again. It would be so much nicer to have a connection (e.g. a object property) from the hosted object back to my native object.
I know it can be done, but it has some drawbacks:
* These kind of (circular) references are potentially memory leaking up to IE7
* When to pass the *hosted object* and when to pass the *native object* (in functions)?
For now, I do the back referencing with jQuery's data() method. But all in all I don't like the way I have to keep track of the relation between the hosted object and its native counterpart.
### How do you handle this scenario?
**EDIT3:**
After some insight I've gained from Anurag's example..
\*@Anurag:\* If I've understood your example right, the critical point is to set up the correct (what's correct depends on your needs, though) ***execution context*** for the event handlers. And this is in your case the presentation object instance, which is done with Mootool's bind() function. So you ensure that you're \*ALWAYS\* dealing with the wrapper object (I've called it the native object) instead of the DOM object, right?
***A note for the reader:*** You're not forced to use Mootools to achieve this. In jQuery, you would setup your event handlers with the \*$.proxy()\* function, or if you're using plain old Javascript, you would utilize the \*apply\* property that every function exposes. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2407872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49628/"
] | For the four objects that need to be synchronized, you could have a single object and pass the reference around in a constructor, or as function arguments.
The way I fix this problem is to never lose a reference to the wrapper object. Whenever a DOM object is needed (for example inserting into the page), this wrapper object provides it. But sticking that widget onto the screen, the wrapper object sets up all event handling and AJAX handling code specific to the widget, so the reference the the wrapper is maintained at all times in these event handlers and AJAX callbacks.
I've created a [simple example](http://jsfiddle.net/YHcTv/5/) on jsfiddle using MooTools that might make sense to you. | I'm not sure I've fully understood your question, but I'll try to point some ideas.
In my opinion, you should make base widget class, which contains common functionality for widgets.
Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and function as values. That way each class defines the events for this widget, and you can easily bind them in the constructor. As for the string identifiers, the easiest way is to use toString().
Example:
```
namespace('AppName.Widgets'); // you can find implementations easy
AppName.Widgets.base = function() {
if (!this._type) return;
this._dom = $('div.widget.'+this._type);
for (var e in this._events) {
this._dom.bind(e, this._events[e]);
}
this.toString = function() { return this._type; };
}
AppName.Widgets.example = function() { // extends AppName.Widgets.base
this._type = 'example';
this._events = { 'click' : function(e) { alert('click'); } };
AppName.Widgets.base.call(this);
}
``` |
2,407,872 | I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more or less) thing.
Let's have an look at an arbitrary exemplary UI widget that makes up a tiny part of the application: The widget may be a part of a window and the window may be a part of a window manager:
1. The eventhandlers use DOM elements as parameters. The DOM element represents a widget in the browser.
2. A lot of times I use jQuery objects (Basically wrappers around DOM elements) to do something with the widget. Sometimes they are used transiently, sometimes they are stored in a variable for later purposes.
3. The AJAX function calls use string identifiers for these widgets. They are processed server side.
4. Beside that I have a widget class whose instances represent a widget. It is instantiated through the new operator.
Now I have somehow four different object identifiers for the same thing, which needs to be kept in sync until the page is loaded anew. This seems not to be a good thing.
### Any advice?
**EDIT:**
\*@Will Morgan\*: It's a form designer that allows to create web forms within the browser. The backend is Zope, a python web application server. It's difficult to get more explicit as this is a general problem I observe all the time when doing Javascript development with the trio jQuery, DOM tree and my own prototyped class instances.
**EDIT2:**
I think it would helpful to make an example, albeit an artificial one. Below you see a logger widget that can be used to add a block element to a web page in which logged items are displayed.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
return {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
};
// Usage
var logger = makeLogger();
var foo = document.getElementById('foo');
foo.appendChild(logger.getRootEl());
logger.log('What\'s up?');
```
At this point I have a wrapper around the HTMLDivElement (the hosted object). With having the logger instance (the native object) at hand I can easily work with it through the function *logger.getRootEl()*.
Where I get stuck is when I only have the DOM element at hand and need to do something with the public API returned by function *makeLogger* (e.g. in event handlers). And this is where the mess starts. I need to hold all the native objects in a repository or something so that I can retrieve again. It would be so much nicer to have a connection (e.g. a object property) from the hosted object back to my native object.
I know it can be done, but it has some drawbacks:
* These kind of (circular) references are potentially memory leaking up to IE7
* When to pass the *hosted object* and when to pass the *native object* (in functions)?
For now, I do the back referencing with jQuery's data() method. But all in all I don't like the way I have to keep track of the relation between the hosted object and its native counterpart.
### How do you handle this scenario?
**EDIT3:**
After some insight I've gained from Anurag's example..
\*@Anurag:\* If I've understood your example right, the critical point is to set up the correct (what's correct depends on your needs, though) ***execution context*** for the event handlers. And this is in your case the presentation object instance, which is done with Mootool's bind() function. So you ensure that you're \*ALWAYS\* dealing with the wrapper object (I've called it the native object) instead of the DOM object, right?
***A note for the reader:*** You're not forced to use Mootools to achieve this. In jQuery, you would setup your event handlers with the \*$.proxy()\* function, or if you're using plain old Javascript, you would utilize the \*apply\* property that every function exposes. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2407872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49628/"
] | I'm not sure I've fully understood your question, but I'll try to point some ideas.
In my opinion, you should make base widget class, which contains common functionality for widgets.
Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and function as values. That way each class defines the events for this widget, and you can easily bind them in the constructor. As for the string identifiers, the easiest way is to use toString().
Example:
```
namespace('AppName.Widgets'); // you can find implementations easy
AppName.Widgets.base = function() {
if (!this._type) return;
this._dom = $('div.widget.'+this._type);
for (var e in this._events) {
this._dom.bind(e, this._events[e]);
}
this.toString = function() { return this._type; };
}
AppName.Widgets.example = function() { // extends AppName.Widgets.base
this._type = 'example';
this._events = { 'click' : function(e) { alert('click'); } };
AppName.Widgets.base.call(this);
}
``` | A lot of what you can or can't do will depend on how much control you have over the javascript. Personally I often have to use libraries built by others so I might only get a DOM node to work with, but I really need my object instead. In these cases I find using the data feature in jQuery is very handy. By using the data feature, you can 'store' your object inside the DOM node to retrieve it later.
Given your example above, here's how you could use the data feature to get back your widget after having functions that only use the DOM node.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
var self = {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
// Save a copy to the domNode
$(rootEl).data("logger", self);
return self;
};
// Example of only getting the dom node
function whatsUp (domNode){
// Get the logger from the domNode
$(domNode).data('logger').log('What\'s up?');
}
// Usage
var logger = makeLogger();
var loggerNode = logger.getRootEl();
var foo = document.getElementById('foo');
foo.appendChild(loggerNode);
whatsUp(loggerNode);
``` |
2,407,872 | I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more or less) thing.
Let's have an look at an arbitrary exemplary UI widget that makes up a tiny part of the application: The widget may be a part of a window and the window may be a part of a window manager:
1. The eventhandlers use DOM elements as parameters. The DOM element represents a widget in the browser.
2. A lot of times I use jQuery objects (Basically wrappers around DOM elements) to do something with the widget. Sometimes they are used transiently, sometimes they are stored in a variable for later purposes.
3. The AJAX function calls use string identifiers for these widgets. They are processed server side.
4. Beside that I have a widget class whose instances represent a widget. It is instantiated through the new operator.
Now I have somehow four different object identifiers for the same thing, which needs to be kept in sync until the page is loaded anew. This seems not to be a good thing.
### Any advice?
**EDIT:**
\*@Will Morgan\*: It's a form designer that allows to create web forms within the browser. The backend is Zope, a python web application server. It's difficult to get more explicit as this is a general problem I observe all the time when doing Javascript development with the trio jQuery, DOM tree and my own prototyped class instances.
**EDIT2:**
I think it would helpful to make an example, albeit an artificial one. Below you see a logger widget that can be used to add a block element to a web page in which logged items are displayed.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
return {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
};
// Usage
var logger = makeLogger();
var foo = document.getElementById('foo');
foo.appendChild(logger.getRootEl());
logger.log('What\'s up?');
```
At this point I have a wrapper around the HTMLDivElement (the hosted object). With having the logger instance (the native object) at hand I can easily work with it through the function *logger.getRootEl()*.
Where I get stuck is when I only have the DOM element at hand and need to do something with the public API returned by function *makeLogger* (e.g. in event handlers). And this is where the mess starts. I need to hold all the native objects in a repository or something so that I can retrieve again. It would be so much nicer to have a connection (e.g. a object property) from the hosted object back to my native object.
I know it can be done, but it has some drawbacks:
* These kind of (circular) references are potentially memory leaking up to IE7
* When to pass the *hosted object* and when to pass the *native object* (in functions)?
For now, I do the back referencing with jQuery's data() method. But all in all I don't like the way I have to keep track of the relation between the hosted object and its native counterpart.
### How do you handle this scenario?
**EDIT3:**
After some insight I've gained from Anurag's example..
\*@Anurag:\* If I've understood your example right, the critical point is to set up the correct (what's correct depends on your needs, though) ***execution context*** for the event handlers. And this is in your case the presentation object instance, which is done with Mootool's bind() function. So you ensure that you're \*ALWAYS\* dealing with the wrapper object (I've called it the native object) instead of the DOM object, right?
***A note for the reader:*** You're not forced to use Mootools to achieve this. In jQuery, you would setup your event handlers with the \*$.proxy()\* function, or if you're using plain old Javascript, you would utilize the \*apply\* property that every function exposes. | 2010/03/09 | [
"https://Stackoverflow.com/questions/2407872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49628/"
] | For the four objects that need to be synchronized, you could have a single object and pass the reference around in a constructor, or as function arguments.
The way I fix this problem is to never lose a reference to the wrapper object. Whenever a DOM object is needed (for example inserting into the page), this wrapper object provides it. But sticking that widget onto the screen, the wrapper object sets up all event handling and AJAX handling code specific to the widget, so the reference the the wrapper is maintained at all times in these event handlers and AJAX callbacks.
I've created a [simple example](http://jsfiddle.net/YHcTv/5/) on jsfiddle using MooTools that might make sense to you. | A lot of what you can or can't do will depend on how much control you have over the javascript. Personally I often have to use libraries built by others so I might only get a DOM node to work with, but I really need my object instead. In these cases I find using the data feature in jQuery is very handy. By using the data feature, you can 'store' your object inside the DOM node to retrieve it later.
Given your example above, here's how you could use the data feature to get back your widget after having functions that only use the DOM node.
```
makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
var self = {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
// Save a copy to the domNode
$(rootEl).data("logger", self);
return self;
};
// Example of only getting the dom node
function whatsUp (domNode){
// Get the logger from the domNode
$(domNode).data('logger').log('What\'s up?');
}
// Usage
var logger = makeLogger();
var loggerNode = logger.getRootEl();
var foo = document.getElementById('foo');
foo.appendChild(loggerNode);
whatsUp(loggerNode);
``` |
38,302,028 | Using pip from a (python 3.5) script, how can i upgrade a package i previously installed via the command line (using `pip install`)?
Something like
```
import pip
pip.install("mysuperawesomepackage", upgrade=True)
``` | 2016/07/11 | [
"https://Stackoverflow.com/questions/38302028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113623/"
] | I think you should link in either 2 stylesheets, one for portrait and one for landscape OR define your styles with media queries using orientation
In the following example i have included both, but either will do.
e.g.
```html
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="all and (orientation:portrait)"src="portrait.css">
<!---portrait css contains @charset "utf-8";
img{width:400px;}--->
<link rel="stylesheet" media="all and (orientation:landscape)" src="landscape.css">
<!---landscape.css contains @charset "utf-8";
img{width:600px;}---->
<title>Simple orientation trial (view on device)</title>
<style>
img{max-width:400px;}
@media all and (orientation:portrait) {
img{max-width:400px;}
}
@media all and (orientation:landscape) {
img{max-width:600px;}
}
</style>
</head>
<img src="http://www.rachelgallen.com/images/daisies.jpg">
<body>
</body>
</html>
``` | Try to give every thing in percentage in some exceptional cases like font size etc you can use EM or PX. |
57,596,488 | I am trying to access JSON using urllib.request.urlopen. It works fine when I use urllib2 in python2, but not urllib.request.urlopen.
```
URL = 'https://api.exchangeratesapi.io/latest'
f = urllib.request.urlopen(URL)
```
```
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1316, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1229, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1275, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1224, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1016, in _send_output
self.send(msg)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 956, in send
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1391, in connect
server_hostname=server_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 415, in wrap_socket
_session=session
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 826, in __init__
self.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 1080, in do_handshake
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 701, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:864)
```
During handling of the above exception, another exception occurred:
```
Traceback (most recent call last):
File "a1.py", line 19, in <module>
print(getLatestRates())
File "a1.py", line 15, in getLatestRates
f = urllib.request.urlopen(URL)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 525, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 543, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 503, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1359, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1318, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:864)>
``` | 2019/08/21 | [
"https://Stackoverflow.com/questions/57596488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11958437/"
] | This is what I used and it worked:
```
from urllib.request import urlopen
URL = 'https://api.exchangeratesapi.io/latest'
f = urlopen(URL)
```
I hope this works for you! | you can try to disable the ssl verification
```
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
``` |
57,596,488 | I am trying to access JSON using urllib.request.urlopen. It works fine when I use urllib2 in python2, but not urllib.request.urlopen.
```
URL = 'https://api.exchangeratesapi.io/latest'
f = urllib.request.urlopen(URL)
```
```
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1316, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1229, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1275, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1224, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1016, in _send_output
self.send(msg)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 956, in send
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1391, in connect
server_hostname=server_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 415, in wrap_socket
_session=session
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 826, in __init__
self.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 1080, in do_handshake
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 701, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:864)
```
During handling of the above exception, another exception occurred:
```
Traceback (most recent call last):
File "a1.py", line 19, in <module>
print(getLatestRates())
File "a1.py", line 15, in getLatestRates
f = urllib.request.urlopen(URL)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 525, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 543, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 503, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1359, in https_open
context=self._context, check_hostname=self._check_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py", line 1318, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:864)>
``` | 2019/08/21 | [
"https://Stackoverflow.com/questions/57596488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11958437/"
] | This is what I used and it worked:
```
from urllib.request import urlopen
URL = 'https://api.exchangeratesapi.io/latest'
f = urlopen(URL)
```
I hope this works for you! | In my case there was an issue with error in *request.py*:
**\_load\_windows\_store\_certs** caused *MemoryError*
Fixed by updating python from version **3.7.4** to **3.8.1**
Hope this help |
54,685,134 | I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning.
```
vgg16_model = VGG16()
```
why this warning happens and how can I resolve this?
```
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
``` | 2019/02/14 | [
"https://Stackoverflow.com/questions/54685134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10594993/"
] | It looks like there's an open git issue to clean this up in the keras code:
<https://github.com/tensorflow/minigo/issues/740>
You should be safe to ignore the warning, I don't believe you can change it without modifying the TF repo. You can disable warnings as [mentioned here](https://stackoverflow.com/questions/48608776/how-to-suppress-tensorflow-warning-displayed-in-result):
```
tf.logging.set_verbosity(tf.logging.ERROR)
``` | So , the method `colocate_with` is a context manager to make sure that the operation or tensor you're about to create will be placed on the same device the reference operation is on. But, your warning says that it will be deprecated and that this will from now on be handled automatically. From the next version of tensorflow, this method will be removed so you will either have to update your code now (which will run currently) or later (when you update the version of tensorflow to the next one, this code will no longer be runnable because that method will be removed) |
54,685,134 | I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning.
```
vgg16_model = VGG16()
```
why this warning happens and how can I resolve this?
```
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
``` | 2019/02/14 | [
"https://Stackoverflow.com/questions/54685134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10594993/"
] | You can use the function below to avoid these warnings. First, you must make the appropriate imports:
```
import os
os.environ['KERAS_BACKEND']='tensorflow'
import tensorflow as tf
def tf_no_warning():
"""
Make Tensorflow less verbose
"""
try:
tf.logging.set_verbosity(tf.logging.ERROR)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
except ImportError:
pass
```
And then call the above function at the beginning of the code.
```
tf_no_warning()
``` | So , the method `colocate_with` is a context manager to make sure that the operation or tensor you're about to create will be placed on the same device the reference operation is on. But, your warning says that it will be deprecated and that this will from now on be handled automatically. From the next version of tensorflow, this method will be removed so you will either have to update your code now (which will run currently) or later (when you update the version of tensorflow to the next one, this code will no longer be runnable because that method will be removed) |
54,685,134 | I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning.
```
vgg16_model = VGG16()
```
why this warning happens and how can I resolve this?
```
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
``` | 2019/02/14 | [
"https://Stackoverflow.com/questions/54685134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10594993/"
] | It looks like there's an open git issue to clean this up in the keras code:
<https://github.com/tensorflow/minigo/issues/740>
You should be safe to ignore the warning, I don't believe you can change it without modifying the TF repo. You can disable warnings as [mentioned here](https://stackoverflow.com/questions/48608776/how-to-suppress-tensorflow-warning-displayed-in-result):
```
tf.logging.set_verbosity(tf.logging.ERROR)
``` | You can use the function below to avoid these warnings. First, you must make the appropriate imports:
```
import os
os.environ['KERAS_BACKEND']='tensorflow'
import tensorflow as tf
def tf_no_warning():
"""
Make Tensorflow less verbose
"""
try:
tf.logging.set_verbosity(tf.logging.ERROR)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
except ImportError:
pass
```
And then call the above function at the beginning of the code.
```
tf_no_warning()
``` |
39,693,115 | I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:
```
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
```
I need to extract the hours from each line (in this case 09) and then find the most common hours the emails were sent.
Basically, what I need to do is build a for loop that splits each text by colon
```
split(':')
```
and then splits by space:
```
split()
```
I've tried for hours, but can't seem to figure it out. What my code looks like so far:
```
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()
temp = list()
for line in handle:
if not "From " in line: continue
words = line.split(':')
for word in words:
counts[word] = counts.get(word,0) + 1
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse = True)
for val, key in lst:
print key, val
```
The code above only does 1 split, but I've kept trying multiple methods to split the text again. I keep getting a list attribute error, saying "list object has no attribute split". Would appreciate any help on this. Thanks again | 2016/09/26 | [
"https://Stackoverflow.com/questions/39693115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6879638/"
] | Ok, first off, you should probably use a `with` `as` statement, it just simplifies things and makes sure you don't mess up. So
`fh = open('poem.txt', 'r')`
becomes
`with open('poem.txt','r') as file:`
and since you're just concerned with words, you might as well use a built-in from the start:
```
words = file.read().split()
```
Then you just set a counter of the max word length (initialized to 0), and an empty list. If the word has broken the max length, set a new maxlength and rewrite the list to include only that word. If it's equal to the maxlength, include it in the list. Then just print out the list members. If you want to include some checks like `.isalpha()` feel free to put it in the relevant portions of the code.
```
maxlength = 0
longestlist = []
for word in words:
if len(word) > maxlength:
maxlength = len(word)
longestlist = [word]
elif len(word) == maxlength:
longestlist.append(word)
for item in longestlist:
print item
```
-MLP | What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only put that one word in it and also update the longest length. If you visited words with same length as the longest you should add them to the list.
P.S. I did not put the code so you can do it yourself. |
39,693,115 | I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:
```
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
```
I need to extract the hours from each line (in this case 09) and then find the most common hours the emails were sent.
Basically, what I need to do is build a for loop that splits each text by colon
```
split(':')
```
and then splits by space:
```
split()
```
I've tried for hours, but can't seem to figure it out. What my code looks like so far:
```
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()
temp = list()
for line in handle:
if not "From " in line: continue
words = line.split(':')
for word in words:
counts[word] = counts.get(word,0) + 1
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse = True)
for val, key in lst:
print key, val
```
The code above only does 1 split, but I've kept trying multiple methods to split the text again. I keep getting a list attribute error, saying "list object has no attribute split". Would appreciate any help on this. Thanks again | 2016/09/26 | [
"https://Stackoverflow.com/questions/39693115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6879638/"
] | What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only put that one word in it and also update the longest length. If you visited words with same length as the longest you should add them to the list.
P.S. I did not put the code so you can do it yourself. | ### TLDR
Showing the results for a file named `poem.txt` whose contents are:
`a dog is by a cat to go hi`
```py
>>> with open('poem.txt', 'r') as file:
... words = file.read().split()
...
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']
```
### Explanation
You can also make this faster by using the fact that `<file-handle>.read.split()` returns a `list` object and the fact that Python's `max` function can take a function (as the keyword argument `key`.) After that, you can use list comprehension to find multiple longest words.
Let's clarify that. I'll start by making a file with the example properties you mentioned,
>
> For example, if the longest words were dog and cat your code should produce:
>
>
> dog cat
>
>
>
{If on Windows - here I specifically use `cmd`}
```
>echo a dog is by a cat to go hi > poem.txt
```
{If on a \*NIX system - here I specifically use `bash`}
```sh
$ echo "a dog is by a cat to go hi" > poem.txt
```
Let's look at the result of the `<file-handle>.read.split()` call. Let's follow the advice of @MLP and use the `with open` ... `as` statement.
{Windows}
```
>python
```
or possibly (with `conda`, for example)
```
>py
```
{\*NIX}
```sh
$ python3
```
From here, it's the same.
```py
>>> with open('poem.txt', 'r') as file:
... words = file.read().split()
...
>>> type(words)
<class 'list'>
```
From the [Python documentation for `max`](https://docs.python.org/3/library/functions.html#max)
>
> max(iterable, \*[, key, default])
>
>
> max(arg1, arg2, \*args[, key])
>
>
> Return the largest item in an iterable or the largest of two or more arguments.
>
>
> If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
>
>
> There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for `list.sort()`. The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a `ValueError` is raised.
>
>
> If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as `sorted(iterable, key=keyfunc, reverse=True)[0]` and `heapq.nlargest(1, iterable, key=keyfunc`).
>
>
> New in version 3.4: The default keyword-only argument.
>
>
> Changed in version 3.8: The key can be None.
>
>
>
Let's use a quick, not-so-robust way to see if we meet the iterable requirement ([this SO Q&A](https://stackoverflow.com/q/1952464/6505499) gives a variety of other ways).
```py
>>> hasattr(words, '__iter__')
True
```
Armed with this knowledge, and remembering the caveat, "If multiple items are maximal, the function returns the first one encountered.", we can go about solving the problem. We'll use the `len` function (use `>>> help(len)` if you want to know more).
```py
>>> max(words, key=len)
'dog'
```
Not quite there. We just have the word. Now, it's time to use list comprehension to find all words with that length. First getting that length
```py
>>> max_word_length = len(max(words, key=len))
>>> max_word_length
3
```
Now for the kicker.
```py
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']
```
or, using the commands from before, and making things a bit more readable
```py
>>> [this_word for this_word in words if len(this_word) == max_word_length]
['dog', 'cat']
```
You can use a variety of methods you'd like if you don't want the list format, i.e. if you actually want
`dog cat`
but I need to go, so I'll leave it where it is. |
39,693,115 | I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:
```
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
```
I need to extract the hours from each line (in this case 09) and then find the most common hours the emails were sent.
Basically, what I need to do is build a for loop that splits each text by colon
```
split(':')
```
and then splits by space:
```
split()
```
I've tried for hours, but can't seem to figure it out. What my code looks like so far:
```
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()
temp = list()
for line in handle:
if not "From " in line: continue
words = line.split(':')
for word in words:
counts[word] = counts.get(word,0) + 1
for key, val in counts.items():
lst.append( (val, key) )
lst.sort(reverse = True)
for val, key in lst:
print key, val
```
The code above only does 1 split, but I've kept trying multiple methods to split the text again. I keep getting a list attribute error, saying "list object has no attribute split". Would appreciate any help on this. Thanks again | 2016/09/26 | [
"https://Stackoverflow.com/questions/39693115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6879638/"
] | Ok, first off, you should probably use a `with` `as` statement, it just simplifies things and makes sure you don't mess up. So
`fh = open('poem.txt', 'r')`
becomes
`with open('poem.txt','r') as file:`
and since you're just concerned with words, you might as well use a built-in from the start:
```
words = file.read().split()
```
Then you just set a counter of the max word length (initialized to 0), and an empty list. If the word has broken the max length, set a new maxlength and rewrite the list to include only that word. If it's equal to the maxlength, include it in the list. Then just print out the list members. If you want to include some checks like `.isalpha()` feel free to put it in the relevant portions of the code.
```
maxlength = 0
longestlist = []
for word in words:
if len(word) > maxlength:
maxlength = len(word)
longestlist = [word]
elif len(word) == maxlength:
longestlist.append(word)
for item in longestlist:
print item
```
-MLP | ### TLDR
Showing the results for a file named `poem.txt` whose contents are:
`a dog is by a cat to go hi`
```py
>>> with open('poem.txt', 'r') as file:
... words = file.read().split()
...
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']
```
### Explanation
You can also make this faster by using the fact that `<file-handle>.read.split()` returns a `list` object and the fact that Python's `max` function can take a function (as the keyword argument `key`.) After that, you can use list comprehension to find multiple longest words.
Let's clarify that. I'll start by making a file with the example properties you mentioned,
>
> For example, if the longest words were dog and cat your code should produce:
>
>
> dog cat
>
>
>
{If on Windows - here I specifically use `cmd`}
```
>echo a dog is by a cat to go hi > poem.txt
```
{If on a \*NIX system - here I specifically use `bash`}
```sh
$ echo "a dog is by a cat to go hi" > poem.txt
```
Let's look at the result of the `<file-handle>.read.split()` call. Let's follow the advice of @MLP and use the `with open` ... `as` statement.
{Windows}
```
>python
```
or possibly (with `conda`, for example)
```
>py
```
{\*NIX}
```sh
$ python3
```
From here, it's the same.
```py
>>> with open('poem.txt', 'r') as file:
... words = file.read().split()
...
>>> type(words)
<class 'list'>
```
From the [Python documentation for `max`](https://docs.python.org/3/library/functions.html#max)
>
> max(iterable, \*[, key, default])
>
>
> max(arg1, arg2, \*args[, key])
>
>
> Return the largest item in an iterable or the largest of two or more arguments.
>
>
> If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
>
>
> There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for `list.sort()`. The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a `ValueError` is raised.
>
>
> If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as `sorted(iterable, key=keyfunc, reverse=True)[0]` and `heapq.nlargest(1, iterable, key=keyfunc`).
>
>
> New in version 3.4: The default keyword-only argument.
>
>
> Changed in version 3.8: The key can be None.
>
>
>
Let's use a quick, not-so-robust way to see if we meet the iterable requirement ([this SO Q&A](https://stackoverflow.com/q/1952464/6505499) gives a variety of other ways).
```py
>>> hasattr(words, '__iter__')
True
```
Armed with this knowledge, and remembering the caveat, "If multiple items are maximal, the function returns the first one encountered.", we can go about solving the problem. We'll use the `len` function (use `>>> help(len)` if you want to know more).
```py
>>> max(words, key=len)
'dog'
```
Not quite there. We just have the word. Now, it's time to use list comprehension to find all words with that length. First getting that length
```py
>>> max_word_length = len(max(words, key=len))
>>> max_word_length
3
```
Now for the kicker.
```py
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']
```
or, using the commands from before, and making things a bit more readable
```py
>>> [this_word for this_word in words if len(this_word) == max_word_length]
['dog', 'cat']
```
You can use a variety of methods you'd like if you don't want the list format, i.e. if you actually want
`dog cat`
but I need to go, so I'll leave it where it is. |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives? | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing.
If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3.
Edit: Usually the string returned by `__str__` will be specific to the class, but will at least be enough to identify the object. The exact format of the string will vary depending on the class and public attributes.
Edit2: Here is a simple (cutdown) example from a class describing countries:
```
def __str__(self):
return "{0:<32} {1:>010}".
format(self.__name, self.__population)
``` | The standard way to print custom info about an object (class instance) is to use `__str__` method:
```
class A:
var = 1
def __str__(self):
return 'Accessing from print function, var = {0}'.format(self.var)
```
In this method you can display any info you want
```
a = A()
print(a)
>>> Accessing from print function, var = 1
``` |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives? | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | You can overwrite either the `__str__` or the `__repr__` method.
There is no convention on how to implement the `__str__` method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the `__repr__` method: it should return a string representation of the object so that the object could be recreated from that representation (if possible), i.e. `eval(repr(obj)) == obj`.
Assuming you have a class `Point`, `__str__` and `__repr__` could be implemented like this:
```
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(%.2f, %.2f)" % (self.x, self.y)
def __repr__(self):
return "Point(x=%r, y=%r)" % (self.x, self.y)
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
```
Example:
```
>>> p = Point(0.1234, 5.6789)
>>> str(p)
'(0.12, 5.68)'
>>> "The point is %s" % p # this will call str
'The point is (0.12, 5.68)'
>>> repr(p)
'Point(x=0.1234, y=5.6789)'
>>> p # echoing p in the interactive shell calls repr internally
Point(x=0.1234, y=5.6789)
>>> eval(repr(p)) # this echos the repr of the new point created by eval
Point(x=0.1234, y=5.6789)
>>> type(eval(repr(p)))
<class '__main__.Point'>
>>> eval(repr(p)) == p
True
``` | Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing.
If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3.
Edit: Usually the string returned by `__str__` will be specific to the class, but will at least be enough to identify the object. The exact format of the string will vary depending on the class and public attributes.
Edit2: Here is a simple (cutdown) example from a class describing countries:
```
def __str__(self):
return "{0:<32} {1:>010}".
format(self.__name, self.__population)
``` |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives? | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing.
If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3.
Edit: Usually the string returned by `__str__` will be specific to the class, but will at least be enough to identify the object. The exact format of the string will vary depending on the class and public attributes.
Edit2: Here is a simple (cutdown) example from a class describing countries:
```
def __str__(self):
return "{0:<32} {1:>010}".
format(self.__name, self.__population)
``` | If your object can be represented in a way that allows recreation, then override the `__repr__` function. For example, if you can create your object with the following code:
```
MyObject('foo', 45)
```
The the `__repr__` should return `"MyObject('foo', 45)"`. You then don't need to implement a `__str__`.
But if the object is so complex that you can't represent it like that, override `__str__` instead. You should then return something that both makes it clear the object can't be recreated, and that it is an object. Hence, don't return `"foo:45"`, because that looks like a string, or `{'foo': 45}` because that looks like a dictionary, and that will confuse you when you debug.
I'd recommend that you keep the brackets, for example `<MyObject foo:45>`. That way it is clear that you have been printing an object, and it is also clear that it is not just a question of writing `MyObject('foo', 45)` to recreate the object, but that there is more data stored. |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives? | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | You can overwrite either the `__str__` or the `__repr__` method.
There is no convention on how to implement the `__str__` method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the `__repr__` method: it should return a string representation of the object so that the object could be recreated from that representation (if possible), i.e. `eval(repr(obj)) == obj`.
Assuming you have a class `Point`, `__str__` and `__repr__` could be implemented like this:
```
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(%.2f, %.2f)" % (self.x, self.y)
def __repr__(self):
return "Point(x=%r, y=%r)" % (self.x, self.y)
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
```
Example:
```
>>> p = Point(0.1234, 5.6789)
>>> str(p)
'(0.12, 5.68)'
>>> "The point is %s" % p # this will call str
'The point is (0.12, 5.68)'
>>> repr(p)
'Point(x=0.1234, y=5.6789)'
>>> p # echoing p in the interactive shell calls repr internally
Point(x=0.1234, y=5.6789)
>>> eval(repr(p)) # this echos the repr of the new point created by eval
Point(x=0.1234, y=5.6789)
>>> type(eval(repr(p)))
<class '__main__.Point'>
>>> eval(repr(p)) == p
True
``` | The standard way to print custom info about an object (class instance) is to use `__str__` method:
```
class A:
var = 1
def __str__(self):
return 'Accessing from print function, var = {0}'.format(self.var)
```
In this method you can display any info you want
```
a = A()
print(a)
>>> Accessing from print function, var = 1
``` |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives? | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | If your object can be represented in a way that allows recreation, then override the `__repr__` function. For example, if you can create your object with the following code:
```
MyObject('foo', 45)
```
The the `__repr__` should return `"MyObject('foo', 45)"`. You then don't need to implement a `__str__`.
But if the object is so complex that you can't represent it like that, override `__str__` instead. You should then return something that both makes it clear the object can't be recreated, and that it is an object. Hence, don't return `"foo:45"`, because that looks like a string, or `{'foo': 45}` because that looks like a dictionary, and that will confuse you when you debug.
I'd recommend that you keep the brackets, for example `<MyObject foo:45>`. That way it is clear that you have been printing an object, and it is also clear that it is not just a question of writing `MyObject('foo', 45)` to recreate the object, but that there is more data stored. | The standard way to print custom info about an object (class instance) is to use `__str__` method:
```
class A:
var = 1
def __str__(self):
return 'Accessing from print function, var = {0}'.format(self.var)
```
In this method you can display any info you want
```
a = A()
print(a)
>>> Accessing from print function, var = 1
``` |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives? | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | You can overwrite either the `__str__` or the `__repr__` method.
There is no convention on how to implement the `__str__` method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the `__repr__` method: it should return a string representation of the object so that the object could be recreated from that representation (if possible), i.e. `eval(repr(obj)) == obj`.
Assuming you have a class `Point`, `__str__` and `__repr__` could be implemented like this:
```
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(%.2f, %.2f)" % (self.x, self.y)
def __repr__(self):
return "Point(x=%r, y=%r)" % (self.x, self.y)
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
```
Example:
```
>>> p = Point(0.1234, 5.6789)
>>> str(p)
'(0.12, 5.68)'
>>> "The point is %s" % p # this will call str
'The point is (0.12, 5.68)'
>>> repr(p)
'Point(x=0.1234, y=5.6789)'
>>> p # echoing p in the interactive shell calls repr internally
Point(x=0.1234, y=5.6789)
>>> eval(repr(p)) # this echos the repr of the new point created by eval
Point(x=0.1234, y=5.6789)
>>> type(eval(repr(p)))
<class '__main__.Point'>
>>> eval(repr(p)) == p
True
``` | If your object can be represented in a way that allows recreation, then override the `__repr__` function. For example, if you can create your object with the following code:
```
MyObject('foo', 45)
```
The the `__repr__` should return `"MyObject('foo', 45)"`. You then don't need to implement a `__str__`.
But if the object is so complex that you can't represent it like that, override `__str__` instead. You should then return something that both makes it clear the object can't be recreated, and that it is an object. Hence, don't return `"foo:45"`, because that looks like a string, or `{'foo': 45}` because that looks like a dictionary, and that will confuse you when you debug.
I'd recommend that you keep the brackets, for example `<MyObject foo:45>`. That way it is clear that you have been printing an object, and it is also clear that it is not just a question of writing `MyObject('foo', 45)` to recreate the object, but that there is more data stored. |
68,929,023 | I have to do this in python so instead of writing these many lines - any other way ?
```
insert into table_a (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_b (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_c (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_d (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_e (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_f (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_g (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_h (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_i (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_j (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_k (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_l (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_m (col1,col2,col3) select col1,col2,col3 from temp;
```
Any code pointers would greatly help to refer. | 2021/08/25 | [
"https://Stackoverflow.com/questions/68929023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16257885/"
] | If you only need it to go until a specific letter, you can just use a string with as many letters as you need and then loop through them. [Thanks to Michael for pointing it out]
```
letters = "abcdefgh"
for letter in letters:
print(f"insert into table_{letter} (col1,col2,col3) select col1,col2,col3 from temp;")
```
This will return:
```
insert into table_a (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_b (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_c (col1,col2,col3) select col1,col2,col3 from temp;
``` | Put the table names in a `list`, then iterate on it and build the query with it
```
tables = ['table_a', 'table_b', 'table_c']
for table in tables:
query = f"insert into {table} (col1,col2,col3) select col1,col2,col3 from temp;"
``` |
12,084,445 | Is it possible to change the getter for a python property after it has been created?
```
class A:
_lookup_str = 'hi'
@property
def thing():
value = some_dictionary[_lookup_str]
# overwrite self.thing so that it is just value, not a special getter
return value
```
The idea is that once I've looked it up once, I shouldn't have to look it up again (the dictionary will never change). I could do:
```
class A:
_lookup_str = 'hi'
_thing = None
@property
def thing():
if not value:
value = some_dictionary[_lookup_str]
return value
```
But even there, I'm testing a condition -- which is more work than if I could remove the getter altogether and replace it with a value. | 2012/08/23 | [
"https://Stackoverflow.com/questions/12084445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257712/"
] | Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call.
Here's the code (from [werkzeug.utils on github](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/utils.py) and edited slightly for length):
```
_missing = object()
class cached_property(object):
"""A decorator that converts a function into a lazy property. The
function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
the value::
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a `__dict__` in order for this property to
work.
"""
# implementation detail: this property is implemented as non-data
# descriptor. non-data descriptors are only invoked if there is
# no entry with the same name in the instance's __dict__.
# this allows us to completely get rid of the access function call
# overhead. If one choses to invoke __get__ by hand the property
# will still work as expected because the lookup logic is replicated
# in __get__ for manual invocation.
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
def __get__(self, obj, type=None):
if obj is None:
return self
value = obj.__dict__.get(self.__name__, _missing)
if value is _missing:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
```
(btw - is it better to post code or a link to code for something like this?)
If you'd like to learn more about why this works, check out the [Python docs on descriptors](http://docs.python.org/howto/descriptor.html). The code above creates a non-data descriptor (unlike `@property`) which allows it to be overwritten. | The answer, as indicated by Jeff Tratner, is to overwrite the property object found in the `__dict__` of the python object. Werkzeug's cached\_property seems overcomplicated to me. The following (much simpler) code works for me:
```
def cached_property(f):
@property
def g(self, *args, **kwargs):
print 'trace'
value = f(self, *args, **kwargs)
self.__dict__[f.__name__] = value
return value
return g
class A:
@cached_property
def thing(self):
return 5
a = A()
print a.thing
print a.thing
print a.thing
print a.thing
# 'trace' is only shown once -- the first time a.thing is accessed.
``` |
12,084,445 | Is it possible to change the getter for a python property after it has been created?
```
class A:
_lookup_str = 'hi'
@property
def thing():
value = some_dictionary[_lookup_str]
# overwrite self.thing so that it is just value, not a special getter
return value
```
The idea is that once I've looked it up once, I shouldn't have to look it up again (the dictionary will never change). I could do:
```
class A:
_lookup_str = 'hi'
_thing = None
@property
def thing():
if not value:
value = some_dictionary[_lookup_str]
return value
```
But even there, I'm testing a condition -- which is more work than if I could remove the getter altogether and replace it with a value. | 2012/08/23 | [
"https://Stackoverflow.com/questions/12084445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257712/"
] | Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call.
Here's the code (from [werkzeug.utils on github](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/utils.py) and edited slightly for length):
```
_missing = object()
class cached_property(object):
"""A decorator that converts a function into a lazy property. The
function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
the value::
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a `__dict__` in order for this property to
work.
"""
# implementation detail: this property is implemented as non-data
# descriptor. non-data descriptors are only invoked if there is
# no entry with the same name in the instance's __dict__.
# this allows us to completely get rid of the access function call
# overhead. If one choses to invoke __get__ by hand the property
# will still work as expected because the lookup logic is replicated
# in __get__ for manual invocation.
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
def __get__(self, obj, type=None):
if obj is None:
return self
value = obj.__dict__.get(self.__name__, _missing)
if value is _missing:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
```
(btw - is it better to post code or a link to code for something like this?)
If you'd like to learn more about why this works, check out the [Python docs on descriptors](http://docs.python.org/howto/descriptor.html). The code above creates a non-data descriptor (unlike `@property`) which allows it to be overwritten. | It is not recommended but it works for old-style classes:
```
>>> class A:
... @property
... def thing(self):
... print 'thing'
... self.thing = 42
... return self.thing
...
>>> a = A()
>>> a.thing
thing
42
>>> a.thing
42
>>> a.thing
42
```
It doesn't work for new-style classes (subclasses of type, object) so it won't work on Python 3 where all classes are new-style. Use [@Jeff Tratner's answer](https://stackoverflow.com/a/12084534/4279) in this case. |
12,084,445 | Is it possible to change the getter for a python property after it has been created?
```
class A:
_lookup_str = 'hi'
@property
def thing():
value = some_dictionary[_lookup_str]
# overwrite self.thing so that it is just value, not a special getter
return value
```
The idea is that once I've looked it up once, I shouldn't have to look it up again (the dictionary will never change). I could do:
```
class A:
_lookup_str = 'hi'
_thing = None
@property
def thing():
if not value:
value = some_dictionary[_lookup_str]
return value
```
But even there, I'm testing a condition -- which is more work than if I could remove the getter altogether and replace it with a value. | 2012/08/23 | [
"https://Stackoverflow.com/questions/12084445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257712/"
] | Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call.
Here's the code (from [werkzeug.utils on github](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/utils.py) and edited slightly for length):
```
_missing = object()
class cached_property(object):
"""A decorator that converts a function into a lazy property. The
function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
the value::
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a `__dict__` in order for this property to
work.
"""
# implementation detail: this property is implemented as non-data
# descriptor. non-data descriptors are only invoked if there is
# no entry with the same name in the instance's __dict__.
# this allows us to completely get rid of the access function call
# overhead. If one choses to invoke __get__ by hand the property
# will still work as expected because the lookup logic is replicated
# in __get__ for manual invocation.
def __init__(self, func, name=None, doc=None):
self.__name__ = name or func.__name__
self.__module__ = func.__module__
self.__doc__ = doc or func.__doc__
self.func = func
def __get__(self, obj, type=None):
if obj is None:
return self
value = obj.__dict__.get(self.__name__, _missing)
if value is _missing:
value = self.func(obj)
obj.__dict__[self.__name__] = value
return value
```
(btw - is it better to post code or a link to code for something like this?)
If you'd like to learn more about why this works, check out the [Python docs on descriptors](http://docs.python.org/howto/descriptor.html). The code above creates a non-data descriptor (unlike `@property`) which allows it to be overwritten. | The answer by J.F. Sebastian and Isaac Sutherland do not work with new style classes.
It will produce the result Jeff Tratner mentions; printing out trace on every access.
For new style classes, you will need to override `__getattribute__`
Simple fix:
```
def cached_property(f):
@property
def g(self, *args, **kwargs):
print 'trace'
value = f(self, *args, **kwargs)
self.__dict__[f.__name__] = value
return value
return g
def cached_class(c):
def d(self, name):
getattr = object.__getattribute__
if (name in getattr(self, '__dict__')):
return getattr(self, '__dict__')[name]
return getattr(self, name)
c.__getattribute__ = d
return c
@cached_class
class A(object):
@cached_property
def thing(self):
return 5
a = A()
print a.thing
print a.thing
print a.thing
print a.thing
``` |
17,300,638 | I am trying to get Node.js to build on Windows. The process completes, seemingly okay, but does not generate node.lib.
Checking what was output it seems there is an issue right at the start (I disappeared off to get a coffee why I didn't see it at first) when trying to build.
```
Project files generated.
Setting environment for using Microsoft Visual Studio 2010 x86 tools.
node_js2c
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(1
51,5): error MSB6006: "cmd.exe" exited with code 1. [D:\dev\AccountsX\node-v0.1
0.12\node_js2c.vcxproj]
```
Checking the generated project code for `node_js2c.vcxproj` I can see this line:
```
<Command>call call C:\Program Files\Python27\python.exe "tools\js2c.py" ... </Command>
```
Which looks wrong on two counts. First the two `call` commands and then the unquoted path.
How do I fix this? | 2013/06/25 | [
"https://Stackoverflow.com/questions/17300638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] | You can save the previous position of the marble like this:
```
CGRect previousPosition = marbleFrame.frame;
```
And in the next iteration, if the marble collides the wall, set its frame to that.
Other solution would be checking from which side is colliding (top, left, right or down), that's easy comparing the intersection rect (for example, if the intersection rect top side is bigger than his right side, it means that is colliding from top or down) and place the marbleFrame besides it, just before entering.
Or, you can just the awesome SpriteKit in iOS7 where it's really easy to do, but only for iOS7 devices. | First of all, collision detection is not a easy thing to get working correctly, so you may want to look into some external libraries, such as ObjectiveChipmunk or Box2d.
That being said, there are a few things you could put into that else statement. The general way to go about it would be to "move the object back" so to speak, depending on which boundary he is hitting. If he is colliding with the left boundary, move him x units to the right, if he is hitting the top boundary, move him x units down, etc.
Another possible solution would be to keep track of the objects "valid" positions, and once it collides with a wall, return the object to its previous position. |
62,885,473 | ```
import numpy as np
import pandas as pd
df = pd.read_csv('Salaries.csv',engine='python')
print( df[ df['JobTitle'].value_counts()==1 ] )
```
I'm trying to get the row if the Job in JobTitle appears once.
However, I keep getting this error:
pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
Here is the Salaries.csv file:
`Id,EmployeeName,JobTitle,BasePay,OvertimePay,OtherPay,Benefits,TotalPay,TotalPayBenefits,Year,Notes,Agency,Status 1,NATHANIEL FORD,GENERAL MANAGER-METROPOLITAN TRANSIT AUTHORITY,167411.18,0.0,400184.25,,567595.43,567595.43,2011,,San Francisco, 2,GARY JIMENEZ,CAPTAIN III (POLICE DEPARTMENT),155966.02,245131.88,137811.38,,538909.28,538909.28,2011,,San Francisco, 3,ALBERT PARDINI,CAPTAIN III (POLICE DEPARTMENT),212739.13,106088.18,16452.6,,335279.91,335279.91,2011,,San Francisco, 4,CHRISTOPHER CHONG,WIRE ROPE CABLE MAINTENANCE MECHANIC,77916.0,56120.71,198306.9,,332343.61,332343.61,2011,,San Francisco,`
Sorry if that's hard to read - if it is, here is a pastebin: <https://pastebin.com/raw/eCfVj1Et> | 2020/07/13 | [
"https://Stackoverflow.com/questions/62885473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13758656/"
] | Another solution using `transform`:
```
df[df.groupby('JobTitle')['JobTitle'].transform('count').eq(1)]
``` | You can do it in a single line of code combining the index values of `value_counts()` where the series is equal to 1:
```
df[df['A'].isin((df['A'].value_counts() == 1).replace({False:np.nan}).dropna().index)]
```
Perhaps a bit better and easier to understand, in two lines of code:
```
values = df['A'].value_counts()
df[df['A'].isin(values.index[values.eq(1)])]
``` |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened.
A reference is closer to the concept of a pointer or object index. ie. it refers to a memory location.
`new` is definitely a keyword in Java, so saying it doesn't exist isn't very meaningful. You could say it doesn't have a one to one mapping in byte code, except byte code is itself run on a virtual machine and the machine actually run could be rather different anyway. i.e. there isn't much point treating byte code as the way things "really" happen. | constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory.
[here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html)
>
> Constructor declarations look like method declarations—except that
> they use the name of the class and have no return type
>
>
> |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened.
A reference is closer to the concept of a pointer or object index. ie. it refers to a memory location.
`new` is definitely a keyword in Java, so saying it doesn't exist isn't very meaningful. You could say it doesn't have a one to one mapping in byte code, except byte code is itself run on a virtual machine and the machine actually run could be rather different anyway. i.e. there isn't much point treating byte code as the way things "really" happen. | Short answer: no
More answer: The thing that is "returning" something is the `new` operator.
When you create a new instance of a class (via the `new` operator), you must provide two pieces of information to the JVM: the name of the class to be instantiated and any parameters that are required to construct the new object (constructor parameters).
To allow for this, java requires the following syntax:
```
Type1 variableName = new Type2(parameter list);
```
In your example: `People person = new People();` People is the type of the reference named person and is the type of the object being instantiated (i.e. new People). The constructor requires no parameters (a no-parameter constructor or default constructor) so the parameter list is "()". |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened.
A reference is closer to the concept of a pointer or object index. ie. it refers to a memory location.
`new` is definitely a keyword in Java, so saying it doesn't exist isn't very meaningful. You could say it doesn't have a one to one mapping in byte code, except byte code is itself run on a virtual machine and the machine actually run could be rather different anyway. i.e. there isn't much point treating byte code as the way things "really" happen. | The return type of a constructor is the **Class** itself.
You cannot consider them as void but its guaranteed to allocate memory on the heap and initialize the member fields , and finally returning the address of the newly allocated object which we use as reference variables. |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened.
A reference is closer to the concept of a pointer or object index. ie. it refers to a memory location.
`new` is definitely a keyword in Java, so saying it doesn't exist isn't very meaningful. You could say it doesn't have a one to one mapping in byte code, except byte code is itself run on a virtual machine and the machine actually run could be rather different anyway. i.e. there isn't much point treating byte code as the way things "really" happen. | according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object.
For Example: in your code `People person = new People();`
it automatically allocate the space required for the newly created object 'person' in the memory. |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory.
[here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html)
>
> Constructor declarations look like method declarations—except that
> they use the name of the class and have no return type
>
>
> | Short answer: no
More answer: The thing that is "returning" something is the `new` operator.
When you create a new instance of a class (via the `new` operator), you must provide two pieces of information to the JVM: the name of the class to be instantiated and any parameters that are required to construct the new object (constructor parameters).
To allow for this, java requires the following syntax:
```
Type1 variableName = new Type2(parameter list);
```
In your example: `People person = new People();` People is the type of the reference named person and is the type of the object being instantiated (i.e. new People). The constructor requires no parameters (a no-parameter constructor or default constructor) so the parameter list is "()". |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory.
[here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html)
>
> Constructor declarations look like method declarations—except that
> they use the name of the class and have no return type
>
>
> | The return type of a constructor is the **Class** itself.
You cannot consider them as void but its guaranteed to allocate memory on the heap and initialize the member fields , and finally returning the address of the newly allocated object which we use as reference variables. |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory.
[here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html)
>
> Constructor declarations look like method declarations—except that
> they use the name of the class and have no return type
>
>
> | according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object.
For Example: in your code `People person = new People();`
it automatically allocate the space required for the newly created object 'person' in the memory. |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | Short answer: no
More answer: The thing that is "returning" something is the `new` operator.
When you create a new instance of a class (via the `new` operator), you must provide two pieces of information to the JVM: the name of the class to be instantiated and any parameters that are required to construct the new object (constructor parameters).
To allow for this, java requires the following syntax:
```
Type1 variableName = new Type2(parameter list);
```
In your example: `People person = new People();` People is the type of the reference named person and is the type of the object being instantiated (i.e. new People). The constructor requires no parameters (a no-parameter constructor or default constructor) so the parameter list is "()". | according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object.
For Example: in your code `People person = new People();`
it automatically allocate the space required for the newly created object 'person' in the memory. |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object is stored assigned to people?
I am just thinking about this now because I am learning python, and want to connect the `__new__` method to a constructor and then `__init__` to the body of the constructor (i.e. the initial values). My professor keeps telling me `__new__` doesn't exist, so I am hoping to get an answer to make things clearer. | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | The return type of a constructor is the **Class** itself.
You cannot consider them as void but its guaranteed to allocate memory on the heap and initialize the member fields , and finally returning the address of the newly allocated object which we use as reference variables. | according to me, When the constructor used with 'new' keyword, it allocate the memory space for that object.
For Example: in your code `People person = new People();`
it automatically allocate the space required for the newly created object 'person' in the memory. |
20,435,615 | I am trying to build a list with the following format:
(t,dt,array)
Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Python.
What I am trying is:
```
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import heapq
popsize = 10
populat = [ (0,0,np.random.randint(0,2,Nsize)) for count in range(popsize)]
heapq.heapify(populat) # Structure to order efficiently
```
However this returns the following:
**ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()**
So does anybody knows how could it do that? or where does the error comes from?
I am using Ubuntu 12.04, running python 2.7 and also ipython 1.1.
I will be very grateful, thanks a lot. | 2013/12/06 | [
"https://Stackoverflow.com/questions/20435615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3053450/"
] | ```
(0,0,np.random.randint(0,2,Nsize))
```
The first two elements there aren't `t` or `dt`. They're both 0. As such, the tuple comparison tries to compare the arrays in the 3rd slot and finds that that doesn't produce a meaningful boolean result. Did you mean to have something meaningful in the first two slots? | As far as where the error comes from:
```
>>> a = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> b = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> a == b
```
The reason for this is that numpy overrides comparison operators in a non-standard way. Rather than returning a boolean result, it returns a numpy boolean *array*. |
20,435,615 | I am trying to build a list with the following format:
(t,dt,array)
Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Python.
What I am trying is:
```
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import heapq
popsize = 10
populat = [ (0,0,np.random.randint(0,2,Nsize)) for count in range(popsize)]
heapq.heapify(populat) # Structure to order efficiently
```
However this returns the following:
**ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()**
So does anybody knows how could it do that? or where does the error comes from?
I am using Ubuntu 12.04, running python 2.7 and also ipython 1.1.
I will be very grateful, thanks a lot. | 2013/12/06 | [
"https://Stackoverflow.com/questions/20435615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3053450/"
] | ```
(0,0,np.random.randint(0,2,Nsize))
```
The first two elements there aren't `t` or `dt`. They're both 0. As such, the tuple comparison tries to compare the arrays in the 3rd slot and finds that that doesn't produce a meaningful boolean result. Did you mean to have something meaningful in the first two slots? | So what I ended up doing was to add another element in the list to make the intial comparison possible:
```
populat = [ (0,0,i,np.random.randint(0,2,Nsize)) for i in range(popsize)]
```
As pointed above if the **two first elements are equal** the comparison goes to the third element (the array) which returns an error due to the bolean logic arrays.
The way around is to create an element that is different for each members of the list that inhibits comparisons at that level of the array (that's what the i is doing). |
20,435,615 | I am trying to build a list with the following format:
(t,dt,array)
Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Python.
What I am trying is:
```
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import heapq
popsize = 10
populat = [ (0,0,np.random.randint(0,2,Nsize)) for count in range(popsize)]
heapq.heapify(populat) # Structure to order efficiently
```
However this returns the following:
**ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()**
So does anybody knows how could it do that? or where does the error comes from?
I am using Ubuntu 12.04, running python 2.7 and also ipython 1.1.
I will be very grateful, thanks a lot. | 2013/12/06 | [
"https://Stackoverflow.com/questions/20435615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3053450/"
] | As far as where the error comes from:
```
>>> a = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> b = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> a == b
```
The reason for this is that numpy overrides comparison operators in a non-standard way. Rather than returning a boolean result, it returns a numpy boolean *array*. | So what I ended up doing was to add another element in the list to make the intial comparison possible:
```
populat = [ (0,0,i,np.random.randint(0,2,Nsize)) for i in range(popsize)]
```
As pointed above if the **two first elements are equal** the comparison goes to the third element (the array) which returns an error due to the bolean logic arrays.
The way around is to create an element that is different for each members of the list that inhibits comparisons at that level of the array (that's what the i is doing). |
18,026,306 | I am trying to create a python class based on this class. I am trying to have it return the person’s wages for the week (including time and a half for any overtime. I need to place this method following the def getPhoneNo(self): method and before the `def __str__(self):` method because I am trying to use this method in another program. I f anyone can help out.
>
>
> ```
> class PersonWorker:
>
> def _init_(self, firstName, lastName, phoneNo):
> self.firstName= firstName
> self.lastName= lastName
> self.phoneNo= phoneNo
> def getFirstName(self):
> return self.firstName
> def getLastName(self):
> return self.lastName
> def getPhoneNo(self):
> return self.phoneNo
> def _str_(self):
> stringRep = "First Name: " + self.firstName + "\n"
> stringRep = "Last Name: " + self.lastName + "\n"
> stringRep = "Phone Number : " + self.phoneNo + "\n"
> return stringRep`:
>
> def getWeeksPay(self, hours, rate)
>
> ```
>
> | 2013/08/02 | [
"https://Stackoverflow.com/questions/18026306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2631037/"
] | Is the `__str__` function looking alright? I mean stringRep is changed several times and the last version is returned.
I think the body of the function should look like this:
```
stringRep = "First Name: " + self.firstName + "\n" +\
"Last Name: " + self.lastName + "\n" +\
"Phone Number : " + self.phoneNo + "\n"
return stringRep
``` | I see two issues in the example you posted:
* The getWeeksPay function needs to be indented so that it is interpreted as a PersonWorker class method versus a normal function.
* You have some funky characters at the end of the return statement in the **str** method.
I updated your code snippet with an example of what I think you are trying to accomplish.
```
class PersonWorker:
def __init__(self, firstName, lastName, phoneNo, rate=0):
self.firstName= firstName
self.lastName= lastName
self.phoneNo= phoneNo
self.rate= rate
def getFirstName(self):
return self.firstName
def getLastName(self):
return self.lastName
def getPhoneNo(self):
return self.phoneNo
def getWeeksPay(self,hours):
if rate is 0: raise Exception("Rate not set")
return hours*self.rate
def __str__(self):
stringRep = "First Name: " + self.firstName + "\n"
stringRep += "Last Name: " + self.lastName + "\n"
stringRep += "Phone Number : " + self.phoneNo + "\n"
return stringRep
``` |
38,466,796 | I just made a heap class in python and am still working in Tree traversal. When I invoked `inoder function`, I got error said `None is not in the list`. In my three traversal functions, they all need `left` and `right` function. I assume that the problem is in these two functions, but I don't know how to fix it.
```
class myHeap:
heapArray = []
def __init_(self):
self.heapArray = []
def __str__(self):
string = " ".join(str(x) for x in self.heapArray)
return string
def makenull(self):
self.heapArray = []
def insert(self, x):
self.heapArray.append(x)
self.upheap(self.heapArray.index(x))
def parent(self, i):
p = (i - 1) / 2
p = int(p)
if(p >= 0):
return self.heapArray[p]
else:
return None
def left(self, i):
l = (i + 1) * 2 - 1
l = int(l)
if(l < len(self.heapArray)):
return self.heapArray[l]
else:
return
def right(self, i):
r = (i + 1) * 2
r = int(r)
if(r < len(self.heapArray)):
return self.heapArray[r]
else:
return None
def swap(self, a, b):
temp = self.heapArray[a]
self.heapArray[a] = self.heapArray[b]
self.heapArray[b] = temp
def upheap(self, i):
if(self.parent(i) and self.heapArray[i] < self.parent(i)):
p = (i - 1) / 2
p = int(p)
self.swap(i, p)
i = p
self.upheap(i)
else:
return
def downheap(self, i):
if(self.left(i) and self.right(i)):
if(self.left(i) <= self.right(i)):
n = self.heapArray.index(self.left(i))
self.swap(i, n)
self.downheap(n)
else:
n = self.heapArray.index(self.right(i))
self.swap(i, n)
self.downheap(n)
elif(self.left(i)):
n = self.heapArray.index(self.left(i))
self.swap(i, n)
self.downheap(n)
elif(self.right(i)):
n = self.heapArray.index(self.right())
self.swap(i,n)
self.downheap(n)
else:
return
def inorder(self, i):
if(self.heapArray[i] != None):
self.inorder(self.heapArray.index(self.left(i)))
print(self.heapArray[i], end=" ")
self.inorder(self.heapArray.index(self.right(i)))
def preorder(self, i):
if(self.heapArray[i] != None):
print(self.heapArray[i], end=" ")
self.preorder(self.heapArray.index(self.left(i)))
self.preorder(self.heapArray.index(self.right(i)))
def postorder(self, i):
if(self.heapArray[i]!= None):
self.postorder(self.heapArray.index(self.left(i)))
self.postorder(self.heapArray.index(self.right(i)))
print(self.heapArray[i], end=" ")
def min(self):
return self.heapArray[0]
def deletemin(self):
self.swap(0, len(self.heapArray) - 1)
self.heapArray.pop
self.downheap(0)
def main():
heap = myHeap()
heap.insert(0)
heap.insert(15)
heap.insert(7)
heap.insert(8)
heap.insert(1)
heap.insert(2)
heap.insert(22)
print(heap)
print(heap.heapArray[0])
heap.inorder(0)
heap.preorder(0)
heap.postorder(0)
if __name__ == "__main__":
main()
``` | 2016/07/19 | [
"https://Stackoverflow.com/questions/38466796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6338377/"
] | You don't actually need to use the ID directly; you can just sample row numbers, and then directly index the data.frame with those:
```
# How many rows in the data.frame?
n <- nrow(mtcars)
# Sample them
mtcars[sample(x = n, size = n, replace = TRUE), ]
```
If you pass in the same integer twice, you get that row twice. Here's an example of that principle in action:
```
mtcars[c(1, 1), ]
```
If you don't know it already, be sure to check out [the boot package](http://www.statmethods.net/advstats/bootstrapping.html), which automates a lot of bootstrapping scenarios for you. | I use the 'matches' function from the grr package for this.
```
Indices <- unlist(matches(b.idx, data_xy$ID, list=TRUE))
b.data <- data_xy[Indices, ]
``` |
65,284,837 | I have this pyspark script in Azure databricks notebook:
```
import argparse
from pyspark.sql.types import StructType
from pyspark.sql.types import StringType
spark.conf.set(
"fs.azure.account.key.gcdmchndev01c.dfs.core.chinacloudapi.cn",
"<storag account key>"
)
inputfile = "abfss://raw@gcdmchndev01c.dfs.core.chinacloudapi.cn/test/CODI_Ignored_Hospital_Code.csv"
outputpath = "abfss://spark-processed@gcdmchndev01c.dfs.core.chinacloudapi.cn/test/CODI_Ignored_Hospital_Code"
jsonTableSchema = "{'type': 'struct', 'fields': [{'name': 'id', 'type': 'integer', 'nullable': False, 'metadata': {} }, {'name': 'hospital_ddi_code', 'type': 'string', 'nullable': True, 'metadata': {} } ]}"
pipelineId = "test111111"
rawpath = "raw/test/CODI_Ignored_Hospital_Code"
rawfilename = "CODI_Ignored_Hospital_Code.csv"
outputpath_bad = "abfss://spark-processed@gcdmchndev01c.dfs.core.chinacloudapi.cn/bad/test/CODI_Ignored_Hospital_Code"
stSchema = StructType.fromJson(eval(jsonTableSchema))
stSchema.add("ValidateErrorMessage", StringType(),True)
raw = spark.read.csv(inputfile, schema=stSchema, header=True, columnNameOfCorruptRecord='ValidateErrorMessage', mode='PERMISSIVE')
raw.createOrReplaceTempView("tv_raw")
dfClean = spark.sql("""
select
*, nvl2(ValidateErrorMessage, 'failed', 'success') as ValidateStatus, now()+ INTERVAL 8 HOURS as ProcessDate, '""" + pipelineId + "'as ProcessId, '" + rawpath + "' as RawPath, '" + rawfilename + "' as RawFileName" + """
from
tv_raw
""")
#dfClean.printSchema()
dfBadRecord = dfClean.filter(dfClean["ValidateErrorMessage"].isNotNull())
#dfBadRecord.cache()
badCount = dfBadRecord.count()
```
And this gives me the error on the last line:
```
badCount = dfBadRecord.count()
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 21.0 failed 4 times, most recent failure: Lost task 0.3 in stage 21.0 (TID 39, 10.139.64.6, executor 1): com.databricks.sql.io.FileReadException: Error while reading file abfss:REDACTED_LOCAL_PART@gcdmchndev01c.dfs.core.chinacloudapi.cn/test/CODI_Ignored_Hospital_Code.csv
```
And detailed error:
```
Py4JJavaError Traceback (most recent call last)
<command-3450774645335260> in <module>
34 dfBadRecord = dfClean.filter(dfClean["ValidateErrorMessage"].isNotNull())
35 #dfBadRecord.cache()
---> 36 badCount = dfBadRecord.count()
37
/databricks/spark/python/pyspark/sql/dataframe.py in count(self)
584 2
585 """
--> 586 return int(self._jdf.count())
587
588 @ignore_unicode_prefix
/databricks/spark/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
1303 answer = self.gateway_client.send_command(command)
1304 return_value = get_return_value(
-> 1305 answer, self.gateway_client, self.target_id, self.name)
1306
1307 for temp_arg in temp_args:
``` | 2020/12/14 | [
"https://Stackoverflow.com/questions/65284837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759352/"
] | tl;dr
=====
```java
java.time.Duration.ofMillis( m ).toDaysPart()
```
Avoid legacy date-time types
============================
You are using terrible date-time classes that were supplanted years ago by the modern *java.time* classes. Never use `Calendar`, `GregorianCalendar`, `java.util.Date`, and such.
`java.time.Duration`
====================
Use [`java.time.Duration`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Duration.html) rather than [`javax.xml.datatype.Duration`](https://docs.oracle.com/en/java/javase/11/docs/api/java.xml/javax/xml/datatype/Duration.html).
```java
Duration duration = Duration.ofMillis( yourCountOfMillisecondsGoesHere ) ;
```
Apparently you want a count of generic 24-hour days without regard for dates. The `java.time.Duration` class can [give you that](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Duration.html#toDaysPart()).
```java
long countOf24HourDays = duration.toDaysPart() ;
```
No need for you to create a formal method of your own. Wherever you need it, just use:
```java
Duration.ofMillis( m ).toDaysPart()
```
---
About *java.time*
=================
The [*java.time*](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), & [`SimpleDateFormat`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html).
To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310).
The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/package-summary.html) classes.
You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes. Hibernate 5 & JPA 2.2 support *java.time*.
Where to obtain the java.time classes?
* [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), [**Java SE 11**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11), and later - Part of the standard Java API with a bundled implementation.
+ [**Java 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9) brought some minor features and fixes.
* [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7)
+ Most of the *java.time* functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/).
* [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system))
+ Later versions of Android (26+) bundle implementations of the *java.time* classes.
+ For earlier Android (<26), a process known as [*API desugaring*](https://developer.android.com/studio/write/java8-support#library-desugaring) brings a [subset of the *java.time*](https://developer.android.com/studio/write/java8-support-table) functionality not originally built into Android.
- If the desugaring does not offer what you need, the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above) to Android. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). | Use java.time also when you need javax.xml.datatype.Duration
------------------------------------------------------------
>
> I am explicitly asking for javax.xml.datatype. It is not in my hand to
> choose another datatype.
>
>
>
The conversion from `java.time.Duration` to a `javax.xml.datatype.Duration` fulfilling your requirements may not be exactly trivial, but I still prefer it as the easiest to understand and safest way to obtain what you want.
```
long millis = 21_098_765_432L;
boolean positive = millis > 0;
java.time.Duration javaTimeDuration = java.time.Duration.ofMillis(millis);
if (! positive) {
javaTimeDuration = javaTimeDuration.negated();
}
BigDecimal seconds = BigDecimal.valueOf(javaTimeDuration.toSecondsPart())
.add(BigDecimal.valueOf(javaTimeDuration.getNano(), 9))
.stripTrailingZeros();
Duration dur = DatatypeFactory.newInstance().newDuration(
positive,
null,
null,
BigInteger.valueOf(javaTimeDuration.toDays()),
BigInteger.valueOf(javaTimeDuration.toHoursPart()),
BigInteger.valueOf(javaTimeDuration.toMinutesPart()),
seconds);
System.out.println(dur);
```
Output from this snippet is:
>
> P244DT4H46M5.432S
>
>
>
What I like about the code is that it is explicit about using the days, hours, minutes and seconds including fraction of second from the java.time duration and constructing an XML duration without years and months.
Some of the trouble comes from the fact that the only way to pass fraction of second to a factory method is through `BigInteger` and `BigDecimal`. So I am first constructing a `BigDecimal` holding seconds and fraction of second.
The `toHoursPart`, `toMinutesPart` and `toSecondsPart` methods I am using were added in Java 9.
Link
----
[Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time. |
43,770,008 | I need to run a large build script (bash commands) on a python script. I receive it as a large string and each line is splitted by a \n. So, I need to execute each line separately.
At first, I tried to use [subprocess.Popen()](https://docs.python.org/2.7/library/subprocess.html) to execute them. But the problem is: after each line, the process terminates and all the environment variables are lost.
The problem is not to wait a command to finish to execute another, I need all of them to be executed on the same shell.
The only solution that I found so far is to save all those commands as a sh file (for example build.sh) and execute it on python.
I would not like to use this approuch because I want to have more control over each execution.
Is there any way to execute those commands on the same process, one by one?
Any other solution would be nice too. | 2017/05/03 | [
"https://Stackoverflow.com/questions/43770008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3061426/"
] | What you want is definitely a little weird, but it's possible using pipes.
```
from subprocess import PIPE, Popen
p = Popen(['bash'], stdin=PIPE, stdout=PIPE)
p.stdin.write('echo hello world\n')
print(p.stdout.readline())
# Check a return code
p.stdin.write('echo $?\n')
if p.stdout.readline().strip() ⩵ '0':
print("Command succeeded")
p.stdin.write('echo bye world\n')
# Close input and wait for bash to exit
stdout, stderr = p.communicate()
print(stdout)
``` | when calling a shell, the os starts a new process unless you have a shell interpreter in python all the way.
the only possibility to do it in the same process is simulating all steps with python directly.
the better way is to accept the limit, call an external process yourself and wait for the script to terminate controlled. example was e.g. here: [python to wait for shell command to complete](https://stackoverflow.com/questions/16196712/python-to-wait-for-shell-command-to-complete) |
66,399,560 | I have encountered some value error when input txt file into python.
the txt file called "htwt.txt", and contain the below data:
```
Ht Wt
169.6 71.2
166.8 58.2
157.1 56
181.1 64.5
158.4 53
165.6 52.4
166.7 56.8
156.5 49.2
168.1 55.6
165.3 77.8
```
When I typed the below code, and value errors are occurred.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import statsmodels.api as sm
from statsmodels.formula.api import ols
os.chdir("/Users/James/Desktop/data/")
data1=np.loadtxt("htwt.txt")
df1=pd.DataFrame(data1)
```
>
> ValueError: could not convert string to float: 'Ht'
>
>
>
May I know what should the correct code so that it can be converted to the data frame? thanks. | 2021/02/27 | [
"https://Stackoverflow.com/questions/66399560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14620006/"
] | Pandas `read_csv` is enough
```
import pandas as pd
import os
os.chdir("/Users/James/Desktop/data/")
df1 = pd.read_csv("htwt.txt",sep=' ')
```
Output:
```
>>> df1
Ht Wt
0 169.6 71.2
1 166.8 58.2
2 157.1 56.0
3 181.1 64.5
4 158.4 53.0
5 165.6 52.4
6 166.7 56.8
7 156.5 49.2
8 168.1 55.6
9 165.3 77.8
```
Checking the types:
```
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Ht 10 non-null float64
1 Wt 10 non-null float64
dtypes: float64(2)
memory usage: 288.0 bytes
``` | The first row in your text file has alphanumeric characters: "Ht Wt".
These characters cannot be converted to a floating point number.
Remove the first row and you should be fine. |
66,399,560 | I have encountered some value error when input txt file into python.
the txt file called "htwt.txt", and contain the below data:
```
Ht Wt
169.6 71.2
166.8 58.2
157.1 56
181.1 64.5
158.4 53
165.6 52.4
166.7 56.8
156.5 49.2
168.1 55.6
165.3 77.8
```
When I typed the below code, and value errors are occurred.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import statsmodels.api as sm
from statsmodels.formula.api import ols
os.chdir("/Users/James/Desktop/data/")
data1=np.loadtxt("htwt.txt")
df1=pd.DataFrame(data1)
```
>
> ValueError: could not convert string to float: 'Ht'
>
>
>
May I know what should the correct code so that it can be converted to the data frame? thanks. | 2021/02/27 | [
"https://Stackoverflow.com/questions/66399560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14620006/"
] | Like mentioned above pandas `read_csv` works, but if you insist on using `np.loadtxt` you can skip the first row which can't be converted to a float. You can do:
```py
data1 = np.loadtxt("htwt.txt", skiprows=1)
``` | The first row in your text file has alphanumeric characters: "Ht Wt".
These characters cannot be converted to a floating point number.
Remove the first row and you should be fine. |
66,399,560 | I have encountered some value error when input txt file into python.
the txt file called "htwt.txt", and contain the below data:
```
Ht Wt
169.6 71.2
166.8 58.2
157.1 56
181.1 64.5
158.4 53
165.6 52.4
166.7 56.8
156.5 49.2
168.1 55.6
165.3 77.8
```
When I typed the below code, and value errors are occurred.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import statsmodels.api as sm
from statsmodels.formula.api import ols
os.chdir("/Users/James/Desktop/data/")
data1=np.loadtxt("htwt.txt")
df1=pd.DataFrame(data1)
```
>
> ValueError: could not convert string to float: 'Ht'
>
>
>
May I know what should the correct code so that it can be converted to the data frame? thanks. | 2021/02/27 | [
"https://Stackoverflow.com/questions/66399560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14620006/"
] | Pandas `read_csv` is enough
```
import pandas as pd
import os
os.chdir("/Users/James/Desktop/data/")
df1 = pd.read_csv("htwt.txt",sep=' ')
```
Output:
```
>>> df1
Ht Wt
0 169.6 71.2
1 166.8 58.2
2 157.1 56.0
3 181.1 64.5
4 158.4 53.0
5 165.6 52.4
6 166.7 56.8
7 156.5 49.2
8 168.1 55.6
9 165.3 77.8
```
Checking the types:
```
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Ht 10 non-null float64
1 Wt 10 non-null float64
dtypes: float64(2)
memory usage: 288.0 bytes
``` | ```py
#for skipping of the first line
file1 = open("hwwt.txt")
lines = file1.readlines()[1:]
for line in lines:
print(line.rstrip())
OUTPUT
#otherwise you can use read_csv which is enough
``` |
66,399,560 | I have encountered some value error when input txt file into python.
the txt file called "htwt.txt", and contain the below data:
```
Ht Wt
169.6 71.2
166.8 58.2
157.1 56
181.1 64.5
158.4 53
165.6 52.4
166.7 56.8
156.5 49.2
168.1 55.6
165.3 77.8
```
When I typed the below code, and value errors are occurred.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import statsmodels.api as sm
from statsmodels.formula.api import ols
os.chdir("/Users/James/Desktop/data/")
data1=np.loadtxt("htwt.txt")
df1=pd.DataFrame(data1)
```
>
> ValueError: could not convert string to float: 'Ht'
>
>
>
May I know what should the correct code so that it can be converted to the data frame? thanks. | 2021/02/27 | [
"https://Stackoverflow.com/questions/66399560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14620006/"
] | Like mentioned above pandas `read_csv` works, but if you insist on using `np.loadtxt` you can skip the first row which can't be converted to a float. You can do:
```py
data1 = np.loadtxt("htwt.txt", skiprows=1)
``` | ```py
#for skipping of the first line
file1 = open("hwwt.txt")
lines = file1.readlines()[1:]
for line in lines:
print(line.rstrip())
OUTPUT
#otherwise you can use read_csv which is enough
``` |
45,138,223 | i have some sort of processes :
```
subprocess.Popen(['python2.7 script1.py')],shell=True)
subprocess.Popen(['python2.7 script2.py')],shell=True)
subprocess.Popen(['python2.7 script3.py')],shell=True)
subprocess.Popen(['python2.7 script4.py')],shell=True)
```
i want to each one starts after the previous process completely finish.
i mean
```
subprocess.Popen(['python2.7 script2.py')],shell=True)
```
starts after
```
subprocess.Popen(['python2.7 script1.py')],shell=True)
```
completly finished, and for others the same. this is cause previous scripts has output that it is used by next script.
thanks | 2017/07/17 | [
"https://Stackoverflow.com/questions/45138223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5121002/"
] | In my app the issue was caused by the templateUrl path being relative-to-code instead of absolute (relative-to-project).
I had added the `module.component(...)` part along with the UpgradeComponent in one go, since the ngJS component was originally routed to directly. When I did so, I used the ng4 usual way of writing templateUrls, where the path is relative to the code, rather than the old ngJS way where templateUrls tend to be relative to the project root.
Hence at runtime angular is looking in its cache for an HTML template by one path but it's in there under a different path, so it thinks it needs to get the template async-ly, causing the error. | I faced the same issue while upgrading from angularJs 1.7 to Angular 9. To fix the issue i changed **`template`** to **`templateUrl`** in the angularJS component file. |
31,318,739 | I try to install flask-bcrypt via pip, but it raisis me this error:
```
error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat)
```
I am currently running `Visual Studio 2015 RC` with `Python 3` on `Windows 10`.
Any ideas how to solve this error?
**Edit:**
I tried to follow diffrent solutions and installed Visual Studio 2010 Express and am now stuck with teh following error (Installing via PIP in VS 2013):
```
Collecting py-bcrypt
Using cached py-bcrypt-0.4.tar.gz
Installing collected packages: py-bcrypt
Running setup.py install for py-bcrypt
Complete output from command "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\Scripts\python.exe" -c "import setuptools, tokenize;__file__='C:\\Users\\Niels\\AppData\\Local\\Temp\\pip-build-3pqnujd2\\py-bcrypt\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\Niels\AppData\Local\Temp\pip-syaty7au-record\install-record.txt --single-version-externally-managed --compile --install-headers "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\include\site\python3.4\py-bcrypt":
running install
running build
running build_py
creating build
creating build\lib.win-amd64-3.4
creating build\lib.win-amd64-3.4\bcrypt
copying bcrypt\__init__.py -> build\lib.win-amd64-3.4\bcrypt
running build_ext
building 'bcrypt._bcrypt' extension
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\Niels\AppData\Local\Temp\pip-build-3pqnujd2\py-bcrypt\setup.py", line 61, in <module>
ext_modules = [bcrypt]
File "C:\Users\Niels\Anaconda3\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "C:\Users\Niels\Anaconda3\lib\distutils\dist.py", line 955, in run_commands
self.run_command(cmd)
File "C:\Users\Niels\Anaconda3\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\lib\site-packages\setuptools-15.1-py3.4.egg\setuptools\command\install.py", line 61, in run
File "C:\Users\Niels\Anaconda3\lib\distutils\command\install.py", line 539, in run
self.run_command('build')
File "C:\Users\Niels\Anaconda3\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Users\Niels\Anaconda3\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\Users\Niels\Anaconda3\lib\distutils\command\build.py", line 126, in run
self.run_command(cmd_name)
File "C:\Users\Niels\Anaconda3\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Users\Niels\Anaconda3\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\lib\site-packages\setuptools-15.1-py3.4.egg\setuptools\command\build_ext.py", line 50, in run
File "C:\Users\Niels\Anaconda3\lib\distutils\command\build_ext.py", line 339, in run
self.build_extensions()
File "C:\Users\Niels\Anaconda3\lib\distutils\command\build_ext.py", line 448, in build_extensions
self.build_extension(ext)
File "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\lib\site-packages\setuptools-15.1-py3.4.egg\setuptools\command\build_ext.py", line 183, in build_extension
File "C:\Users\Niels\Anaconda3\lib\distutils\command\build_ext.py", line 503, in build_extension
depends=ext.depends)
File "C:\Users\Niels\Anaconda3\lib\distutils\msvc9compiler.py", line 460, in compile
self.initialize()
File "C:\Users\Niels\Anaconda3\lib\distutils\msvc9compiler.py", line 371, in initialize
vc_env = query_vcvarsall(VERSION, plat_spec)
File "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\lib\site-packages\setuptools-15.1-py3.4.egg\setuptools\msvc9_support.py", line 52, in query_vcvarsall
File "C:\Users\Niels\Anaconda3\lib\distutils\msvc9compiler.py", line 287, in query_vcvarsall
raise ValueError(str(list(result.keys())))
ValueError: ['path']
----------------------------------------
Command ""C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\Scripts\python.exe" -c "import setuptools, tokenize;__file__='C:\\Users\\Niels\\AppData\\Local\\Temp\\pip-build-3pqnujd2\\py-bcrypt\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\Niels\AppData\Local\Temp\pip-syaty7au-record\install-record.txt --single-version-externally-managed --compile --install-headers "C:\Users\Niels\Documents\Visual Studio 2013\Projects\biospark\biospark\env_biospark\include\site\python3.4\py-bcrypt"" failed with error code 1 in C:\Users\Niels\AppData\Local\Temp\pip-build-3pqnujd2\py-bcrypt
'py-bcrypt' failed to install. Exit code: 1
```
**Edit 2:** I installed pycrypto via thsi Windows Installer: <https://github.com/axper/python3-pycrypto-windows-installer> which comes with bcrypt and suits my needs. But it would be nice to solve the original Problem. | 2015/07/09 | [
"https://Stackoverflow.com/questions/31318739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023926/"
] | Apparently the problem can be solved by installing py-bcrypt first. A win32 installer is available from the first comment to this reddit post:
<http://www.reddit.com/r/flask/comments/15q5xj/anyone_have_a_working_version_of_flaskbcrypt_for/> | Here is another option, you need to setup Wheel package before you can import bcrypt
```
pip install wheel
```
```
pip install bcrypt
```
```
from flask_bcrypt import Bcrypt
``` |
15,077,627 | TL;DR: I want a locals() that looks in a containing scope.
Hi, all.
I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope.
Consider:
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
```
Locals prints an empty environment, and globals prints the usual globals. How do I get access to the environment where x is stored? Clearly the interpreter knows about it because I can refer to it.
Related: When does scoping happen? The following nameErrors on a = x+2 only if x=3 is included:
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
```
If you comment out x=3, the code works. Does this mean that python makes a lexical-scope pass over the code before it interprets it? | 2013/02/25 | [
"https://Stackoverflow.com/questions/15077627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1911697/"
] | What is happening in your code is that when python see's the `x=3` line in your `b()` method, it is recreating `x` with a scope within the `b` function instead of using the `x` with it's scope in the `a` function.
because your code then goes:
```
a = x+2
x = 3
```
it is saying that you need to define the inner scoped `x` before referencing it.
however, when you do not have the assigning of `x` within the `b` function python does not attempt to make a lower scoped `x` and will not throw any errors.
The following code will illustrate this:
```
def a():
x = 1
def b():
x = 3
print (x)
def c():
print (x)
b()
c()
print (x)
a()
```
However if you were to declare `x` as `global` you could use it within a function, like so:
```
def a():
global x
x = 1
def d():
global x
x += 2
print (x)
d()
print (x)
a()
```
Python 3 has also added a `nonlocal` keyword that will let you access a variable from an enclosing scope, usage is like:
```
def a():
x = 1
def d():
nonlocal x
x += 2
print (x)
d()
print (x)
a()
```
Will print the same results as the `global` example.
---
In case I miss-read the question:
As per the answer to [Get locals from calling namespace in Python](https://stackoverflow.com/questions/6618795/get-locals-from-calling-namespace-in-python):
you can use:
```
import inspect
def a():
x = 1
def d():
frame = inspect.currentframe()
try:
print (frame.f_back.f_locals)
finally:
del frame
d()
a()
```
to get the local scope of the functions caller. | The statement `print(locals())` refers to nearest enclosing scope, that is the `def b():` function. When calling `b()`, you will print the locals to this b function, and definition of x is outside the scope.
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
print(locals())
```
would print x as a local variable.
For your second question:
```
def a():
x = 1
def b():
#a = x+2
x = 3
b()
>>> a()
```
gives no error.
```
def a():
x = 1
def b():
a = x+2
#x = 3
b()
>>> a()
```
gives no error.
And
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
>>> a()
```
gives following error: `UnboundLocalError: local variable 'x' referenced before assignment`
IMO (please check), in this third case, first statement in the body of `b()` looks for value of x *in the most enclosing scope*. And in this scope, x is assigned on the next line. If you only have statement `a = x+2`, x is not found in most enclosing scope, and is found in the 'next' enclosing scope, with `x = 1`. |
15,077,627 | TL;DR: I want a locals() that looks in a containing scope.
Hi, all.
I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope.
Consider:
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
```
Locals prints an empty environment, and globals prints the usual globals. How do I get access to the environment where x is stored? Clearly the interpreter knows about it because I can refer to it.
Related: When does scoping happen? The following nameErrors on a = x+2 only if x=3 is included:
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
```
If you comment out x=3, the code works. Does this mean that python makes a lexical-scope pass over the code before it interprets it? | 2013/02/25 | [
"https://Stackoverflow.com/questions/15077627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1911697/"
] | The statement `print(locals())` refers to nearest enclosing scope, that is the `def b():` function. When calling `b()`, you will print the locals to this b function, and definition of x is outside the scope.
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
print(locals())
```
would print x as a local variable.
For your second question:
```
def a():
x = 1
def b():
#a = x+2
x = 3
b()
>>> a()
```
gives no error.
```
def a():
x = 1
def b():
a = x+2
#x = 3
b()
>>> a()
```
gives no error.
And
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
>>> a()
```
gives following error: `UnboundLocalError: local variable 'x' referenced before assignment`
IMO (please check), in this third case, first statement in the body of `b()` looks for value of x *in the most enclosing scope*. And in this scope, x is assigned on the next line. If you only have statement `a = x+2`, x is not found in most enclosing scope, and is found in the 'next' enclosing scope, with `x = 1`. | `python3 -c "help(locals)"` says this about the `locals` function:
```
locals()
Return a dictionary containing the current scope's local variables.
```
That means that calling `locals()` in `b()` will only show you which variables are local to `b()`. That doesn't mean that `b()` can't see variables outside its scope -- but rather, `locals()` only returns information for variables local to `b()`.
What you probably want is to make `b()` show information on the variables of the calling function. To do that, take this code (which show's `b()`'s local variables):
```
def a():
x = 1
def b():
print(locals())
b()
```
and replace it with this one (which uses the `inspect` module to get you the local information of the calling frame):
```
def a():
x = 1
def b():
import inspect
print(inspect.currentframe().f_back.f_locals)
b()
```
---
As for your other issue:
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
```
The error you get is because Python 3 allows you to set/assign global variables and variables local to outside scopes provided you declare them with the `global` and `nonlocal` keywords. (I won't explain them here; I'll just say that you won't have any problem looking them up yourself.)
If you remove the `x = 3` line (keeping the `a = x+2` line), your code will run because `x`'s value is being used, but not set. If instead you remove the `a = x+2` line (keeping the `x = 3` line), your code will run because it will create a new `x` inside `b()`'s scope.
If you keep both lines, Python doesn't know whether `x` is supposed to refer to an `x` outside the current scope (as `a = x+2` seems to suggest) or if it's supposed to refer to an `x` local to `b()`'s scope (as `x = 3` suggests).
If you want `x` to be local to `b()`, then you shouldn't have that `a = x+2` line there, at least not before `x` is set with `x = 3`. But if you want `x` to be `a()`'s `x`, then you should declare `x` as `nonlocal` to `b()`, like this:
```
def a():
x = 1
def b():
nonlocal x # use a()'s x
a = x+2
x = 3
b()
```
If you're confused, remember that Python will let you *use* global variables and variables created outside of your current scope, but only if you don't *assign* to them. (It's often acceptable to read global variables, but it's frowned upon to set them.)
If you want to set a global variable or a non-local variable, you will have to declare those variables with `global` (for global variables) or `nonlocal` (for non-local variables), as shown in the above code.
I hope this helps. |
15,077,627 | TL;DR: I want a locals() that looks in a containing scope.
Hi, all.
I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope.
Consider:
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
```
Locals prints an empty environment, and globals prints the usual globals. How do I get access to the environment where x is stored? Clearly the interpreter knows about it because I can refer to it.
Related: When does scoping happen? The following nameErrors on a = x+2 only if x=3 is included:
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
```
If you comment out x=3, the code works. Does this mean that python makes a lexical-scope pass over the code before it interprets it? | 2013/02/25 | [
"https://Stackoverflow.com/questions/15077627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1911697/"
] | What is happening in your code is that when python see's the `x=3` line in your `b()` method, it is recreating `x` with a scope within the `b` function instead of using the `x` with it's scope in the `a` function.
because your code then goes:
```
a = x+2
x = 3
```
it is saying that you need to define the inner scoped `x` before referencing it.
however, when you do not have the assigning of `x` within the `b` function python does not attempt to make a lower scoped `x` and will not throw any errors.
The following code will illustrate this:
```
def a():
x = 1
def b():
x = 3
print (x)
def c():
print (x)
b()
c()
print (x)
a()
```
However if you were to declare `x` as `global` you could use it within a function, like so:
```
def a():
global x
x = 1
def d():
global x
x += 2
print (x)
d()
print (x)
a()
```
Python 3 has also added a `nonlocal` keyword that will let you access a variable from an enclosing scope, usage is like:
```
def a():
x = 1
def d():
nonlocal x
x += 2
print (x)
d()
print (x)
a()
```
Will print the same results as the `global` example.
---
In case I miss-read the question:
As per the answer to [Get locals from calling namespace in Python](https://stackoverflow.com/questions/6618795/get-locals-from-calling-namespace-in-python):
you can use:
```
import inspect
def a():
x = 1
def d():
frame = inspect.currentframe()
try:
print (frame.f_back.f_locals)
finally:
del frame
d()
a()
```
to get the local scope of the functions caller. | `python3 -c "help(locals)"` says this about the `locals` function:
```
locals()
Return a dictionary containing the current scope's local variables.
```
That means that calling `locals()` in `b()` will only show you which variables are local to `b()`. That doesn't mean that `b()` can't see variables outside its scope -- but rather, `locals()` only returns information for variables local to `b()`.
What you probably want is to make `b()` show information on the variables of the calling function. To do that, take this code (which show's `b()`'s local variables):
```
def a():
x = 1
def b():
print(locals())
b()
```
and replace it with this one (which uses the `inspect` module to get you the local information of the calling frame):
```
def a():
x = 1
def b():
import inspect
print(inspect.currentframe().f_back.f_locals)
b()
```
---
As for your other issue:
```
def a():
x = 1
def b():
a = x+2
x = 3
b()
```
The error you get is because Python 3 allows you to set/assign global variables and variables local to outside scopes provided you declare them with the `global` and `nonlocal` keywords. (I won't explain them here; I'll just say that you won't have any problem looking them up yourself.)
If you remove the `x = 3` line (keeping the `a = x+2` line), your code will run because `x`'s value is being used, but not set. If instead you remove the `a = x+2` line (keeping the `x = 3` line), your code will run because it will create a new `x` inside `b()`'s scope.
If you keep both lines, Python doesn't know whether `x` is supposed to refer to an `x` outside the current scope (as `a = x+2` seems to suggest) or if it's supposed to refer to an `x` local to `b()`'s scope (as `x = 3` suggests).
If you want `x` to be local to `b()`, then you shouldn't have that `a = x+2` line there, at least not before `x` is set with `x = 3`. But if you want `x` to be `a()`'s `x`, then you should declare `x` as `nonlocal` to `b()`, like this:
```
def a():
x = 1
def b():
nonlocal x # use a()'s x
a = x+2
x = 3
b()
```
If you're confused, remember that Python will let you *use* global variables and variables created outside of your current scope, but only if you don't *assign* to them. (It's often acceptable to read global variables, but it's frowned upon to set them.)
If you want to set a global variable or a non-local variable, you will have to declare those variables with `global` (for global variables) or `nonlocal` (for non-local variables), as shown in the above code.
I hope this helps. |
52,736,009 | I have improved [my first Python program](https://stackoverflow.com/questions/51300358/python-hiding-json-empty-key-values-in-the-print-statement/51302419?noredirect=1) using f-strings instead of print:
```
....
js = json.loads(data)
# here is an excerpt of my code:
def publi(type):
if type == 'ART':
return f"{nom} ({dat}). {tit}. {jou}. Pubmed: {pbm}"
print("Journal articles:")
for art in js['response']['docs']:
stuff = art['docType_s']
if not stuff == 'ART': continue
tit = art['title_s'][0]
nom = art['authFullName_s'][0]
jou = art['journalTitle_s']
dat = art['producedDateY_i']
try:
pbm = art['pubmedId_s']
except (KeyError, NameError):
pbm = ""
print(publi('ART'))
```
This program fetches data through json files to build scientific citations:
```
# sample output: J A. Anderson (2018). Looking at the DNA structure, Nature. PubMed: 3256988
```
It works well, except that (again) I don't know how to hide key values from the return statement when keys have no value (ie. there is no such key in the json file for one specific citation).
For example, some of the scientific citations have no "Pubmed" key/value (pmd). Instead of printing "Pubmed: " with a blank value, I would like to get rid of both of them:
```
# Desired output (when pbm key is missing from the JSON file):
# J A. Anderson (2018) Looking at the DNA structure, Nature
# NOT: J A. Anderson (2018) Looking at the DNA structure, Nature. Pubmed:
```
Using the **print** statement in the publi function, I could write the following:
```
# Pubmed: ' if len(pbm)!=0 else "", pbm if len(pbm)!=0 else ""
```
Does anyone know how to get the same result using **f-string**?
Thanks for your help.
PS: As a python beginner, I would not have been able to solve this specific problem just reading the post [Using f-string with format depending on a condition](https://stackoverflow.com/questions/51885913/using-f-string-with-format-depending-on-a-condition) | 2018/10/10 | [
"https://Stackoverflow.com/questions/52736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10069047/"
] | You can use a conditional expression in an f-string as well:
```
return f"{nom} {'(%s)' % dat if dat else ''}. {tit}. {jou}. {'Pubmed: ' + pbm if pbm else ''}"
```
or you can simply use the `and` operator:
```
return f"{nom} {dat and '(%s)' % dat}. {tit}. {jou}. {pbm and 'Pubmed: ' + pbm}"
``` | An easy but slightly fugly workaround is to have the formatting decorations in the string.
```
try:
pbm = ". Pubmed: " + art['pubmedId_s']
except (KeyError, NameError):
pbm = ""
...
print(f"{nom} ({dat}). {tit}. {jou}{pbm}")
``` |
11,188,619 | I have a string built from a few segments, which are not separated, but not overlap. This looks like that:
```
<python><regex><split>
```
I would like to split in into:
```
<python>, <regex>, <split>
```
I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I could change '>' into '> ' etc., but I don't want to do any redundant operations. Is it possible to use regex to do that? | 2012/06/25 | [
"https://Stackoverflow.com/questions/11188619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531954/"
] | Try [re.findall](http://docs.python.org/library/re.html#re.findall):
```
import re
your_string = '<python><regex><split>'
parts = re.findall(r'<.+?>', your_string)
print parts # ['<python>', '<regex>', '<split>']
``` | If your input data is really that simple, you can just use the `.replace()` method that's built into strings.
```
>>> '<python><regex><split>'.replace('><', '>, <')
'<python>, <regex>, <split>'
```
If it's more complex, you should give a better example of input/expected output. |
11,188,619 | I have a string built from a few segments, which are not separated, but not overlap. This looks like that:
```
<python><regex><split>
```
I would like to split in into:
```
<python>, <regex>, <split>
```
I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I could change '>' into '> ' etc., but I don't want to do any redundant operations. Is it possible to use regex to do that? | 2012/06/25 | [
"https://Stackoverflow.com/questions/11188619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531954/"
] | ```
>>> re.sub(r'<(.+?)>',r'<\1>,','<python><regex><split>')[:-1]
'<python>,<regex>,<split>'
``` | If your input data is really that simple, you can just use the `.replace()` method that's built into strings.
```
>>> '<python><regex><split>'.replace('><', '>, <')
'<python>, <regex>, <split>'
```
If it's more complex, you should give a better example of input/expected output. |
11,188,619 | I have a string built from a few segments, which are not separated, but not overlap. This looks like that:
```
<python><regex><split>
```
I would like to split in into:
```
<python>, <regex>, <split>
```
I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I could change '>' into '> ' etc., but I don't want to do any redundant operations. Is it possible to use regex to do that? | 2012/06/25 | [
"https://Stackoverflow.com/questions/11188619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531954/"
] | Try [re.findall](http://docs.python.org/library/re.html#re.findall):
```
import re
your_string = '<python><regex><split>'
parts = re.findall(r'<.+?>', your_string)
print parts # ['<python>', '<regex>', '<split>']
``` | ```
>>> re.sub(r'<(.+?)>',r'<\1>,','<python><regex><split>')[:-1]
'<python>,<regex>,<split>'
``` |
58,257,125 | I have a form with an `<input type="file">`, and I'm getting an error when I try to save the uploaded image. The image is uploaded via POST XMLHttpRequest. I have no idea why this is happening.
views.py:
```
import datetime
from django.shortcuts import render
from .models import TemporaryImage
def upload_file(request):
key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}'
for file in request.FILES.get('file'):
img = TemporaryImage(image=file, key=key)
img.save()
def home_view(request):
return render(request, 'products/home.html', {})
```
models.py:
```
from django.db import models
def get_temp_image_path(instance, filename):
return os.path.join('tmp', str(instance.id), filename)
class TemporaryImage(models.Model):
image = models.ImageField(upload_to=get_temp_image_path, blank=True, null=True)
key = models.CharField(max_length=100)
```
urls.py:
```
from django.contrib import admin
from django.urls import path
from products.views import upload_file, home_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
path('upload/', upload_file, name='upload_file')
]
```
template 'home.html':
```
<!DOCTYPE html>
<html>
<head>
<title>SO Question</title>
<script>
function uploadFile() {
var fd = new FormData();
fd.append("file", document.getElementById('file').files[0]);
var value = [];
document.getElementsByName('csrfmiddlewaretoken').forEach(function(x) {
value.push(x.value);
})
fd.append('csrfmiddlewaretoken', value[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/upload/');
xhr.send(fd);
}
</script>
</head>
<body>
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
<label for="file">Select a File to Upload</label>
<input type="file" id="file" name="file">
<input type="button" onclick="uploadFile()" value="Upload">
</form>
</body>
</html>
```
full stack trace:
```
[06/Oct/2019 12:05:40] "GET / HTTP/1.1" 200 968
request.FILES is <MultiValueDict: {'file': [<TemporaryUploadedFile: 20190615_193154.jpg (image/jpeg)>]}>
image is b'\xff\xd8\xff\xe1\\\xd5Exif\x00\x00II*\x00\x08\x00\x00\x00\x0c\x00\x00\x01\x04\x00\x01\x00\x00\x00 \x10\x00\x00\x01\x01\x04\x00\x01\x00\x00\x00\x18\x0c\x00\x00\x0f\x01\x02\x00\x08\x00\x00\x00\xae\x00\x00\x00\x10\x01\x02\x00\n'
Internal Server Error: /upload/
Traceback (most recent call last):
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/alex/.repos/codelib/practice/soq/src/soq/products/views.py", line 13, in upload_file
img.save()
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql
for sql, params in self.as_sql():
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in as_sql
for obj in self.query.objs
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in <listcomp>
for obj in self.query.objs
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1277, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1228, in pre_save_val
return field.pre_save(obj, add=True)
File "/home/alex/.repos/codelib/practice/soq/env/lib/python3.6/site-packages/django/db/models/fields/files.py", line 286, in pre_save
if file and not file._committed:
AttributeError: 'bytes' object has no attribute '_committed'
```
What could be the issue? | 2019/10/06 | [
"https://Stackoverflow.com/questions/58257125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629753/"
] | You're only uploading a single file; you shouldn't be iterating over the file key.
```
def upload_file(request):
key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}'
file = request.FILES.get('file')
if file:
img = TemporaryImage(image=file, key=key)
img.save()
``` | i guess you have too try to save your image this way:
```
from django.core.files.base import ContentFile
...
def upload_file(request):
key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}'
file = request.FILES.get('file')
if file :
img = TemporaryImage.objects.create(key=key)
img.image.save(key, ContentFile(file), save=True)
``` |
1,312,524 | I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and put a key listener inside it.
Python:
```
def getInput():
while 1:
for event in pygame.event.get(): #returns a list of events from the keyboard/mouse
if event.type == KEYDOWN:
if event.key == "enter": # for example
do function()
return
elif event.key == "up":
do function2()
continue
else: continue # for clarity
```
In trying to find a way to implement this in DOM/javascript, I seem to just crash the page (I assume due to the While Loop), but I presume this is because my event handling is poorly written. Also, registering event handlers with "element.onkeydown = function;" difficult for me to wrap my head around, and setInterval(foo(), interval] hasn't brought me much success.
Basically, I want a "listening" loop to do a certain behavior for key X, but to break when key Y is hit. | 2009/08/21 | [
"https://Stackoverflow.com/questions/1312524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160854/"
] | For easier implementation of event handling I recommend you to use a library such as [Prototype](http://www.prototypejs.org/api/event) or [Jquery](http://docs.jquery.com/Events) (Note that both links take you to their respective Event handling documentation.
In order to use them you have to keep in mind 3 things:
* What DOM element you want to observe
* What Event you want to capture
* What action will the event trigger
This three points are mutually inclusive, meaning you need to take care of the 3 when writing the code.
So having this in mind, using Prototype, you could do this:
```
Event.observe($('id_of_the_element_to_observe'), 'keypress', function(ev) {
// the argument ev is the event object that has some useful information such
// as which keycode was pressed.
code_to_run;
});
```
Here is the code of a more useful example, a CharacterCounter (such as the one found in Twitter, but surely a lot less reliable ;) ):
```
var CharacterCounter = Class.create({
initialize: function(input, counter, max_chars) {
this.input = input;
this.counter = counter;
this.max_chars = max_chars;
Event.observe(this.input, 'keypress', this.keyPressHandler.bind(this));
Event.observe(this.input, 'keyup', this.keyUpHandler.bind(this));
},
keyUpHandler: function() {
words_left = this.max_chars - $F(this.input).length;
this.counter.innerHTML = words_left;
},
keyPressHandler: function(e) {
words_left = this.max_chars - $F(this.input).length;
if (words_left <= 0 && this.allowedChars(e.keyCode)) {
e.stop();
}
},
allowedChars: function(keycode) {
// 8: backspace, 37-40: arrow keys, 46: delete
allowed_keycodes = [ 8, 37, 38, 39, 40, 46 ];
if (allowed_keycodes.include(keycode)) {
return false;
}
return true
}
});
``` | you could attach an event listener to the window object like this
```
window.captureEvents(Event.KEYPRESS);
window.onkeypress = output;
function output(event) {
alert("you pressed" + event.which);
}
``` |
1,312,524 | I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and put a key listener inside it.
Python:
```
def getInput():
while 1:
for event in pygame.event.get(): #returns a list of events from the keyboard/mouse
if event.type == KEYDOWN:
if event.key == "enter": # for example
do function()
return
elif event.key == "up":
do function2()
continue
else: continue # for clarity
```
In trying to find a way to implement this in DOM/javascript, I seem to just crash the page (I assume due to the While Loop), but I presume this is because my event handling is poorly written. Also, registering event handlers with "element.onkeydown = function;" difficult for me to wrap my head around, and setInterval(foo(), interval] hasn't brought me much success.
Basically, I want a "listening" loop to do a certain behavior for key X, but to break when key Y is hit. | 2009/08/21 | [
"https://Stackoverflow.com/questions/1312524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160854/"
] | For easier implementation of event handling I recommend you to use a library such as [Prototype](http://www.prototypejs.org/api/event) or [Jquery](http://docs.jquery.com/Events) (Note that both links take you to their respective Event handling documentation.
In order to use them you have to keep in mind 3 things:
* What DOM element you want to observe
* What Event you want to capture
* What action will the event trigger
This three points are mutually inclusive, meaning you need to take care of the 3 when writing the code.
So having this in mind, using Prototype, you could do this:
```
Event.observe($('id_of_the_element_to_observe'), 'keypress', function(ev) {
// the argument ev is the event object that has some useful information such
// as which keycode was pressed.
code_to_run;
});
```
Here is the code of a more useful example, a CharacterCounter (such as the one found in Twitter, but surely a lot less reliable ;) ):
```
var CharacterCounter = Class.create({
initialize: function(input, counter, max_chars) {
this.input = input;
this.counter = counter;
this.max_chars = max_chars;
Event.observe(this.input, 'keypress', this.keyPressHandler.bind(this));
Event.observe(this.input, 'keyup', this.keyUpHandler.bind(this));
},
keyUpHandler: function() {
words_left = this.max_chars - $F(this.input).length;
this.counter.innerHTML = words_left;
},
keyPressHandler: function(e) {
words_left = this.max_chars - $F(this.input).length;
if (words_left <= 0 && this.allowedChars(e.keyCode)) {
e.stop();
}
},
allowedChars: function(keycode) {
// 8: backspace, 37-40: arrow keys, 46: delete
allowed_keycodes = [ 8, 37, 38, 39, 40, 46 ];
if (allowed_keycodes.include(keycode)) {
return false;
}
return true
}
});
``` | ```
document.onkeydown = function(e) {
//do what you need to do
}
```
That's all it takes in javascript. You don't need to loop to wait for the event to happen, whenever the event occurs that function will be called, which in turn can call other functions, do whatever needs to be be done. Think of it as that instead of you having to wait for the event your looking for to happen, the event your looking for will let you know when it happens. |
1,312,524 | I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and put a key listener inside it.
Python:
```
def getInput():
while 1:
for event in pygame.event.get(): #returns a list of events from the keyboard/mouse
if event.type == KEYDOWN:
if event.key == "enter": # for example
do function()
return
elif event.key == "up":
do function2()
continue
else: continue # for clarity
```
In trying to find a way to implement this in DOM/javascript, I seem to just crash the page (I assume due to the While Loop), but I presume this is because my event handling is poorly written. Also, registering event handlers with "element.onkeydown = function;" difficult for me to wrap my head around, and setInterval(foo(), interval] hasn't brought me much success.
Basically, I want a "listening" loop to do a certain behavior for key X, but to break when key Y is hit. | 2009/08/21 | [
"https://Stackoverflow.com/questions/1312524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160854/"
] | In JavaScript, you give up control of the main loop. The browser runs the main loop and calls back down into your code when an event or timeout/interval occurs. You have to handle the event and then return so that the browser can get on with doing other things, firing events, and so on.
So you cannot have a ‘listening’ loop. The browser does that for you, giving you the event and letting you deal with it, but once you've finished handling the event you must return. You can't fall back into a different loop. This means you can't write step-by-step procedural code; if you have state that persists between event calls you must store it, eg. in a variable.
This approach cannot work:
```
<input type="text" readonly="readonly" value="" id="status" />
var s= document.getElementById('status');
s.value= 'Press A now';
while (true) {
var e= eventLoop.nextKeyEvent(); // THERE IS NO SUCH THING AS THIS
if (e.which=='a')
break
}
s.value= 'Press Y or N';
while (true) {
var e= eventLoop.nextKeyEvent();
if (e.which=='y') ...
```
Step-by-step code has to be turned inside out so that the browser calls down to you, instead of you calling up to the browser:
```
var state= 0;
function keypressed(event) {
var key= String.fromCharCode(event? event.which : window.event.keyCode); // IE compatibility
switch (state) {
case 0:
if (key=='a') {
s.value= 'Press Y or N';
state++;
}
break;
case 1:
if (key=='y') ...
break;
}
}
s.value= 'Press A now';
document.onkeypress= keypressed;
```
You can also make code look a little more linear and clean up some of the state stuff by using nested anonymous functions:
```
s.value= 'Press A now';
document.onkeypress= function(event) {
var key= String.fromCharCode(event? event.which : window.event.keyCode);
if (key=='a') {
s.value= 'Press Y or N';
document.onkeypress= function(event) {
var key= String.fromCharCode(event? event.which : window.event.keyCode);
if (key=='y') ...
};
}
};
``` | you should not use such loops in javascript. basically you do not want to block the browser from doing its job. Thus you work with events (onkeyup/down).
also instead of a loop you should use setTimeout if you want to wait a little and continue if something happened
you can do sth like that:
```
<html>
<script>
var dataToLoad = new Array('data1', 'data2', 'data3' );
var pos = 0;
function continueData(ev) {
// do whatever checks you need about key
var ele = document.getElementById("mydata");
if (pos < dataToLoad.length)
{
ele.appendChild(document.createTextNode(dataToLoad[pos]));
pos++;
}
}
</script>
<body onkeyup="continueData()"><div id="mydata"></div></body></html>
```
everytime a key is released the next data field is appended |
1,312,524 | I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and put a key listener inside it.
Python:
```
def getInput():
while 1:
for event in pygame.event.get(): #returns a list of events from the keyboard/mouse
if event.type == KEYDOWN:
if event.key == "enter": # for example
do function()
return
elif event.key == "up":
do function2()
continue
else: continue # for clarity
```
In trying to find a way to implement this in DOM/javascript, I seem to just crash the page (I assume due to the While Loop), but I presume this is because my event handling is poorly written. Also, registering event handlers with "element.onkeydown = function;" difficult for me to wrap my head around, and setInterval(foo(), interval] hasn't brought me much success.
Basically, I want a "listening" loop to do a certain behavior for key X, but to break when key Y is hit. | 2009/08/21 | [
"https://Stackoverflow.com/questions/1312524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160854/"
] | In JavaScript, you give up control of the main loop. The browser runs the main loop and calls back down into your code when an event or timeout/interval occurs. You have to handle the event and then return so that the browser can get on with doing other things, firing events, and so on.
So you cannot have a ‘listening’ loop. The browser does that for you, giving you the event and letting you deal with it, but once you've finished handling the event you must return. You can't fall back into a different loop. This means you can't write step-by-step procedural code; if you have state that persists between event calls you must store it, eg. in a variable.
This approach cannot work:
```
<input type="text" readonly="readonly" value="" id="status" />
var s= document.getElementById('status');
s.value= 'Press A now';
while (true) {
var e= eventLoop.nextKeyEvent(); // THERE IS NO SUCH THING AS THIS
if (e.which=='a')
break
}
s.value= 'Press Y or N';
while (true) {
var e= eventLoop.nextKeyEvent();
if (e.which=='y') ...
```
Step-by-step code has to be turned inside out so that the browser calls down to you, instead of you calling up to the browser:
```
var state= 0;
function keypressed(event) {
var key= String.fromCharCode(event? event.which : window.event.keyCode); // IE compatibility
switch (state) {
case 0:
if (key=='a') {
s.value= 'Press Y or N';
state++;
}
break;
case 1:
if (key=='y') ...
break;
}
}
s.value= 'Press A now';
document.onkeypress= keypressed;
```
You can also make code look a little more linear and clean up some of the state stuff by using nested anonymous functions:
```
s.value= 'Press A now';
document.onkeypress= function(event) {
var key= String.fromCharCode(event? event.which : window.event.keyCode);
if (key=='a') {
s.value= 'Press Y or N';
document.onkeypress= function(event) {
var key= String.fromCharCode(event? event.which : window.event.keyCode);
if (key=='y') ...
};
}
};
``` | you could attach an event listener to the window object like this
```
window.captureEvents(Event.KEYPRESS);
window.onkeypress = output;
function output(event) {
alert("you pressed" + event.which);
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.