qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 29
22k
| response_k
stringlengths 26
13.4k
| __index_level_0__
int64 0
17.8k
|
---|---|---|---|---|---|---|
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. | 2,706 |
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
``` | 2,707 |
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
``` | 2,709 |
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. | 2,710 |
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 | 2,713 |
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. | 2,714 |
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. | 2,715 |
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']});
}
});
``` | 2,716 |
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. | 2,721 |
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. | 2,722 |
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. | 2,725 |
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].) | 2,727 |
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\\")
``` | 2,730 |
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,739 |
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,740 |
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. | 2,745 |
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)
``` | 2,746 |
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) | 2,748 |
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. | 2,751 |
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
``` | 2,754 |
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;"
``` | 2,760 |
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.
``` | 2,761 |
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. | 2,764 |
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)])]
``` | 2,765 |
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
>
>
> | 2,766 |
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*. | 2,775 |
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
``` | 2,778 |
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, ]
``` | 2,779 |
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. | 2,780 |
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) | 2,781 |
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. | 2,782 |
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. | 2,786 |
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
``` | 2,787 |
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`. | 2,788 |
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}")
``` | 2,791 |
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. | 2,792 |
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)
``` | 2,795 |
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);
}
``` | 2,796 |
41,596,143 | I am trying to find an elegant way to calculate a bivariate normal CDF with python where one upper bound of the CDF is a function of two variables, of which one is a variable of the bivariate normal density (integral variable).
Example:
```
from scipy import integrate
import numpy as np
# First define f(x, y) as the bivariate normal distribution with fixed correlation p
p = 0.4
def f(x, y):
Q = x**2 + y**2 - 2*p*x*y
return 1/(2*np.pi*np.sqrt(1-p**2))*np.exp(-1/(2*(1-p**2))*Q)
# Define N2(a, b) as the cumulative bivariate normal distribution f where a is constant
# and b is a function of two variables
def N2(a, b):
prob, error = integrate.dblquad(f, np.NINF, a, lambda x: np.NINF, b)
return prob
# Upper bound function of 2 variables example where x is an integral variable
def upper_bound(x, v):
return 0.5*v*x
# My approach which doesn't work
# Calculate bivariate normal CDF for different values of v in the upper bound
results = [N2(1, upper_bound(x, v)) for v in np.linspace(0.01, 4, 200)]
```
Any ideas on how I could change my approach so the call to `upper_bound(x, v)` in
`results = [N2(1, upper_bound(x, v)) for v in np.linspace(0.01, 4, 200)]` would work? Other approaches to tackle the problem also welcome.
Edit: This is the integral I want to compute, where f(x,y) is the bivariate normal density function. Note that the actual upper bound f(x,v) = 0.5\*v\*x I want to compute is way more complicated, this is just as an example, therefore I do not want to compute it symbolically, for instance with sympy. Also, my goal is to compute the integral for a few hundreds different values of v.
The integral: [](https://i.stack.imgur.com/CV5Tr.png) | 2017/01/11 | [
"https://Stackoverflow.com/questions/41596143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3023486/"
] | Although it's slow this approach seems to work.
The first few lines, up to 'this should produce 1', are a sanity check. I wanted to verify that my approach would correctly calculate the volume under the density. It does.
I use a variance-covariance matrix to get the desired correlation of 0.4 and avoid writing my own pdf.
I curry functions in two places so that functions have only single parameters. This makes it possible to calculate the inner integral as a function of *x*. It also makes it possible to take the *v* parameter 'outside' the other calculations.
```
from toolz import curry
from scipy.stats import multivariate_normal
from scipy.integrate import quad
import numpy as np
@curry
def bivariate(x,y):
return multivariate_normal.pdf([x,y],cov=[[1,.4],[.4,1]])
def out_y(x):
marginal = bivariate(x)
return quad(marginal, np.NINF, np.PINF)[0]
# this should produce 1
print (quad(out_y, np.NINF, np.PINF)[0])
# now to what the OP wants
@curry
def inner_integral(v,x):
marginal = bivariate(x)
return quad(marginal, np.NINF, 0.5*v*x)[0]
inner_integral_for_one_v = inner_integral(0.8)
print (quad(inner_integral_for_one_v,np.NINF, 1)[0])
```
To use this code you would write something equivalent to:
```
for v in range(0,1,0.1):
inner_integral_for_one_v = inner_integral(v)
print (quad(inner_integral_for_one_v,np.NINF, 1)[0])
``` | I had to write an option model that was using a bivariate distribution in Python. However, I did not find a prebuilt function that was fast - some seem to be using the random scipy generator to emulate it with the multivariate function. BUT... if you really dig deep and see what the other financial packages are using, it's pretty much ALL code written by one guy, Alan Genz from the University of Washington. He pretty much writes everything in Fortan or MATLAB, and that's it. So if you look into packages that have the bivariate CDF you'll find his name and his code there (I found an old version in MATLAB actually). <http://www.math.wsu.edu/faculty/genz/software/software.html>
So why this isn't built into SciPy or NumPy already, I have no idea. But I rewrote it in several hours, using both MATLAB and Python to check the resulting code. He's solving with Gauss Legendre quadrature so this will always be much faster than a solution that uses a random number generator: <https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature>
```
# Alan Genz - original MATLAB code converted by Matt Slezak to Python
# http://www.math.wsu.edu/faculty/genz/software/matlab/bvnl.m
# Department of Mathematics
# Washington State University
# This is the bivariate CDF distribution
#
# dh 1st upper integration limit
# dk 2nd upper integration limit
# r correlation coefficient
import numpy as np
from scipy.stats import norm
def bivariate_cdf(dh, dk, r):
# dh and dk get signs flipped right away
dh = float(-dh)
dk = float(-dk)
if (dh == np.inf) or (dk == np.inf):
return 0
else:
if dh == - np.inf:
if dk == - np.inf:
return 1
else:
return norm.cdf(- dk)
if dk == - np.inf:
return norm.cdf(- dh)
else:
if r == 0:
return norm.cdf(- dh)*norm.cdf(- dk)
else:
tp=2*np.pi
h=dh
k=dk
hk=h*k
bvn=0
if abs(r) < 0.3:
w=np.array([0.1713244923791705,0.3607615730481384,0.4679139345726904])
x=np.array([0.9324695142031522,0.6612093864662647,0.238619186083197])
else:
if abs(r) < 0.75:
w=np.array([0.04717533638651177,0.1069393259953183,0.1600783285433464,0.2031674267230659,0.2334925365383547,0.2491470458134029])
x=np.array([0.9815606342467191,0.904117256370475,0.769902674194305,0.5873179542866171,0.3678314989981802,0.1252334085114692])
else:
w=np.array([0.01761400713915212,0.04060142980038694,0.06267204833410905,0.08327674157670475,0.1019301198172404,0.1181945319615184,0.1316886384491766,0.1420961093183821,0.1491729864726037,0.1527533871307259])
x=np.array([0.9931285991850949, 0.9639719272779138, 0.9122344282513259,0.8391169718222188, 0.7463319064601508, 0.6360536807265150,0.5108670019508271,0.3737060887154196,0.2277858511416451,0.07652652113349733])
w = np.concatenate((w, w), axis=0)
x = np.concatenate((1 - x, 1 + x), axis=0)
if abs(r) < 0.925:
hs=(h*h+k*k) / 2
asr=np.arcsin(r) / 2
sn=np.sin(asr*x)
bvn=np.dot(np.exp((sn*hk-hs)/(1-sn**2)),w.T)
bvn=bvn*asr/tp + norm.cdf(-h)*norm.cdf(-k)
else:
if r < 0:
k=- k
hk=- hk
if abs(r) < 1:
as1=1 - r ** 2
a=np.sqrt(as1)
bs=(h - k) ** 2
asr=- (bs / as1 + hk) / 2
c=(4 - hk) / 8
d=(12 - hk) / 80
if asr > - 100:
bvn= a*np.exp(asr)*(1-c*(bs-as1)*(1-d*bs)/3+c*d*as1**2)
if hk > - 100:
b=np.sqrt(bs)
sp=np.sqrt(tp)*norm.cdf(-b/a)
bvn=bvn - np.exp(-hk/2)*sp*b*( 1 - c*bs*(1-d*bs)/3 )
a=a / 2
xs=(a*x) ** 2
asr=- (bs / xs + hk) / 2
ix=asr > - 100
xs=xs[ix]
sp=( 1 + c*xs*(1+5*d*xs) )
rs=np.sqrt(1 - xs)
ep=np.exp(- (hk / 2)*xs / (1 + rs) ** 2) / rs
bvn=( a*( np.dot((np.exp(asr[ix])*(sp-ep)),w[ix].T) ) - bvn )/tp
if r > 0:
bvn=bvn + norm.cdf(- max(h,k))
else:
if h >= k:
bvn=- bvn
else:
if h < 0:
L=norm.cdf(k) - norm.cdf(h)
else:
L=norm.cdf(- h) - norm.cdf(- k)
bvn=L - bvn
return max(0,min(1,bvn))
``` | 2,806 |
47,784,693 | I am not able to handle to pass optional parameters in python `**kwargs`
```
def ExecuteyourQuery(self, queryStatement, *args, **kwargs):
if self.cursorOBJ is not None:
resultOBJ = self.cursorOBJ.execute(queryStatement, *args,**kwargs)
self.resultsVal = resultOBJ.fetchall()
```
---
The below statement works fine when I am calling the function
```
ExecuteyourQuery('select * from item_table where x = :x and y:y', x, y)
```
But when I give an extra argument which is not mentioned in the query, like
```
ExecuteyourQuery('select * from item_table where x = :x and y:y', x, y, z)
```
It returns 0 as output | 2017/12/13 | [
"https://Stackoverflow.com/questions/47784693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949381/"
] | When using args as the last parameter of your function, you can pass any number of **arguments** after the formal arguments, when existing. Args is a [tuple](https://www.tutorialspoint.com/python/python_tuples.htm).
```
def my_method(farg, *args):
print('FARG: ', farg)
print('ARGS: ', args)
my_method('Formal Argument', 1, 2, 3)
```
When using kwargs as the last parameter of your function, you can pass any number of **named arguments** after the formal arguments, when existing. Kwargs is a [dictionary](https://www.tutorialspoint.com/python/python_dictionary.htm).
```
def my_method(farg, **kwargs):
print('FARG: ', farg)
print('KWARGS: ', kwargs)
my_method('Formal Argument', kwarg_1 = 1, kwarg_2 = 2, kwarg_3 = 3)
```
When using both args and kwargs as the last parameteres of your function, you can pass any number of **arguments** (that will be mapped to args) and **named arguments** (that will be mapped to kwargs) after the formal arguments, when existing.
```
def my_method(farg, *args, **kwargs):
print('FARG: ', farg)
print('ARGS: ', args)
print('KWARGS: ', kwargs)
my_method('Formal Argument', 1, 2, 3, kwarg_1 = 1, kwarg_2 = 2, kwarg_3 = 3)
```
Try this out and see the results in your console, hopefully it will help you solve your original problem :) | another way to do this is by setting a default value for a parameter
```
def method(one, two, three=3):
print(one)
print(two)
if three != 3: # don't have to use it like this but it is a default value
print(three)
```
this set a default value if the parameter is not filled
if it is filled it will overrule the default value and use that
```
method(11, 22) # prints first two parameters
method(23, 54, 89) # prints all three
```
Not sure if this is what your looking for but it is another way | 2,807 |
28,750,643 | okay, im a new guy at all this, just randomly picked it up with my neighbor and we are both stuck at this. We have been following this tutorial([here](http://www.swaroopch.com/notes/python/#intro)) and have made it to 6.6 in the tutorial. I have searched the forums looking for a way to get passed my problem but all the of questions people have are too complex for me as of right now. I am running windows 8.1 on my laptop, i have python27. So here we go i put in,
```
>>> cd c:\\py
```
and i get
```
File "<stdin>", line 1
cd c:\\py
^
SyntaxError: invalid syntax
```
Then i searched around and found a thread saying to use os.chdir so i gave that a shot and got;
```
>>> os.chdir("c:\\py")
>>> os.getcwd()
'C:\\py'
>>>
```
So my guess is that it worked? so then i go ahead and try to run my program like it says to do, so i put in
```
python hello.py
```
and i get this in return
```
>>> python hello.py
File "<stdin>", line 1
python hello.py
^
SyntaxError: invalid syntax
```
I'm literally stuck, i have no clue what to do now. If someone can help me through this i will love you long time.
Thank you | 2015/02/26 | [
"https://Stackoverflow.com/questions/28750643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4611612/"
] | First of all, Python shell differs from system shell (cmd.exe). You try to run `python script.py` in Python interpreter instead of `cmd.exe`.
Open `cmd.exe` and type in `python script.py` to solve this. It'll run fine if it doesn't contain any errors. `cd c:\\` doesn't work due to the same reason.
First `quit()` or `exit()` the Python interpreter (type one of them right in it) then type the commands you want to execute (such as `cd`) into terminal.
If you want to run `code.py` in Python interpreter, you can `os.chdir("...")` to the directory where your script resides and type `import code`. That may not work if your script contains
```
if __name__=="__main__":
```
All in all, Python interpreter is for running Python code right in it and command prompt (terminal, cmd.exe) is for running other non-GUI programs and much more. | You are in the python interpreter which is an interactive shell. You can consider it "scratch paper" to test out or try different things.
To run your script :
quit()
in the command prompt run python.exe hello.py ( on windows.. on \*nix just python) | 2,808 |
74,158,560 | I am going through JavaScript course on freecodecamp and I came across this ['Steamroller' challenge](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller). Coming from python I really like one-liner solutions so I managed to write one for this challenge:
```
function steamrollArray(arr) {
return Array.isArray(arr) ? [].concat(...arr.map(steamrollArray)) : arr;
}
steamrollArray([1, [2], [3, [[4]]]]) // returns [1, 2, 3, 4]
```
The goal is basically to flatten an array of arbitrary depth. What puzzles me though (still new to JavaScript) is why seemingly similar code behaves very differently. Something I wrote at the beginning doesn't work, but code I arrived at through trial and (mostly) error works:
```
[...arr.map(steamrollArray)] // this doesn't work, returns an unchanged array
[].concat(...arr.map(steamrollArray)) // this works, returns a flat array
```
This seems strange to me because 'unfolding' the recursion would suggest it should be the other way around
```
[...arr.map(steamrollArray)]
[1, ...[2], ...[3, ...[...[4]]]] // this should work
[].concat(...arr.map(steamrollArray))
[].concat(...[1, [].concat(...[2]), [].concat(...[3, [].concat(...[].concat(...[4]))])]) // what 'is going on'
```
Can anyone please explain this behaviour? | 2022/10/21 | [
"https://Stackoverflow.com/questions/74158560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14625103/"
] | Quote from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat#description):
>
> Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; **for arrays ..., each element of the argument will be independently added to the final array.**
>
>
>
You can observe this behavior below; both give us `[1, 2, 3, 4, 5, 6]`, even though the second call uses an array.
```js
console.log([1, 2, 3].concat(4, 5, 6));
console.log([1, 2, 3].concat([4, 5, 6]));
```
If you want to concat the whole array, then you must wrap it in another array:
```js
console.log([1, 2, 3].concat([[4, 5, 6]])); // [1, 2, 3, [4, 5, 6]]
```
So how does this relate to your problem? Well... If we have an array like `[1, 2, [3, 4], 5, [6]]`, and we spread that into `concat`, we would get something like this:
```js
console.log([].concat(1, 2, [3, 4], 5, [6]));
```
... essentially "flattening" it by one level. Your function is recursive, so it flattens the array like this until it is completely flat. | So others answer your question, but here are simplified code
```js
const steamrollArray1 = arr => Array.isArray(arr) ? [].concat(...arr.map(steamrollArray1)) : arr;
const steamrollArray2 = arr => Array.isArray(arr) ? arr.flat(Infinity) : arr;
console.log(
steamrollArray1([1, [2], [3, [[4]]]])
); // returns [1, 2, 3, 4]
console.log(
steamrollArray2([1, [2], [3, [[4]]]])
); // returns [1, 2, 3, 4]
``` | 2,809 |
48,946,036 | I'm getting started with docker compose and have been working through the simple demo flask application. The thing is, I'm running this from inside of an organization that intercepts all communication in such a way that SSL errors are thrown right and left. They provide us with three root certificates we need to install, and I've generally got these working on my own machine, but I'm lost when it comes to getting these to work inside docker-compose deployments.
When I run docker-compose up, I get the following:
```
$ sudo docker-compose up
Creating network "project_default" with the default driver
Building web
Step 1/5 : FROM python:3.4-alpine
3.4-alpine: Pulling from library/python
81033e7c1d6a: Pull complete
9b61101706a6: Pull complete
415e2a07c89b: Pull complete
f22df7a3f000: Pull complete
8c16bf19c1f9: Pull complete
Digest: sha256:fe436cb066394d81cf49448a04dec7c765082445a500bc44f1ae5e8a455793bd
Status: Downloaded newer image for python:3.4-alpine
---> 5c72717ec319
Step 2/5 : ADD . /code
---> a5790c0e3e94
Removing intermediate container 052c614e41d0
Step 3/5 : WORKDIR /code
---> a2ea9acb3005
Removing intermediate container 77f2375ca0a6
Step 4/5 : RUN pip install -r requirements.txt
---> Running in 5f4fe856776d
Collecting flask (from -r requirements.txt (line 1))
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb0061f1d30>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/flask/
Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb0061f19b0>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/flask/
Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb0061f1828>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/flask/
Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb0061f1588>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/flask/
Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb0061f1390>: Failed to establish a new connection: [Errno -3] Try again',)': /simple/flask/
Could not find a version that satisfies the requirement flask (from -r requirements.txt (line 1)) (from versions: )
No matching distribution found for flask (from -r requirements.txt (line 1))
```
Pip fails to install anything.
The docker-compose.yml file looks like this:
```
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
```
And the main Dockerfile looks like this:
```
FROM python:3.4-alpine
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD ["python", "app.py"]
```
Is there any way to be able to make this work in this particular case? Is there a general solution to this sort of problem that would allow me to pass to any container deployed the SSL certificates and have them be used? | 2018/02/23 | [
"https://Stackoverflow.com/questions/48946036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3929175/"
] | This isn't really a docker-specific question: you are asking, in effect, "how do I install certificate authorities under Linux"? The answer is going to be the same regardless of whether you are running your ssl client inside or outside of a container.
Your Python image is based on alpine, and alpine uses the "ca-certificates" package to manage CA certificiates. To install your local CA certificates, you would need to (a) copy them into the `/usr/share/ca-certificates` directory and (b) run `update-ca-certificates`.
For example, adding something like this to your Dockerfile (before your `pip install`):
```
COPY company-ca.crt /usr/share/ca-certificates
RUN update-ca-certificates
``` | In my case, Host machine's MTU is 1450, and Docker's MTU is 1500.
Which causes docker set MSS to 1460, and then TLS "server hello" packet got bigger than 1450 bytes, so the Host machine discard it.
To see if it's your case too, run ifconfig on both you Docker container and your host machine. If Host's MTU is less than 1500, it's easy to run into this discarding packet situation. Especially in HTTPS, for that "server hello" needs to send the certificate, which is a big packet | 2,811 |
32,866,578 | I am trying to bastardise Django and Django REST Framework into a single module so see if it can work. So far, I have the following code:
```
###############################################################################
# SETTINGS
###############################################################################
import os
from django.apps import apps
from django.conf import settings
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if not settings.configured:
settings.configure(
DEBUG=True,
SECRET_KEY='thisisthesecretkey',
ROOT_URLCONF=__name__,
STATIC_URL='/static/',
STATICFILES_DIRS=(
os.path.join(BASE_DIR, "static"),
),
MIGRATION_MODULES = {'__main__': 'migrations'},
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'tinydb',
}
},
INSTALLED_APPS = (
'__main__',
'rest_framework',
'django.contrib.staticfiles',
),
)
apps.populate(settings.INSTALLED_APPS)
###############################################################################
# MODELS
###############################################################################
from django.db import models
class Book(models.Model):
ISBN = models.AutoField(primary_key=True)
author = models.CharField(max_length=100)
title = models.CharField(max_length=200)
description = models.CharField(max_length=500)
###############################################################################
# SERIALIZERS
###############################################################################
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
###############################################################################
# VIEWS
###############################################################################
class BooksView():
queryset = Book.objects.all()
serializer_class = BookSerializer
###############################################################################
# URLCONF
###############################################################################
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'books', BooksView)
urlpatterns = (
url(r'^$', include(router.urls)),
)
###############################################################################
# MANAGE
###############################################################################
import sys
if __name__ == "__main__":
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
```
Right now, the server runs and I see the API browser. However, when I try to create an object, I get the following trace:
```
>>> from __main__ import Book
>>> Book.objects.create(author='a1', title='t1', description='d1')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/query.py", line 348, in create
obj.save(force_insert=True, using=self.db)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 734, in save
force_update=force_update, update_fields=update_fields)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 762, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 846, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/base.py", line 885, in _do_insert
using=using, raw=raw)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/query.py", line 920, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 974, in execute_sql
cursor.execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/lwm/.virtualenvs/tiny-api/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: __main___book
```
`makemigrations` returns:
```
lwm$ python api.py makemigrations
No changes detected
```
I can run a migration:
```
lwm$ python api.py migrate
Operations to perform:
Synchronize unmigrated apps: __main__, staticfiles, rest_framework
Apply all migrations: (none)
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
No migrations to apply.
```
So. I think, since I don't have my `Book` model in a seperate app, there is no database table being created for it. Other than manually creating the tables, for example, using the `db_table` Meta field, I still wanted to get all the goodness of the ORM doing things for me.
Any ideas? | 2015/09/30 | [
"https://Stackoverflow.com/questions/32866578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you are using `docker run` to start your container, you have the `--add-host=""` argument which takes a hostname and an IP that get written to the container's `/etc/hosts`.
Your startup command would look like this:
```
docker run -d --add-host="domain-a.dev:192.168.0.10" [...]
```
Replace `192.168.0.10` with your computer's local IP address.
Don't use `127.0.0.1` as Docker will resolve that to the container not your computer. | I basically worked around this now by using <http://xip.io/>
By using urls like `sub.127.0.0.1.xip.io` I can connect to my local machine. My app only has to know that `127.0.0.1.xip.io` is treated as the "top level domain", and `sub` is the domain name without tld. (In a Ruby on Rails app this can be done by adjusting `config.action_dispatch.tld_length = 6` for example). | 2,816 |
69,920,403 | There is an HTML page that I would like to find the elements of two input types and press one button to log in with the help of selenium along with python3.
The problem is that I can't seem to find a way of doing this correctly.
The two texts and the button are in a form without an id or some tag, also I'm new on this one.
Below there is the HTML code with the two text fields (Email & Password) I need to find with the
selenium WebDriver along with the submit button.
HTML CODE:
```html
<form action="https://www.example.com/login" autocomplete="on" method="post" role="form">
<input type="hidden" name="_token" value="asdc">
<div class="form-group">
<input type="email" name="email" class="form-control " placeholder="Email"
value="" autofocus>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control " placeholder="Password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block" style1="height: 41px; font-size: 18px">Sign In</button></div>
</form>
```
Full HTML (URLS are changed) :
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="shortcut icon" type="image/png" href="https://example.com/favicon.png?"/>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,500,500i,700,700i,900"
rel="stylesheet">
<!-- Icon fonts -->
<link href="/fonts/fontawesome-pro/css/all.min.css" rel="stylesheet" type="text/css"/>
<!-- theme -->
<link id="theme-link" href="https://example.com/theme.css?&ver=a_230wednesday_10_nov_2021_135539_utc" rel="stylesheet" type="text/css"/>
<link href="https://example.com/login.css?&ver=a_230wednesday_10_nov_2021_135539_utc" rel="stylesheet" type="text/css"/>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag( 'js', new Date() );
gtag( 'config', "UA-101862321-1" );
</script>
</head>
<body>
<div class="limiter d-none">
<div class="container-login100">
<div class="wrap-login100 align-content-center align-items-center">
<div class="login100-pic js-tilt" data-tilt>
<img src="https://example.com/login-illustration.png?"/>
</div>
<div class="login100-form">
<div class="text-center mb-3">
<img src="https://example.com/logo-login.png?"/>
</div>
<div class="card-body p-4">
<form action="https://www.example.com/login" autocomplete="on" method="post" role="form">
<input type="hidden" name="_token" value="Somevalue">
<div class="form-group">
<input type="email" name="email"
class="form-control " placeholder="Email"
value="" autofocus>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control " placeholder="Password">
</div>
<div class="form-group">
<label class="custom-control custom-checkbox">
<input id="remember" name="remember" type="checkbox" class="custom-control-input" value="1">
<span class="custom-control-label">Remember me</span>
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block" style1="height: 41px; font-size: 18px">Sign In</button>
</div>
</form>
<div class="d-flex align-items-center form-group">
<hr class="flex-grow-1"/>
<div class="text-muted px-3">
OR CONNECT WITH
</div>
<hr class="flex-grow-1"/>
</div>
<a href="https://example.com/login/office" class="btn btn-default text-center btn-block">
<img src="https://example/office-365.png?&ver=a_230wednesday_10_nov_2021_135539_utc" class="img-fluid"/>
</a>
<div class="text-right mt-3">
<a href="https://www.example.com/password/reset">
Forgot Your Password?
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="login-cover-bg">
<div class="login-box d-flex justify-content-between align-items-center">
<div class="login100-pic">
<img src="https://example.com/logo-login.png?"/>
</div>
<div class="login100-form">
<div class="text-center mb-3">
<img src="https://example.com/logo-login.png?" class="img-fluid"/>
</div>
<div class="card-body p-4">
<form action="https://www.example.com/login" autocomplete="on" method="post" role="form">
<input type="hidden" name="_token" value="somevalue">
<div class="form-group">
<input type="email" name="email"
class="form-control " placeholder="Email"
value="" autofocus>
</div>
<div class="form-group">
<input type="password" name="password" class="form-control " placeholder="Password">
</div>
<div class="form-group">
<label class="custom-control custom-checkbox">
<input id="remember" name="remember" type="checkbox" class="custom-control-input" value="1">
<span class="custom-control-label">Remember me</span>
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block" style1="height: 41px; font-size: 18px">Sign In</button>
</div>
</form>
<div class="d-flex align-items-center form-group">
<hr class="flex-grow-1"/>
<div class="text-muted px-3">
OR CONNECT WITH
</div>
<hr class="flex-grow-1"/>
</div>
<a href="https://www.example.com/login/office" class="btn btn-default text-center btn-block">
<img src="office-365.png?&ver=a_230wednesday_10_nov_2021_135539_utc" class="img-fluid"/>
</a>
<div class="text-right mt-3">
<a href="https://www.example.com">
Forgot Your Password?
</a>
</div>
</div>
</div>
</div>
</div>
<!-- Core scripts From Bootstrap 4.4-->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" ></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" "></script>
</body>
</html>
```
My code so far:
```css
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("http://example.com/")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.LINK_TEXT, "Login to start working"))
)
element.click()
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Password']"))
)
element.click()
element.send_keys('random@random.com')
element.send_keys(Keys.ENTER)
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "Submit"))
)
element.click()
except Exception as exc:
driver.quit()
print(exc)
```
Thank you in advance! | 2021/11/10 | [
"https://Stackoverflow.com/questions/69920403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089615/"
] | I just changed your code from `presence_of_element_located` expected conditions to `presence_of_element_located`, corrected the locators and make some more things clearer. I hope now this should work.
```py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("http://example.com/")
email_input = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//input[@name='email']")))
email_input.click()
email_input.send_keys("your_email_value")
password_input = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//input[@name='password']")))
password_input.click()
password_input.send_keys("your_password_value")
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//button[@type='submit']"))).click()
``` | To click on the link *`Login to start working`*, next key in the credentials and finally to click on the *Submit* button you can use the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
```
driver.get("http://example.com/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Login to start working"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.form-group > input.form-control[name='email']"))).send_keys("random@random.com")
driver.find_element(By.CSS_SELECTOR, "div.form-group > input.form-control[name='password']").send_keys("random_password")
driver.find_element(By.XPATH, "//div[@class='form-group']/button[@class='btn btn-primary btn-block' and text()='Sign In']").click()
``` | 2,817 |
34,126,957 | I'm trying to install Pygame for python 3.5 32bit. I have learned that I can open the `.whl` files provided on the site by using the `pip` command. The problem is I've tried multiple ways doing this but with constant error.
```
python -m pip install pygame-1.9.2a0-cp35-none-win32.whl
'python' is not recognized as an internal or external command,
operable program or batch file.
```
The file I'm trying to install: `pygame-1.9.2a0-cp35-none-win32.whl`
My python program is located in my programs folder and everything else works fine. | 2015/12/07 | [
"https://Stackoverflow.com/questions/34126957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5481774/"
] | It would be helpful if your filtered the result set from the database by the customer's name, for example...
```
DefaultListModel dlm = new DefaultListModel();
try (PreparedStatement st = con.prepareStatement("select songpick from customer where customername=?")) {
String customerName = (String)jComboBox1.getSelectedItem();
st.setString(1, customerName);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
String songpick = rs.getString("songpick");
dlm.addElement(songpick);
}
jList1.setModel(dlm);
}
} catch (SQLException exp) {
exp.printStackTrace();
}
```
*ps: I don't know you database structure, so I'm only guessing at the relationships*
You should also take a look at [The try-with-resources Statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) for more details about how to manage your resources and the [SQL Where Clause](http://www.w3schools.com/sql/sql_where.asp) | You need to have a `WHERE` clause and set the value that you want to get from
E.g. `SELECT songpick FROM customer WHERE <columnName> = ?` and set the value of the that you need before the `executeQuery` statement with `st.setString(1, "Foo");` | 2,819 |
72,207,311 | ```
#!/bin/bash
data_dir=./all
for file_name in "$data_dir"/*
do
echo "$file_name"
python process.py "$file_name"
done
```
For example, this script processes the files sequentially in a directory in a 'for' loop. Is it possible to start multiple process.py instances to process files concurrently? I want to do this in a shell script. | 2022/05/11 | [
"https://Stackoverflow.com/questions/72207311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3943868/"
] | It's better to use [os.listdir](https://docs.python.org/3/library/os.html#os.listdir) and [subprocess.Popen](https://stackoverflow.com/a/7224186/5707560) to start new processes. | With **GNU Parallel**, like this:
```
parallel python process.py {} ::: all/*
```
It will run N jobs in parallel, where N is the number of CPU cores you have, or you can specify `-j4` to run on just 4, for example.
Many, many options for:
* logging,
* splitting/chunking inputs,
* tagging/separating output,
* staggering job starts,
* massaging input parameters,
* fail and retry handling,
* distributing jobs and data to other machines
* and so on...
Try putting `[gnu-parallel]` in the StackOverflow search box. | 2,820 |
17,694,780 | I'm a front-end dev struggling along with Django. I have the basics pretty much down but I've hit at wall at the following point.
I have a site running locally and also on a dev machine. Locally I've added an extra class model to an already existing app, registered it in the relevant admin.py and checked it in the settings. Locally the new class and relevant fields appear in admin but when I move this all to dev they're not appearing. The app is called 'publish'.
My method was as follows:
1. Created the new class in the publish > models.py file:
```
class Whitepaper(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=100, blank=True)
pub_date = models.DateField('date published')
section = models.ForeignKey('Section', related_name='whitepapers', blank=True, null=True)
description = models.CharField(max_length=1000)
docfile = models.FileField(upload_to="whitepapers/%Y/%m/%d", null=True, blank=True)
```
1. Updated and migrated the model with South using:
```
python manage.py schemamigration publish --auto
```
and
```
python manage.py migrate publish
```
1. Registered the class in the admin.py file:
```
from models import Section, Tag, Post, Whitepaper
from django.contrib import admin
from django import forms
admin.site.register(Whitepaper)
```
The app is listed in the settings.py file:
```
INSTALLED_APPS = (
...,
...,
'publish',
...,
)
```
As this is running on a dev server that's hosting a few other testing areas, restarting the whole thing is out of the question so I've been 'touching' the .wsgi file.
On my local version this got the model and fields showing up in the admin but on the dev server they are nowhere to be seen.
What am I missing?
Thanks ye brainy ones. | 2013/07/17 | [
"https://Stackoverflow.com/questions/17694780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321623/"
] | I figured out the problem. Turns out the login I was using to get into the admin didn't have superuser privileges. So I made a new one with:
```
python manage.py createsuperuser
```
After logging in with the new username and password I could see all my new shiny tables! | Are you sure touching `.wsgi` file does restart your app?
It looks like it doesn't.
Make sure the app is restarted. Find the evidence touching `.wsgi` file restarts the app maybe.
Since you don't provide any insight about how the dev server runs the apps, we won't be able to help you any further. | 2,822 |
54,172,462 | I'm new to ML and Colab. Trying to play around with the project at <https://github.com/tkarras/progressive_growing_of_gans> but having a hard time getting it running in Colab.
When I run the import\_example.py script from the project, I get immediate errors relating to Tensorflow not loading. So I tried stepping back and simply doing `import tensorflow as tf`. When I run this, I get the below errors. I've got the runtime set to GPU. I was getting the same issue yesterday with the Colab demo GPU code, but that's working today.
Can anyone give me any pointers? It seems like basic stuff that should just work in the environment.
```
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
57
---> 58 from tensorflow.python.pywrap_tensorflow_internal import *
59 from tensorflow.python.pywrap_tensorflow_internal import __version__
/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py in <module>()
27 return _mod
---> 28 _pywrap_tensorflow_internal = swig_import_helper()
29 del swig_import_helper
/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py in swig_import_helper()
23 try:
---> 24 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
25 finally:
/usr/lib/python3.6/imp.py in load_module(name, file, filename, details)
242 else:
--> 243 return load_dynamic(name, filename, file)
244 elif type_ == PKG_DIRECTORY:
/usr/lib/python3.6/imp.py in load_dynamic(name, path, file)
342 name=name, loader=loader, origin=path)
--> 343 return _load(spec)
344
ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-8-64156d691fe5> in <module>()
----> 1 import tensorflow as tf
/usr/local/lib/python3.6/dist-packages/tensorflow/__init__.py in <module>()
22
23 # pylint: disable=g-bad-import-order
---> 24 from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
25
26 try:
/usr/local/lib/python3.6/dist-packages/tensorflow/python/__init__.py in <module>()
47 import numpy as np
48
---> 49 from tensorflow.python import pywrap_tensorflow
50
51 from tensorflow.python.tools import component_api_helper
/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow.py in <module>()
72 for some common reasons and solutions. Include the entire stack trace
73 above this error message when asking for help.""" % traceback.format_exc()
---> 74 raise ImportError(msg)
75
76 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long
ImportError: Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/usr/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/usr/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
Failed to load the native TensorFlow runtime.
See https://www.tensorflow.org/install/errors
for some common reasons and solutions. Include the entire stack trace
above this error message when asking for help.
---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------
``` | 2019/01/13 | [
"https://Stackoverflow.com/questions/54172462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1958417/"
] | Even I was facing the same issue. Later I realized I forgot to enable **GPU** in notebook settings.
I enabled it and installed **TensorFlow-GPU** (GPU version).
You can find notebook settings in **Edit** > **Notebook Settings**.
[Here's the screenshot](https://i.stack.imgur.com/Sr7Hr.jpg) | You just have to read the error carefully:
>
> NOTE: If your import is failing due to a missing package, you can
> manually install dependencies using either !pip or !apt.
>
>
>
Try running:
```
!pip install tensorflow
```
inside notebook, and then rerun the cell with the import. | 2,823 |
24,253,977 | I am trying to remove non repeating characters from a list in python. e.g list = [1,1,2,3,3,3,5,6] should return [1,1,3,3].
My initial attempt was:
```
def tester(data):
for x in data:
if data.count(x) == 1:
data.remove(x)
return data
```
This will work for some inputs, but for [1,2,3,4,5], for example, it returns [2,4]. Could someone please explain why this occurs? | 2014/06/17 | [
"https://Stackoverflow.com/questions/24253977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636636/"
] | ```
l=[1,1,2,3,3,3,5,6]
[x for x in l if l.count(x) > 1]
[1, 1, 3, 3, 3]
```
Adds elements that appear at least twice in your list.
In your own code you need to change the line `for x in data` to `for x in data[:]:`
Using `data[:]` you are iterating over a `copy` of original list. | Another linear solution.
```
>>> data = [1, 1, 2, 3, 3, 3, 5, 6]
>>> D = dict.fromkeys(data, 0)
>>> for item in data:
... D[item] += 1
...
>>> [item for item in data if D[item] > 1]
[1, 1, 3, 3, 3]
``` | 2,828 |
45,062,219 | Is there a simpler way possible to just add numbers which are regarded as strings but also integer by python? It doesn't let me add it, maybe because of the way I converted the integer to string and then a list?
I have done this so far:
```
function_menu()
print()
numbers = str(number)
lists = []
lists.extend(numbers)
addition = sum(lists)
average = addition / len(lists)
print(average)
``` | 2017/07/12 | [
"https://Stackoverflow.com/questions/45062219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8295906/"
] | You could remove `0`s from the list. If the list becomes empty, return `0`, the product otherwise:
```
>>> no_zeroes = [value for value in values if value > 0]
>>> no_zeroes
[1.0, 3.4]
>>> reduce(lambda x, y : y*x, no_zeroes) if no_zeroes else 0
3.4
```
Note that from a mathematical point of view, the product of an empy list should probably be `1`. In that case, you could write :
```
reduce(lambda x, y : y*x, no_zeroes, 1)
``` | if you use numpy arrays you can filter out the zero values:
```
import numpy as np
vals = np.array([0.0, 0.0, 0.0, 0.0])
no_zeros = vals[vals>0]
if no_zeros:
print( np.prod(no_zeros))
else:
print(0.0)
``` | 2,838 |
37,622,153 | I would like to compute all (different) intersections of a collection of finite sets of integers (here implemented as a list of lists) in python (to avoid confusion, a formal definition is at the end of the question):
```
> A = [[0,1,2,3],[0,1,4],[1,2,4],[2,3,4],[0,3,4]]
> all_intersections(A) # desired output
[[], [0], [1], [2], [3], [4], [0, 1], [0, 3], [0, 4], [1, 2], [1, 4], [2, 3], [2, 4], [3, 4], [0, 1, 4], [0, 3, 4], [1, 2, 4], [2, 3, 4], [0, 1, 2, 3]]
```
I have an algorithm that does it iteratively, but it is rather slow (should I post it?), a test case would be
```
[[0, 1, 2, 3, 4, 9], [0, 1, 4, 5, 6, 10], [0, 2, 4, 5, 7, 11], [1, 3, 4, 6, 8, 12], [2, 3, 4, 7, 8, 13], [4, 5, 6, 7, 8, 14], [0, 1, 9, 10, 15, 16], [0, 2, 9, 11, 15, 17], [1, 3, 9, 12, 16, 18], [2, 3, 9, 13, 17, 18], [9, 15, 16, 17, 18, 19], [0, 5, 10, 11, 15, 20], [1, 6, 10, 12, 16, 21], [10, 15, 16, 19, 20, 21], [5, 6, 10, 14, 20, 21], [11, 15, 17, 19, 20, 22], [5, 7, 11, 14, 20, 22], [2, 7, 11, 13, 17, 22], [7, 8, 13, 14, 22, 23], [3, 8, 12, 13, 18, 23], [13, 17, 18, 19, 22, 23], [14, 19, 20, 21, 22, 23], [6, 8, 12, 14, 21, 23], [12, 16, 18, 19, 21, 23]]
```
which takes me about 2.5 secs to compute.
>
> Any ideas how to do it fast?
>
>
>
Formal definition (actually hard without latex mode): let A = {A1,...,An} be a finite set of finite sets Ai of non-negative integers. The output should then be the set { intersection of the sets in B : B subset of A }.
So the formal algorithm would be to take the union of all intersections of all subsets of A. But that's clearly taking forever.
Many thanks! | 2016/06/03 | [
"https://Stackoverflow.com/questions/37622153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442181/"
] | Here is a recursive solution. It is almost instantaneous on your test example:
```
def allIntersections(frozenSets):
if len(frozenSets) == 0:
return []
else:
head = frozenSets[0]
tail = frozenSets[1:]
tailIntersections = allIntersections(tail)
newIntersections = [head]
newIntersections.extend(tailIntersections)
newIntersections.extend(head & s for s in tailIntersections)
return list(set(newIntersections))
def all_intersections(lists):
sets = allIntersections([frozenset(s) for s in lists])
return [list(s) for s in sets]
```
**On Edit** Here is a cleaner, nonrecursive implementation of the same ideas.
The problem is easiest if you define the intersection of an empty collection of sets to be the universal set, and an adequate universal set can be obtained by taking the union of all elements. This is a standard move in lattice-theory, and is dual to taking the union of an empty collection of sets to be the empty set. You could always throw away this universal set if you don't want it:
```
def allIntersections(frozenSets):
universalSet = frozenset.union(*frozenSets)
intersections = set([universalSet])
for s in frozenSets:
moreIntersections = set(s & t for t in intersections)
intersections.update(moreIntersections)
return intersections
def all_intersections(lists):
sets = allIntersections([frozenset(s) for s in lists])
return [list(s) for s in sets]
```
The reason that this is so fast with your test example is that, even though your collection has 24 sets, hence having 2\*\*24 (16.8 million) potential intersections, there are in fact only 242 (or 241 if you don't count the empty intersection) distinct intersections. Thus the number of intersections in each pass through the loop is in the low hundreds at most.
It is possible to pick 24 sets so that all of the 2\*\*24 possible intersections are in fact different, so it is easy to see that the worst-case behavior is exponential. But if, as in your test example, the number of intersections is small, this approach will allow you to rapidly compute them.
A potential optimization might be to sort the sets in increasing size before you loop over them. Processing the smaller sets up front might result in more empty intersections appearing earlier, thus keeping the total number of distinct intersections smaller until towards the end of the loop. | Iterative solution that takes about 3.5 ms on my machine for your large test input:
```
from itertools import starmap, product
from operator import and_
def all_intersections(sets):
# Convert to set of frozensets for uniquification/type correctness
last = new = sets = set(map(frozenset, sets))
# Keep going until further intersections add nothing to results
while new:
# Compute intersection of old values with newly found values
new = set(starmap(and_, product(last, new)))
last = sets.copy() # Save off prior state
new -= last # Determine truly newly added values
sets |= new # Accumulate newly added values in complete set
# No more intersections being generated, convert results to canonical
# form, list of lists, where each sublist is displayed in order, and
# the top level list is ordered first by size of sublist, then by contents
return sorted(map(sorted, sets), key=lambda x: (len(x), x))
```
Basically, it just keeps doing two way intersections among the old result set and the newly found intersections until a round of intersections doesn't change anything, then it's done.
**Note:** This is not actually the best solution (recursion is sufficiently better algorithmically to win on the test data, where John Coleman's solution, after adding sorting to the outer wrapper so it matches format, takes about 0.94 ms, vs. 3.5 ms for mine). I'm mostly providing it as an example of solving the problem in other ways. | 2,846 |
61,657,685 | First project from work and got stuck with this tedious error on Ubuntu.
Currently using node -v 13.8.0, installed python 2.7.17, GCC 7.5.0
also checked node-gyp npm page and installed all python and gcc dependencies.
here is my package.json file
```
"dependencies": {
"apn": "^2.1.5",
"async": "^1.5.2",
"bcrypt-nodejs": "^0.0.3",
"body-parser": "^1.15.1",
"compression": "^1.6.2",
"consolidate": "^0.14.5",
"cookie-parser": "^1.4.1",
"cors": "^2.8.4",
"dotenv": "^2.0.0",
"express": "^4.13.4",
"express-validator": "^2.20.4",
"fcm-node": "^1.2.0",
"geocoder": "^0.2.3",
"jimp": "^0.2.28",
"jsonwebtoken": "^5.7.0",
"moment": "^2.12.0",
"moment-timezone": "^0.5.14",
"mongoose": "^4.4.8",
"mongoose-unique-validator": "^1.0.6",
"morgan": "^1.7.0",
"multer": "^1.3.0",
"mustache": "^2.3.0",
"node-cron": "^1.2.1",
"node-excel-export": "^1.4.4",
"nodemailer": "^2.3.0",
"nodemailer-mailgun-transport": "^1.3.5",
"nodemailer-smtp-transport": "^2.7.4",
"qr-image": "^3.2.0",
"randomstring": "^1.1.5",
"request": "^2.69.0",
"soap": "^0.23.0",
"socket.io": "^2.0.3",
"strong-soap": "^1.5.0",
"swagger-jsdoc": "^1.9.3",
"swagger-ui-express": "^1.0.7",
"time": "^0.12.0",
"twilio": "^3.9.1",
"underscore": "^1.8.3",
"uuid": "^3.2.1",
"ws.js": "^2.0.23"
},
"devDependencies": {},
"engines": {
"node": "6.9.5"
}
```
```
npm install
> ursa@0.9.4 install /home/shubham/Desktop/hotel/demo_hotellife_api/node_modules/ursa
> node-gyp rebuild
make: Entering directory '/home/shubham/Desktop/hotel/demo_hotellife_api/node_modules/ursa/build'
CXX(target) Release/obj.target/ursaNative/src/ursaNative.o
In file included from ../../nan/nan.h:192:0,
from ../src/ursaNative.h:10,
from ../src/ursaNative.cc:3:
../../nan/nan_maybe_43_inl.h: In function ‘Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object>, v8::Local<v8::Value>, v8::Local<v8::Value>, v8::PropertyAttribute)’:
../../nan/nan_maybe_43_inl.h:112:15: error: ‘class v8::Object’ has no member named ‘ForceSet’
return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);
^~~~~~~~
In file included from ../../nan/nan_converters.h:67:0,
from ../../nan/nan.h:197,
from ../src/ursaNative.h:10,
from ../src/ursaNative.cc:3:
../../nan/nan_converters_43_inl.h: In static member function ‘static Nan::imp::ToFactoryBase<v8::Boolean>::return_t Nan::imp::ToFactory<v8::Boolean>::convert(v8::Local<v8::Value>)’:
../../nan/nan_converters_43_inl.h:18:69: error: no matching function for call to ‘v8::Value::ToBoolean(v8::Local<v8::Context>)’
val->To ## TYPE(v8::Isolate::GetCurrent()->GetCurrentContext()) \
^
../../nan/nan_converters_43_inl.h:22:1: note: in expansion of macro ‘X’
X(Boolean)
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2750:44: note: candidate: v8::MaybeLocal<v8::String> v8::Value::ToString(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
^~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2750:44: note: candidate expects 1 argument, 0 provided
In file included from ../src/time.cc:5:0:
../../nan/nan.h:921:74: error: no matching function for call to ‘v8::String::WriteUtf8(char*&, int, int, const int&)’
length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2947:7: note: candidate: int v8::String::WriteUtf8(v8::Isolate*, char*, int, int*, int) const
int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
^~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2947:7: note: no known conversion for argument 1 from ‘char*’ to ‘v8::Isolate*’
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘v8::Local<v8::Value> Nan::Callback::Call_(v8::Isolate*, v8::Local<v8::Object>, int, v8::Local<v8::Value>*) const’:
../../nan/nan.h:1479:5: warning: ‘v8::Local<v8::Value> node::MakeCallback(v8::Isolate*, v8::Local<v8::Object>, v8::Local<v8::Function>, int, v8::Local<v8::Value>*)’ is deprecated: Use MakeCallback(..., async_context) [-Wdeprecated-declarations]
));
^
In file included from ../../nan/nan.h:49:0,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:180:50: note: declared here
NODE_EXTERN v8::Local<v8::Value> MakeCallback(
^
/home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:99:42: note: in definition of macro ‘NODE_DEPRECATED’
__attribute__((deprecated(message))) declarator
^~~~~~~~~~
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘void Nan::AsyncWorker::SaveToPersistent(const char*, const v8::Local<v8::Value>&)’:
../../nan/nan.h:1533:64: error: no matching function for call to ‘v8::Object::Set(v8::Local<v8::String>, const v8::Local<v8::Value>&)’
New(persistentHandle)->Set(New(key).ToLocalChecked(), value);
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3547:37: note: candidate: v8::Maybe<bool> v8::Object::Set(v8::Local<v8::Context>, v8::Local<v8::Value>, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3547:37: note: candidate expects 3 arguments, 2 provided
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3550:37: note: candidate: v8::Maybe<bool> v8::Object::Set(v8::Local<v8::Context>, uint32_t, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3550:37: note: candidate expects 3 arguments, 2 provided
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘void Nan::AsyncWorker::SaveToPersistent(const v8::Local<v8::String>&, const v8::Local<v8::Value>&)’:
../../nan/nan.h:1539:42: error: no matching function for call to ‘v8::Object::Set(const v8::Local<v8::String>&, const v8::Local<v8::Value>&)’
New(persistentHandle)->Set(key, value);
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3547:37: note: candidate: v8::Maybe<bool> v8::Object::Set(v8::Local<v8::Context>, v8::Local<v8::Value>, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3547:37: note: candidate expects 3 arguments, 2 provided
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3550:37: note: candidate: v8::Maybe<bool> v8::Object::Set(v8::Local<v8::Context>, uint32_t, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3550:37: note: candidate expects 3 arguments, 2 provided
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘void Nan::AsyncWorker::SaveToPersistent(uint32_t, const v8::Local<v8::Value>&)’:
../../nan/nan.h:1545:44: error: no matching function for call to ‘v8::Object::Set(uint32_t&, const v8::Local<v8::Value>&)’
New(persistentHandle)->Set(index, value);
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3547:37: note: candidate: v8::Maybe<bool> v8::Object::Set(v8::Local<v8::Context>, v8::Local<v8::Value>, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3547:37: note: candidate expects 3 arguments, 2 provided
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3550:37: note: candidate: v8::Maybe<bool> v8::Object::Set(v8::Local<v8::Context>, uint32_t, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3550:37: note: candidate expects 3 arguments, 2 provided
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘v8::Local<v8::Value> Nan::AsyncWorker::GetFromPersistent(const char*) const’:
../../nan/nan.h:1551:61: error: no matching function for call to ‘v8::Object::Get(v8::Local<v8::String>)’
New(persistentHandle)->Get(New(key).ToLocalChecked()));
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3594:43: note: candidate: v8::MaybeLocal<v8::Value> v8::Object::Get(v8::Local<v8::Context>, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3594:43: note: candidate expects 2 arguments, 1 provided
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3597:43: note: candidate: v8::MaybeLocal<v8::Value> v8::Object::Get(v8::Local<v8::Context>, uint32_t)
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3597:43: note: candidate expects 2 arguments, 1 provided
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘v8::Local<v8::Value> Nan::AsyncWorker::GetFromPersistent(const v8::Local<v8::String>&) const’:
../../nan/nan.h:1557:55: error: no matching function for call to ‘v8::Object::Get(const v8::Local<v8::String>&)’
return scope.Escape(New(persistentHandle)->Get(key));
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3594:43: note: candidate: v8::MaybeLocal<v8::Value> v8::Object::Get(v8::Local<v8::Context>, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3594:43: note: candidate expects 2 arguments, 1 provided
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3597:43: note: candidate: v8::MaybeLocal<v8::Value> v8::Object::Get(v8::Local<v8::Context>, uint32_t)
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3597:43: note: candidate expects 2 arguments, 1 provided
In file included from ../src/time.cc:5:0:
../../nan/nan.h: In member function ‘v8::Local<v8::Value> Nan::AsyncWorker::GetFromPersistent(uint32_t) const’:
../../nan/nan.h:1562:57: error: no matching function for call to ‘v8::Object::Get(uint32_t&)’
return scope.Escape(New(persistentHandle)->Get(index));
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3594:43: note: candidate: v8::MaybeLocal<v8::Value> v8::Object::Get(v8::Local<v8::Context>, v8::Local<v8::Value>)
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3594:43: note: candidate expects 2 arguments, 1 provided
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3597:43: note: candidate: v8::MaybeLocal<v8::Value> v8::Object::Get(v8::Local<v8::Context>, uint32_t)
V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
^~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:3597:43: note: candidate expects 2 arguments, 1 provided
In file included from /usr/include/c++/7/cassert:44:0,
from /home/shubham/.cache/node-gyp/13.8.0/include/node/node_object_wrap.h:26,
from ../../nan/nan.h:51,
from ../src/time.cc:5:
../../nan/nan_object_wrap.h: In destructor ‘virtual Nan::ObjectWrap::~ObjectWrap()’:
../../nan/nan_object_wrap.h:24:25: error: ‘class Nan::Persistent<v8::Object>’ has no member named ‘IsNearDeath’
assert(persistent().IsNearDeath());
^
In file included from ../../nan/nan.h:2222:0,
from ../src/time.cc:5:
../../nan/nan_object_wrap.h: In member function ‘void Nan::ObjectWrap::MakeWeak()’:
../../nan/nan_object_wrap.h:67:18: error: ‘class Nan::Persistent<v8::Object>’ has no member named ‘MarkIndependent’
persistent().MarkIndependent();
^~~~~~~~~~~~~~~
In file included from /usr/include/c++/7/cassert:44:0,
from /home/shubham/.cache/node-gyp/13.8.0/include/node/node_object_wrap.h:26,
from ../../nan/nan.h:51,
from ../src/time.cc:5:
../../nan/nan_object_wrap.h: In static member function ‘static void Nan::ObjectWrap::WeakCallback(const v8::WeakCallbackInfo<Nan::ObjectWrap>&)’:
../../nan/nan_object_wrap.h:124:26: error: ‘class Nan::Persistent<v8::Object>’ has no member named ‘IsNearDeath’
assert(wrap->handle_.IsNearDeath());
^
../src/time.cc: At global scope:
../src/time.cc:12:20: error: ‘Handle’ has not been declared
static void Init(Handle<Object> target) {
^~~~~~
../src/time.cc:12:26: error: expected ‘,’ or ‘...’ before ‘<’ token
static void Init(Handle<Object> target) {
^
../src/time.cc: In static member function ‘static void Time::Init(int)’:
../src/time.cc:16:20: error: ‘target’ was not declared in this scope
Nan::SetMethod(target, "time", Time_);
^~~~~~
../src/time.cc:16:20: note: suggested alternative: ‘tzset’
Nan::SetMethod(target, "time", Time_);
^~~~~~
tzset
../src/time.cc: In static member function ‘static Nan::NAN_METHOD_RETURN_TYPE Time::Localtime(Nan::NAN_METHOD_ARGS_TYPE)’:
../src/time.cc:87:64: error: no matching function for call to ‘v8::Value::IntegerValue()’
time_t rawtime = static_cast<time_t>(info[0]->IntegerValue());
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2774:40: note: candidate: v8::Maybe<long int> v8::Value::IntegerValue(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
^~~~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2774:40: note: candidate expects 1 argument, 0 provided
../src/time.cc: In static member function ‘static Nan::NAN_METHOD_RETURN_TYPE Time::Mktime(Nan::NAN_METHOD_ARGS_TYPE)’:
../src/time.cc:141:103: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_sec = Nan::Get(arg, Nan::New("seconds").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc:142:103: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_min = Nan::Get(arg, Nan::New("minutes").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc:143:101: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_hour = Nan::Get(arg, Nan::New("hours").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc:144:106: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_mday = Nan::Get(arg, Nan::New("dayOfMonth").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc:145:101: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_mon = Nan::Get(arg, Nan::New("month").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc:146:100: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_year = Nan::Get(arg, Nan::New("year").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc:147:113: error: no matching function for call to ‘v8::Value::Int32Value()’
tmstr.tm_isdst = Nan::Get(arg, Nan::New("isDaylightSavings").ToLocalChecked()).ToLocalChecked()->Int32Value();
^
In file included from /home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:63:0,
from ../../nan/nan.h:49,
from ../src/time.cc:5:
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate: v8::Maybe<int> v8::Value::Int32Value(v8::Local<v8::Context>) const
V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
^~~~~~~~~~
/home/shubham/.cache/node-gyp/13.8.0/include/node/v8.h:2778:40: note: candidate expects 1 argument, 0 provided
../src/time.cc: At global scope:
../src/time.cc:156:21: error: variable or field ‘init’ declared void
static void init (Handle<Object> target) {
^~~~~~
../src/time.cc:156:21: error: ‘Handle’ was not declared in this scope
../src/time.cc:156:21: note: suggested alternative: ‘rand_r’
static void init (Handle<Object> target) {
^~~~~~
rand_r
../src/time.cc:156:34: error: expected primary-expression before ‘>’ token
static void init (Handle<Object> target) {
^
../src/time.cc:156:36: error: ‘target’ was not declared in this scope
static void init (Handle<Object> target) {
^~~~~~
../src/time.cc:156:36: note: suggested alternative: ‘tzset’
static void init (Handle<Object> target) {
^~~~~~
tzset
In file included from ../../nan/nan.h:49:0,
from ../src/time.cc:5:
../src/time.cc:159:21: error: ‘init’ was not declared in this scope
NODE_MODULE(time, init)
^
/home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:610:36: note: in definition of macro ‘NODE_MODULE_X’
(node::addon_register_func) (regfunc), \
^~~~~~~
../src/time.cc:159:3: note: in expansion of macro ‘NODE_MODULE’
NODE_MODULE(time, init)
^~~~~~~~~~~
../src/time.cc:159:21: note: suggested alternative: ‘int’
NODE_MODULE(time, init)
^
/home/shubham/.cache/node-gyp/13.8.0/include/node/node.h:610:36: note: in definition of macro ‘NODE_MODULE_X’
(node::addon_register_func) (regfunc), \
^~~~~~~
../src/time.cc:159:3: note: in expansion of macro ‘NODE_MODULE’
NODE_MODULE(time, init)
^~~~~~~~~~~
time.target.mk:113: recipe for target 'Release/obj.target/time/src/time.o' failed
make: *** [Release/obj.target/time/src/time.o] Error 1
make: Leaving directory '/home/shubham/Desktop/hotel/demo_hotellife_api/node_modules/time/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack at ChildProcess.emit (events.js:321:20)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Linux 5.0.0-37-generic
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/shubham/Desktop/hotel/demo_hotellife_api/node_modules/time
gyp ERR! node -v v13.8.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
npm WARN Trump@1.0.0 No repository field.
npm WARN Trump@1.0.0 No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: ursa@0.9.4 (node_modules/ursa):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: ursa@0.9.4 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! time@0.12.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the time@0.12.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/shubham/.npm/_logs/2020-05-07T11_31_00_132Z-debug.log
```
**Things I tried**
downgraded to various node versions like to v8.11.0- same problem
downgraded node to v6.9.5 as mentioned in package.json file. but there started getting various
JS versioning errors like '...Object' not supported. not supporting es6.
installed node-gyp globally, still nothing resolved.
please help me on my maiden command of my maiden project | 2020/05/07 | [
"https://Stackoverflow.com/questions/61657685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11847762/"
] | The problem you have is the **time** package which is outdated <https://www.npmjs.com/package/time>.
There are some different solutions depending on why are you using that package, you could use a different library/package to handle dates and time, but you will probably need to refactor some code.
Try removing this dependency from the **package.json**, `"time": "^0.12.0"` and running `npm install` again to see if it runs correctly.
Then change the dependency to use an updated fork of `time` like this one
<https://github.com/riyadshauk/node-time>. Your `time` dependency on **package.json** should look like this
```
"dependencies": {
"time": "github:riyadshauk/node-time"
}
```
Your full dependencies should be like this (assuming you haven't installed/removed anything since your question), the only change is on `time`, the rest is the same.
I used node v13.7.0
```
"dependencies": {
"apn": "^2.1.5",
"async": "^1.5.2",
"bcrypt-nodejs": "^0.0.3",
"body-parser": "^1.15.1",
"compression": "^1.6.2",
"consolidate": "^0.14.5",
"cookie-parser": "^1.4.1",
"cors": "^2.8.4",
"dotenv": "^2.0.0",
"express": "^4.13.4",
"express-validator": "^2.20.4",
"fcm-node": "^1.2.0",
"geocoder": "^0.2.3",
"jimp": "^0.2.28",
"jsonwebtoken": "^5.7.0",
"moment": "^2.12.0",
"moment-timezone": "^0.5.14",
"mongoose": "^4.4.8",
"mongoose-unique-validator": "^1.0.6",
"morgan": "^1.7.0",
"multer": "^1.3.0",
"mustache": "^2.3.0",
"node-cron": "^1.2.1",
"node-excel-export": "^1.4.4",
"nodemailer": "^2.3.0",
"nodemailer-mailgun-transport": "^1.3.5",
"nodemailer-smtp-transport": "^2.7.4",
"qr-image": "^3.2.0",
"randomstring": "^1.1.5",
"request": "^2.69.0",
"soap": "^0.23.0",
"socket.io": "^2.0.3",
"strong-soap": "^1.5.0",
"swagger-jsdoc": "^1.9.3",
"swagger-ui-express": "^1.0.7",
"time": "github:riyadshauk/node-time",
"twilio": "^3.9.1",
"underscore": "^1.8.3",
"uuid": "^3.2.1",
"ws.js": "^2.0.23"
}
``` | This works for me
```
npm install -g npm-check-updates
npm-check-updates -u
npm install
``` | 2,847 |
11,067,697 | I'm building a calendar-based web app, and am in great need of a javascript Date library-- something similar to python's [dateutil](http://labix.org/python-dateutil). I came across [DateJs](http://www.datejs.com/). The functionality looks great. My only hesitance is that the repo hasn't been touched since early 2008. Usually this is a (very) bad sign for an open source project. So I wanted to check whether people currently use, trust and recommend this library, or whether its just an abandoned set of good intentions with good SEO. If not, is there another comprehensive JS date library I should be looking at? | 2012/06/16 | [
"https://Stackoverflow.com/questions/11067697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/652693/"
] | I'd like to recommend [momentjs](http://momentjs.com/) - a very lightweight, yet surprisingly capable Date JS library. ) | DateJS works wonders for us. I am not really concerned that development seems to have stalled as it is pretty complete as-is. | 2,848 |
1,314,717 | In python, I can construct my [optparse](http://docs.python.org/library/optparse.html) instance such that it will automatically filter out the options and non-option/flags into two different buckets:
```
(options, args) = parser.parse_args()
```
With boost::program\_options, how do I retrieve a list of tokens which are the remaining non-option and non-flag tokens?
e.g. If my program has flags
```
--foo
--bar BAR
```
and I then pass in the command line:
```
--foo hey --bar BAR you
```
how can I get a list comprised solely of tokens "hey" and "you" | 2009/08/22 | [
"https://Stackoverflow.com/questions/1314717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20712/"
] | IIRC, you have to use a combination of [`positional_options_description`](http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/overview.html#id2892937) and [*hidden options*](http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/howto.html#id2893967). The idea is to (1) add a normal option and give it a name, maybe something like `--positional=ARG`, (2) don't include that option in the help description, (3) configure `command_line_parser` to treat all positional arguments as if `--positional` was specified, and (4) retrieve the positional arguments using `vm["positional"].as< std::vector<std::string> >()`.
There is probably an example somewhere in the source tree but I don't have it on this machine right now. | Here is an example:
```
namespace po = boost::program_options;
po::positional_options_description m_positional;
po::options_description m_cmdLine;
po::variables_map m_variables;
m_cmdLine.add_options()
(/*stuff*/)
("input", po::value<vector<string> >()->composing(), "")
;
m_positional.add("input", -1);
po::parsed_options parsed = po::command_line_parser(argc, argv)
.options(m_cmdLine)
.positional(m_positional)
.allow_unregistered()
.run();
// store, notify, etc
```
Then just get "input" named options as vector of strings and you are all set. | 2,851 |
59,801,340 | I have been attempting to make a small python program to monitor and return ping results from different servers. I have reached a point where pinging each device in the sequence has become inefficient and lacks performance. I want to continuously ping each one of my targets at the same time on my python.
What would the best approach to this be? Thanks for your time
```
def get_latency(ip_address, port):
from tcp_latency import measure_latency
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
latency = str(measure_latency(host=ip_address, port=port, runs=1, timeout=1))[1:-1]
#add to table and upload to database function()
ip_address_list = [('google.com', '80'), ('bing.com', '80')]
#Problem
#run function simultaneously but with different arguments
get_latency(ip_address_list[0][0], ip_address_list[0][1])
get_latency(ip_address_list[1][0], ip_address_list[1][1])
``` | 2020/01/18 | [
"https://Stackoverflow.com/questions/59801340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12737497/"
] | First of all you can't have many id's with the same value in a one html page. Cause it will result an error in the future while your doing a lot of code to it. Please change your btnedt to a class not an id. then change your script like this.
```
<script>
$(document).ready(function () {
$(document).on('click', '.btnedt', function() {
// alert($(this).closest('tr').find('.contact_name').text());
$("#newModal").modal("show");
});
});
</script>
```
if modal is already the issue. Then here some reason's why its not appearing
1. **Remove the fade class in your modal.**
2. **The versions of your Javascript and Bootstrap does not match.**
3. **You forgot to include bootstrap.js library in the document**
please check this out [enter link description here](https://stackoverflow.com/questions/36672304/bootstrap-mymodal-modalshow-is-not-working) | Use class instead of multiple IDs
=================================
>
> Share your modal code
>
>
>
```
var mem_butn = "<td><input type=\"button\" class=\"btnedt\" value=\"Edit\" /></td>";
```
```
<script>
$(document).ready(function () {
$('body').on('click', '.btnedt', function() {
$("#newModal").modal("show");
});
});
</script>
``` | 2,852 |
61,005,152 | Here I am using `fft` function of `numpy` to plot the fft of PCM wave generated from a 10000Hz sine wave. But the amplitude of the plot I am getting is wrong.
The frequency is coming correct using `fftfreq` function which I am printing in the console itself. My python code is here.
```
import numpy as np
import matplotlib.pyplot as plt
frate = 44100
filename = 'Sine_10000Hz.bin' #signed16 bit PCM of a 10000Hz sine wave
f = open('Sine_10000Hz.bin','rb')
y = np.fromfile(f,dtype='int16') #Extract the signed 16 bit PCM value of 10000Hz Sine wave
f.close()
####### Spectral Analysis #########
fft_value = np.fft.fft(y)
freqs = np.fft.fftfreq(len(fft_value)) # frequencies associated with the coefficients:
print("freqs.min(), freqs.max()")
idx = np.argmax(np.abs(fft_value)) # Find the peak in the coefficients
freq = freqs[idx]
freq_in_hertz = abs(freq * frate)
print("\n\n\n\n\n\nfreq_in_hertz")
print(freq_in_hertz)
for i in range(2):
print("Value at index {}:\t{}".format(i, fft_value[i + 1]), "\nValue at index {}:\t{}".format(fft_value.size -1 - i, fft_value[-1 - i]))
#####
n_sa = 8 * int(freq_in_hertz)
t_fft = np.linspace(0, 1, n_sa)
T = t_fft[1] - t_fft[0] # sampling interval
N = n_sa #Here it is n_sample
print("\nN value=")
print(N)
# 1/T = frequency
f = np.linspace(0, 1 / T, N)
plt.ylabel("Amplitude")
plt.xlabel("Frequency [Hz]")
plt.xlim(0,15000)
# 2 / N is a normalization factor Here second half of the sequence gives us no new information that the half of the FFT sequence is the output we need.
plt.bar(f[:N // 2], np.abs(fft_value)[:N // 2] * 2 / N, width=15,color="red")
```
Output comes in the console (Only minimal prints I am pasting here)
```
freqs.min(), freqs.max()
-0.5 0.49997732426303854
freq_in_hertz
10000.0
Value at index 0: (19.949569768991054-17.456031216294324j)
Value at index 44099: (19.949569768991157+17.45603121629439j)
Value at index 1: (9.216783424692835-13.477631008179145j)
Value at index 44098: (9.216783424692792+13.477631008179262j)
N value=
80000
```
The frequency extraction is coming correctly but in the plot something I am doing is incorrect which I don't know.
Updating the work:
1. When I am change the multiplication factor **10** in the line `n_sa = 10 * int(freq_in_hertz)` to **5** gives me correct plot. Whether its correct or not I am not able to understand
2. In the line `plt.xlim(0,15000)` if I increase max value to **20000** again is not plotting. Till **15000** it is plotting correctly.
3. I generated this `Sine_10000Hz.bin` using Audacity tool where I generate a sine wave of freq 10000Hz of 1sec duration and a sampling rate of 44100. Then I exported this audio to signed 16bit with headerless (means raw PCM). I could able to regenerate this sine wave using this script. Also I want to calculate the FFT of this. So I expect a peak at 10000Hz with amplitude 32767. You can see i changed the multiplication factor `8` instead of `10` in the line `n_sa = 8 * int(freq_in_hertz)`. Hence it worked. But the amplitude is showing incorrect. I will attach my new figure here[](https://i.stack.imgur.com/dQSyX.png) | 2020/04/03 | [
"https://Stackoverflow.com/questions/61005152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12673488/"
] | After a long home work I could able to find my issue. As I mentioned in the **Updating the work:** the reason was with the number of samples which I took was wrong.
I changed the two lines in the code
```
n_sa = 8 * int(freq_in_hertz)
t_fft = np.linspace(0, 1, n_sa)
```
to
```
n_sa = y.size //number of samples directly taken from the raw 16bits
t_fft = np.arange(n_sa)/frate //Here we need to divide each samples by the sampling rate
```
This solved my issue.
My spectral output is [](https://i.stack.imgur.com/Xd7bF.png)
Special thanks to @meta4 and @YoniChechik for giving me some suggestions. | I'm not sure exactly what you are trying to do, but my suspicion is that the Sine\_10000Hz.bin file isn't what you think it is.
Is it possible it contains more than one channel (left & right)?
Is it realy signed 16 bit integers?
It's not hard to create a 10kHz sine wave in 16 bit integers in numpy.
```py
import numpy as np
import matplotlib.pyplot as plt
n_samples = 2000
f_signal = 10000 # (Hz) Signal Frequency
f_sample = 44100 # (Hz) Sample Rate
amplitude = 2**3 # Arbitrary. Must be > 1. Should be > 2. Larger makes FFT results better
time = np.arange(n_samples) / f_sample # sample times
# The signal
y = (np.sin(time * f_signal * 2 * np.pi) * amplitude).astype('int16')
```
If you plot 30 points of the signal you can see there are about 5 points per cycle.
```py
plt.plot(time[:30], y[:30], marker='o')
plt.xlabel('Time (s)')
plt.yticks([]); # Amplitude value is artificial. hide it
```
[](https://i.stack.imgur.com/hQXt2.png)
If you plot 30 samples of the data from Sine\_10000Hz.bin does it have about 5 points per cycle?
This is my attempt to recreate the FFT work as I understand it.
```
fft_value = np.fft.fft(y) # compute the FFT
freqs = np.fft.fftfreq(len(fft_value)) * f_sample # frequencies for each FFT bin
N = len(y)
plt.plot(freqs[:N//2], np.abs(fft_value[:N//2]))
plt.yscale('log')
plt.ylabel("Amplitude")
plt.xlabel("Frequency [Hz]")
```
I get the following plot
[](https://i.stack.imgur.com/ACMl2.png)
The y-axis of this plot is on a log scale. Notice that the amplitude of the peak is in the thousands. The amplitude of most of the rest of the data points are around 100.
```py
idx_max = np.argmax(np.abs(fft_value)) # Find the peak in the coefficients
idx_min = np.argmin(np.abs(fft_value)) # Find the peak in the coefficients
print(f'idx_max = {idx_max}, idx_min = {idx_min}')
print(f'f_max = {freqs[idx_max]}, f_min = {freqs[idx_min]}')
print(f'fft_value[idx_max] {fft_value[idx_max]}')
print(f'fft_value[idx_min] {fft_value[idx_min]}')
```
produces:
```
idx_max = 1546, idx_min = 1738
f_max = -10010.7, f_min = -5777.1
fft_value[idx_max] (-4733.232076236707+219.11718299533203j)
fft_value[idx_min] (-0.17017443966211232+0.9557200531465061j)
``` | 2,853 |
64,924,830 | Is it possible to write an API with Python so you can connect a physical ON and OFF switch via USB to a PC and when user presses the switch to ON or OFF, the python program detects it and send a signal to a web app and shows ON or OFF message on the website?
I am sorry if what I am asking its not clear enough! | 2020/11/20 | [
"https://Stackoverflow.com/questions/64924830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12487489/"
] | You can simply use `std::optional`:
```
String(const std::optional<int> &min_len, const std::optional<int> &max_len,
const std::optional<std::string> &pattern);
Type *type = new String(5, {}, std::nullptr); // last 2 parameters are omitted.
```
For C++14 you can use similar constructs that exist in other open source libraries, (e.g. `boost::optional`, `folly::Optional`). | Have you tried to use an [std::optional](https://en.cppreference.com/w/cpp/utility/optional) (since C++17)?
I know you mentioned the need to use C++14 compatible code, but there is a [boost::optional](https://www.boost.org/doc/libs/1_65_1/libs/optional/doc/html/index.html) available. | 2,855 |
8,210,344 | I get the following error
ImportError: No module named numeric if I have the following import
```
from numeric import *
```
in my python source code. How do I get this running on my Windows box against a python 2.7.x compiler? | 2011/11/21 | [
"https://Stackoverflow.com/questions/8210344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004443/"
] | You will probably need to install this module: <http://numpy.scipy.org/>
There are binaries for windows too, so installation should be easy.
Josh | There is no common module called `numeric`. Are you sure you don't mean `import numpy`? | 2,860 |
4,227,503 | I would like to establish a good naming scheme for physical/mathematical quantities used in my simulation code. Consider the following example:
```
from math import *
class GaussianBeamIntensity(object):
"""
Optical intensity profile of a Gaussian laser beam.
"""
def __init__(self, intensity_at_waist_center, waist_radius, wavelength):
"""
Arguments:
*intensity_at_waist_center*: The optical intensity of the beam at the
center of its waist in W/m^2 units.
*waist_radius*: The radius of the beam waist in meters.
*wavelength*: The wavelength of the laser beam in meters.
"""
self.intensity_at_waist_center = intensity_at_waist_center
self.waist_radius = waist_radius
self.wavelength = wavelength
self._calculate_auxiliary_quantities()
def _calculate_auxiliary_quantities(self):
# Shorthand notation
w_0, lambda_ = self.waist_radius, self.wavelength
self.rayleigh_range = pi * w_0**2 / lambda_
# Generally some more quantities could follow
def __call__(self, rho, z):
"""
Arguments:
*rho*, *z*: Cylindrical coordinates of a spatial point.
"""
# Shorthand notation
I_0, w_0 = self.intensity_at_waist_center, self.waist_radius
z_R = self.rayleigh_range
w_z = w_0 * sqrt(1.0 + (z / z_R)**2)
I = I_0 * (w_0 / w_z)**2 * exp(-2.0 * rho**2 / w_z**2)
return I
```
What consistent naming scheme would you propose for the physical properties (properties, function arguments etc.) in order to balance between **readability** and **concise notation** (that formulae remain relatively short)? Could you please refine the example above? Or perhaps propose a better scheme?
It would be nice to follow the guidelines of [PEP8](http://www.python.org/dev/peps/pep-0008/ "PEP8"), remembering that "A Foolish Consistency is the Hobgoblin of Little Minds". It seems difficult to stick to descriptive names while obeying the traditional 80-character limit for line lengths.
Thank you in advance! | 2010/11/19 | [
"https://Stackoverflow.com/questions/4227503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335609/"
] | I think you've already found the good balance. Expressive names are important, so I totally agree with the use of *wavelenght* instead of lambda as a class attribute. This way the interface remains clear and expressive.
In a long formula, though, lambda\_ is good choice as shorthand notation, because this is a commonly accepted and widely used notation for the wavelength in optics. I think when you implement a formula, what you want to do is staying as close as possible to the form of the equations you'd write on a piece of paper (or as they appear in an article etc).
In short: keep the interfaces expressive, the formulae short. | Use Python3 and you can use the actual symbol λ for a variable name.
I look forward to writing code like:
```
from math import pi as π
sphere_volume = lambda r : 4/3 * π * r**3
``` | 2,862 |
53,545,656 | I know there are many post related to dictionary operations but I could not find the solution for my special case.
I have list of dictinoary (repeated dictionary keys with similar or different values) and I have to create a new dictionary from this list.
Eg:
```
a = [{u'a': 1}, {u'a': 2}, {u'a': 1}, {u'b': 2}, {u'b': 1}, {u'c': 1}, {u'c': 1}]
```
Output I am looking for:
```
{'a': 2, 'b':2, 'c': 1}
```
So as you can see I just want one entry per key from the list and the value for that key would be max of all values. Hope its not too confusing.
I have come with a working soultion but I just wanted to check if there is more pythonic answer to this (with less #of lines or better way)
This is my working solution:
```
d = {}
for i in a:
if not d.get(i.keys()[0]):
d.update(i)
elif d.get(i.keys()[0], 0) < i.values()[0]:
d.update(i)
print d
```
Thansk for your time. | 2018/11/29 | [
"https://Stackoverflow.com/questions/53545656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565385/"
] | You can sort the list `a` so that the like keys are groups and the largest values are last. Then add the values so that last value is the value left in the dict:
```
>>> a = [{u'a': 1}, {u'a': 2}, {u'a': 1}, {u'b': 2}, {u'b': 1}, {u'c': 1}, {u'c': 1}]
>>> {k:v for k,v in (x.items()[0] for x in sorted(a))}
{u'a': 2, u'c': 1, u'b': 2}
```
Or, alternate syntax:
```
>>> dict(x.items()[0] for x in sorted(a))
```
For Python 2 and 3 syntax:
```
>>> {k:v for k,v in (sorted(list(x.items())[0] for x in a))}
{'a': 2, 'b': 2, 'c': 1}
>>> dict(sorted(list(x.items())[0] for x in a))
{'a': 2, 'b': 2, 'c': 1}
```
---
From comments: *what's happening here?*
First, let's come up with a more instructive example:
```
>>> a = [{u'a': -1}, {u'a': -11}, {u'a': -3}, {u'b': 0}, {u'b': 100}, {u'c': 3}, {u'c': 1}]
```
So the desired result here is the keys (for Python 3 that maintain order in a dict or with OrderedDict) would be i) Keys in groups of sorted values and then ii) values interpreted as numerics in increasing values.
So try this first:
```
>>> sorted(list(x.items())[0] for x in a)
[('a', -11), ('a', -3), ('a', -1), ('b', 0), ('b', 100), ('c', 1), ('c', 3)]
```
Break it apart:
```
sorted(list(x.items())[0] for x in a)
^ ^ comprehension of
^ a list of one element dicts
^ ^ ^ convert to a two element tuple
^ sort the tuple first by key, then by value
```
So that works by sorting the tuples first by the keys, then by the values.
Which leads to an alternate solution using `groupby`:
```
>>> from itertools import groupby
>>> for k,v in groupby(sorted(list(x.items())[0] for x in a), key=lambda t: t[0]):
... print(k, max(v))
...
a ('a', -1)
b ('b', 100)
c ('c', 3)
```
The `groupby` solution would be substantially more memory friendly since it does not create an extra list. The first solution, likely, will be faster with smaller list of dicts since the sorting is easier (but you would need to test that.)
It is not *required* in the solution that I gave that the keys be grouped (it is required for `groupby` to work). This works too:
```
>>> sorted((list(x.items())[0] for x in a), key=lambda t: t[1])
[('a', -11), ('a', -3), ('a', -1), ('b', 0), ('c', 1), ('c', 3), ('b', 100)]
```
Then turn it into a `dict` with the dict construction function. Recall that takes a list of tuples of `(key, value)`:
```
>>> dict(sorted((list(x.items())[0] for x in a), key=lambda t: t[1]))
{'a': -1, 'b': 100, 'c': 3}
``` | You could do:
```
a = [{u'a': 1}, {u'a': 2}, {u'a': 1}, {u'b': 2}, {u'b': 1}, {u'c': 1}, {u'c': 1}]
result = {}
for di in a:
for key, value in di.items():
result[key] = max(value, result.get(key, value))
print(result)
```
**Output**
```
{'a': 2, 'c': 1, 'b': 2}
``` | 2,863 |
67,268,013 | I have been trying to draw a networkx multidigraph with multiple self-loops on nodes using matplotlib for quite a few days now but nothing works.
After multiple tests, I narrowed the problem to Networkx with Matplotlib.
I executed the following tutorial <https://networkx.org/documentation/latest/auto_examples/drawing/plot_selfloops.html>
on my laptop and using an online python compiler but no self-loop get printed. I think there might be a bug somewhere since it is supposed to work according the official documentation.
Please do not propose to used Graphviz... I already did and it does not correspond to what I want.
Current Behavior
From the tutorial, here is the image that I obtain :

Expected Behavior
The image that I'm supposed to obtain :

My environment :
Python version: 3
NetworkX version: 2.5 (I upraded it)
Thanks! | 2021/04/26 | [
"https://Stackoverflow.com/questions/67268013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6099112/"
] | any time GoogleFinance() reutrns a historical array, you need to INDEX() it to get just the single answer.
It's almost always the second row and second column of the array that you want.
So:
```
=INDEX(Goooglefinance(.... ), 2, 2)
``` | I've tested your function and the error ***Function MULTIPLY parameter 2 expects number values. But 'Date' is a text and cannot be coerced to a number*** is due to this part `E2*GOOGLEFINANCE("Currency:"&F2&$G$1,"price", H2)` in your IFS function.
The return value of the `GOOGLEFINANCE("Currency:"&F2&$G$1,"price", H2)` is an array (it contains strings and numbers) and multiplying it to E2 value is not possible. Also, if running `GOOGLEFINANCE("Currency:"&F2&$G$1,"price", H2)` alone works just fine, then the H2 (the date cell) isn't the main cause of the error.
**RECOMMENDED SOLUTION:**
I've checked on how to only return price instead of an array on GOOGLEFINANCE function and stumbled upon an answer from [How can I get GOOGLEFINANCE to return only the historical price of a stock and not an array?](https://webapps.stackexchange.com/questions/14725/how-can-i-get-googlefinance-to-return-only-the-historical-price-of-a-stock-and-n/23964#23964).
Instead, you can try this function below:
```
=IFS(F2<>"EUR", min(GoogleFinance("Currency:"&F2&$G$1, "PRICE", H2))*E2, F2 = "EUR",E2)
```
Here's a sample test on my end:
[](https://i.stack.imgur.com/XMOvx.png) | 2,866 |
51,263,370 | I am trying to implement k-nearest neighbor algorithm with the dataset which I have preprocessed. I imported the data as pandas dataframe and then converted it into numpy array but the following error is occuring-
```
File "/home/user/Documents/Mooc_implementation.py", line 8, in <module>
x = num_data[:,:10]
File "/usr/lib/python2.7/dist-packages/numpy/core/records.py", line 499, in __getitem__
obj = super(recarray, self).__getitem__(indx)
IndexError: too many indices for array
```
here is my code-
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('/home/user/Documents/MOOC dataset cleaned/student_reg_vle_info_assessment.csv')
num_data = dataset.to_records(index=False)
x = num_data[:,:10]
y = num_data[:,10:11]
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20)
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=4)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
```
what should I do?
output of dataset.head()-
```
date_submitted date_registration date_unregistration sum_click \
0 18 -159 445 16
1 22 -53 445 4
2 30 -92 12 3
3 17 -52 445 1
4 26 -176 445 5
num_of_prev_attempts age_band region highest_education studied_credits \
0 0 0 0 0 240
1 0 1 1 0 60
2 0 1 2 1 60
3 0 1 3 1 60
4 0 2 4 2 60
score final_result
0 78 0
1 70 0
2 87 2
3 72 0
4 69 0
[Finished in 0.274s]
``` | 2018/07/10 | [
"https://Stackoverflow.com/questions/51263370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9355642/"
] | you use `.` instead of `->` because of this declaration of parameters:
`int ball_room(ball *b, int i, int n)`
`b` is expected to be pointer to data with type `ball`, so you can access it in various ways:
1. array way: e.g. `b[5].somefield = 15` - you use dot here, because if `b` is of type `ball *`, it means that `b` is pointer OR it is array of objects with type `b`, if it's array of objects with type `b` (which is your case) you use `.` to access fields of object
2. pointer way: e.g. `(b+5)->somefield = 15` - it will do exactly same thing as code above, but you will access data in `pointer` way | In C/C++ an array devolves into the address of it's first member. So when you pass the array to `ball_room` what actually gets passed is `&ball[0]`.
Now inside `ball_room` the reverse happens. `b` is a pointer to ball. But here you use it as an array `b[j]`. So it un-devolves back into an array of structs. So what `b[j]` gives you is the struct and not a pointer to a struct. Consequently you access it using `.` instead of `->`.
You can also use `(b + j)->somefield`. Or for even more fun how about writing `j[b].somefield`. The later being a really confusing left-over from the eraly compiler days when `a[b]` truly got turned into `*(a + b)` internally. | 2,867 |
58,411,930 | After all of web searching and coming up of no answer to this, I thought of asking this question on this platform. I had an application container which i try to connect with mine database container but due to reasons unaware mine application is not able to connect.
I am providing all the relevant information required for it.
Here is mine docker-compose file
```
version: '2'
services:
application: &application
image: gmasmatrix_application:latest
command: /start.sh
volumes:
- .:/app
depends_on:
- db
ports:
- 8000:8000
# cpu_shares: 874
# mem_limit: 1610612736
# mem_reservation: 1610612736
build:
context: ./
dockerfile: ./compose/local/application/Dockerfile
args:
- GMAS_ENV_TYPE=local
db:
image: mysql:5.7.10
environment:
MYSQL_DATABASE: gmas_mkt
MYSQL_ROOT_PASSWORD: pulkit1607
ports:
- '3306:3306'
volumes:
- my-db:/var/lib/mysql
volumes:
my-db:
```
I also changed the host in the settings.py file
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'gmas_mkt',
'USER': 'root',
'PASSWORD': 'pulkit1607',
'HOST': 'db',
'PORT': '3306',
}
}
```
Here is the error I get upon running the docker-compose up file
```
application_1 | Traceback (most recent call last):
application_1 | File "manage.py", line 22, in <module>
application_1 | execute_from_command_line(sys.argv)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
application_1 | utility.execute()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute
application_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
application_1 | self.execute(*args, **cmd_options)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
application_1 | self.check()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 482, in check
application_1 | include_deployment_checks=include_deployment_checks,
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
application_1 | new_errors = check(app_configs=app_configs)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 28, in check_all_models
application_1 | errors.extend(model.check(**kwargs))
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 1205, in check
application_1 | errors.extend(cls._check_fields(**kwargs))
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 1282, in _check_fields
application_1 | errors.extend(field.check(**kwargs))
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 934, in check
application_1 | errors = super(AutoField, self).check(**kwargs)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 207, in check
application_1 | errors.extend(self._check_backend_specific_checks(**kwargs))
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 306, in _check_backend_specific_checks
application_1 | return connection.validation.check_field(self, **kwargs)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 18, in check_field
application_1 | field_type = field.db_type(connection)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 614, in db_type
application_1 | return connection.data_types[self.get_internal_type()] % data
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
application_1 | return getattr(connections[DEFAULT_DB_ALIAS], item)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py", line 59, in __get__
application_1 | res = instance.__dict__[self.name] = self.func(instance)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 196, in data_types
application_1 | if self.features.supports_microsecond_precision:
application_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py", line 59, in __get__
application_1 | res = instance.__dict__[self.name] = self.func(instance)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/features.py", line 52, in supports_microsecond_precision
application_1 | return self.connection.mysql_version >= (5, 6, 4) and Database.version_info >= (1, 2, 5)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py", line 59, in __get__
application_1 | res = instance.__dict__[self.name] = self.func(instance)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 371, in mysql_version
application_1 | with self.temporary_connection():
application_1 | File "/usr/local/lib/python2.7/contextlib.py", line 17, in __enter__
application_1 | return self.gen.next()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 462, in temporary_connection
application_1 | cursor = self.cursor()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor
application_1 | cursor = self.make_debug_cursor(self._cursor())
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 135, in _cursor
application_1 | self.ensure_connection()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection
application_1 | self.connect()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__
application_1 | six.reraise(dj_exc_type, dj_exc_value, traceback)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection
application_1 | self.connect()
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 119, in connect
application_1 | self.connection = self.get_new_connection(conn_params)
application_1 | File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 276, in get_new_connection
application_1 | conn = Database.connect(**conn_params)
application_1 | File "/usr/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
application_1 | return Connection(*args, **kwargs)
application_1 | File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 166, in __init__
application_1 | super(Connection, self).__init__(*args, **kwargs2)
application_1 | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
```
Not able to figure out what i am doing wrong. | 2019/10/16 | [
"https://Stackoverflow.com/questions/58411930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182512/"
] | in my case
i changed
```
mysql://root:root@localhost:3307/db
```
to
```
mysql://root:root@Gateway ip:3307/test_db
```
the Gateway ip you can find it in
```
docker network ls
docker network inspect
``` | Change 'HOST': 'db' to 'HOST': '**localhost**' in settings.py file. Because you map the default MySQL port from container to MySQL default port in your main host. | 2,876 |
29,678,324 | I'm just learning python so be gentle. I want to read a file and that to be one function and then have another function work on what the previous function "read". I am having trouble passing the result on one function to another. Here is what I have no far:
I want to call read\_file more than once and to be able to pass its result to more than one function, therefore, I do not want frame to be a global variable. How do I get read\_file to pass 'frame' to cost\_channelID directly? Perhaps, for cost\_channelID to call read\_file?
```
def read_file():
user_input = raw_input("please put date needed in x.xx form: ")
path = r'C:\\Users\\CP\\documents\\' + user_input
allFiles = glob.glob(path + '/*.csv')
frame = pd.DataFrame()
list = []
for file in allFiles:
df = pd.read_csv(file,index_col=None,header=0)
list.append(df)
frame =pd.concat(list,ignore_index=True)
def cost_channelID():
numbers =r'[0,1,2,3,4,5,6,7,8,9]'
Ads = frame['Ad']
ID = []
for ad in Ads:
num = ''.join(re.findall(numbers,ad)[1:7])
ID.append(num)
ID = pd.Series(ID)
pieces = [frame,ID]
frame2 = pd.concat(pieces,ignore_index=True,axis=1)
frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})
```
Any and all help is greatly appreciated! | 2015/04/16 | [
"https://Stackoverflow.com/questions/29678324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797120/"
] | Here is your modified code (comments in uppercase for easier finding, not rudeness):
```
def read_file():
user_input = raw_input("please put date needed in x.xx form: ")
path = r'C:\\Users\\CP\\documents\\' + user_input
allFiles = glob.glob(path + '/*.csv')
frame = pd.DataFrame()
list = []
for file in allFiles:
df = pd.read_csv(file,index_col=None,header=0)
list.append(df)
frame =pd.concat(list,ignore_index=True)
return(frame) #YOUR FUNCTION WILL BE RETURNING THE READ FRAME
def cost_channelID(read_frame): #YOU WILL BE RECEIVING A DIFFERENT FRAME EVERY TIME
numbers =r'[0,1,2,3,4,5,6,7,8,9]'
Ads = read_frame['Ad']
ID = []
for ad in Ads:
num = ''.join(re.findall(numbers,ad)[1:7])
ID.append(num)
ID = pd.Series(ID)
pieces = [frame,ID]
frame2 = pd.concat(pieces,ignore_index=True,axis=1)
frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})
#HERE YOU MEANT TO USE FRAME2 WITHIN THE FUNCTION? IT IS WHAT HAPPENING BECAUSE OF THE INDENTATION
frame1 = read_file() #YOU CAN READ AS MANY FRAMES AS YOU WANT AND THEY'LL BE KEPT IN SEPARATED FRAMES
frame2 = read_file()
#...framexx = read_file()
#AND YOU CAN JUST CALL cost_channelID in any of them (or any other function)
const_channelID(frame1)
const_channelID(frame2)
#... AND SO ON
``` | If you are trying to pass frame from one function to the other, you need to declare it outside the scope of the function. Otherwise we need more information about what you are trying to accomplish.
```
frame = None
def read_file():
user_input = raw_input("please put date needed in x.xx form: ")
path = r'C:\\Users\\CP\\documents\\' + user_input
allFiles = glob.glob(path + '/*.csv')
frame = pd.DataFrame()
list = []
for file in allFiles:
df = pd.read_csv(file,index_col=None,header=0)
list.append(df)
frame =pd.concat(list,ignore_index=True)
def cost_channelID():
numbers =r'[0,1,2,3,4,5,6,7,8,9]'
Ads = frame['Ad']
ID = []
for ad in Ads:
num = ''.join(re.findall(numbers,ad)[1:7])
ID.append(num)
ID = pd.Series(ID)
pieces = [frame,ID]
frame2 = pd.concat(pieces,ignore_index=True,axis=1)
frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})
```
Here is a good reference for scope rules in python
[Short Description of the Scoping Rules?](https://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules) | 2,877 |
51,171,741 | I am using Python for the first time to create a simple JSON parser. However, when printing the JSON data to the console, it includes many extra brackets and other symbols that are unwanted. I am also running Python 2.7.10.
```
import json
from urllib2 import urlopen
response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()
# print(source)
data = json.loads(source)
# print(json.dumps(data, indent=2))
usd_rates = dict()
for item in data['list']['resources']:
name = item['resource']['fields']['name']
price = item['resource']['fields']['price']
usd_rates[name] = price
print(name, price)
```
And the output is as follows:
[](https://i.stack.imgur.com/pW15b.png)
When I try to change the python version to 3.7.10:
[](https://i.stack.imgur.com/9R47A.png) | 2018/07/04 | [
"https://Stackoverflow.com/questions/51171741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6131554/"
] | I think you are actually printing a tuple with python 2 `print` syntax and the `u` character is a unicode flag ([What exactly do "u" and "r" string flags do, and what are raw string literals?](https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals)).
Also in python 3 you couldn't use `urllib2` but would have to use `urllib.request`.
This code works for me (python 3.6.5):
```
import json
from urllib.request import urlopen
response = urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json")
source = response.read()
data = json.loads(source)
usd_rates = dict()
for item in data['list']['resources']:
name = item['resource']['fields']['name']
price = item['resource']['fields']['price']
usd_rates[name] = price
print(name, price)
```
EDIT ---------
From the image you posted it looks like you have python 3 installed but your `usr/bin/python` is a symbolic link to `usr/bin/python2`.
If you want to run python 3 by default you could create an alias.
Check this link for more info <https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3>
(should be valid info for macs too) | Convert name and price to string
`print(str(name), str(price))`
or
use
`name = str(item['resource']['fields']['name'])` | 2,878 |
70,423,743 | I'm new in python and programming in general. I have this project to create a simple library to add new authors and upload books. I must also display the uploaded book details(total words, most common words, different words, etc.) when I open the book. Now to do this I know that I first must open the uploaded book in readmode, but I don't know how to access the file that I uploaded.
This is my models:
```
from django.db import models
from authors.models import Author
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book_name = models.CharField(max_length=50)
genre = models.CharField(max_length=50)
files = models.FileField(upload_to='books/files/')
def __str__(self):
return self.book_name()
```
This is my forms:
```
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('book_name', 'author', 'genre', 'files')
```
My views:
```
def create(request):
if request.method == 'POST':
form = BookForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('books:home')
elif request.method == 'GET':
form = BookForm()
return render(request, 'books/create.html', {
'form': form
})
def detail(request, pk):
book = get_object_or_404(Book, pk=pk)
return render(request, 'books/detail.html', context={'book': book})
```
My details.html:
```
{% extends 'base.html' %}
{% block title %} {{ book.book_name }} {% endblock %}
{% block content %}
<p>Book title: {{ book.book_name }}</p>
<p>Genre: {{ book.genre }}</p>
<p>Author:
<a href="{% url 'authors:detail' book.author.pk %}">{{ book.author.full_name }}</a>
</p>
<p><button type="button"><a href="{{ book.files.url }}" target="_blank">Shkarko</a></button></p>
{% endblock %}
```
I want it to be shown in details.html.
Thanks in advance! | 2021/12/20 | [
"https://Stackoverflow.com/questions/70423743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17725025/"
] | ```
<v-btn
class="mr-4"
:loading="saveLoading == index"
@click="submit(item, index)"
>
data: () => ({
valid: true,
saveLoading: -1,
})
submit (formItem, index) {
this.saveLoading = index
console.log(formItem)
// POST the formItem and make the saveLoading false in async then(), catch()
},
```
It is not a very logical method, but this way you can solve the problem. | If you are generating the forms from the api response, mean that in some way you are attaching the response to the Vue Data property. If so, you could easily enrich the objects of the array (the forms object) to have a isLoading property. So the result will be something like:
```
API RESPONSE
[
{
form_name: 'Form One',
name: 'Peter',
email: 'peter@email.com'
},
{
form_name: 'Form Two',
name: 'John',
email: 'john@email.com'
}
]
```
and store is as:
```
Stored object
[
{
form_name: 'Form One',
name: 'Peter',
email: 'peter@email.com',
isLoading: false
},
{
form_name: 'Form Two',
name: 'John',
email: 'john@email.com',
isLoading: false
}
]
```
Set the loading status in the submit(item) method:
```
submit(item){
item.isLoading = true;
}
```
then you can use it by checking the value of isLoading on the form object, something on the lines of:
```
<v-form
v-for="(item, index) in forms" :key="index"
>
<v-btn
:loading="item.isLoading"
@click="submit(item)"
>
submit
</v-btn>
</v-form>
``` | 2,879 |
37,143,664 | Just trying to pull some lat/lon info from EXIF data on a bunch of photos, but code is throwing a `KeyError` even though that key is used (successfully) later on to print specific coordinates.
Dictionary in question is "`tags`" - `'GPS GPSLatitude'` and `'GPS GPSLongitude'` are both keys in `tags.keys()`; I've triple checked.
So any intuition on why `tags['GPS GPSLatitude']` & `tags['GPS GPSLongitude']` are throwing key errors?
```
import os
import exifread
output = dict()
output['name'] = []
output['lon'] = []
output['lat'] = []
for file in os.listdir(path):
if file.endswith(".JPG"):
full_path = path + file
print (file) #check to ensure all files were found
output['name'].append(file) #append photo name to dictionary
f = open(full_path, 'rb') #open photo
tags = exifread.process_file(f) #read exifdata
# lon = tags['GPS GPSLongitude'] #this + next line = one method
# output['lon'].append(lon)
# output['lat'].append(tags['GPS GPSLatitude']) # = cleaner second method
for tag in tags.keys():
if tag in ('GPS GPSLongitude','GPS GPSLatitude'):
print ("Key: %s, value %s" % (tag, tags[tag])) #successfully prints lat/lon coords with 'GPS GPSLongitude' and 'GPS GPSLatitude' as keys
```
UPDATE:
Here's the output of `print (tags.keys())` -- you'll see `GPS GPSLatitude` and `GPS GPSLongitude` in there. Also, have manually checked all the photos in the subset I'm using have GPS data.
`dict_keys(['GPS GPSImgDirection', 'EXIF SceneType', 'MakerNote Tag 0x0006', 'GPS GPSDestBearing', 'Thumbnail XResolution', 'EXIF BrightnessValue', 'GPS GPSAltitude', 'GPS GPSLongitude', 'EXIF LensSpecification', 'GPS GPSAltitudeRef', 'GPS GPSSpeedRef', 'GPS GPSDestBearingRef', 'EXIF WhiteBalance', 'Thumbnail ResolutionUnit', 'EXIF FocalLengthIn35mmFilm', 'EXIF SceneCaptureType', 'Image Model', 'MakerNote Tag 0x0008', 'Image Make', 'EXIF ShutterSpeedValue', 'MakerNote Tag 0x0007', 'EXIF ExifImageWidth', 'EXIF LensModel', 'Image YResolution', 'EXIF ComponentsConfiguration', 'Image GPSInfo', 'EXIF ISOSpeedRatings', 'EXIF ExposureMode', 'EXIF Flash', 'EXIF FlashPixVersion', 'GPS GPSLatitudeRef', 'EXIF ExposureBiasValue', 'Thumbnail JPEGInterchangeFormatLength', 'Thumbnail Compression', 'Image YCbCrPositioning', 'EXIF MakerNote', 'EXIF FNumber', 'JPEGThumbnail', 'MakerNote Tag 0x0001', 'EXIF ColorSpace', 'EXIF SubSecTimeDigitized', 'Thumbnail JPEGInterchangeFormat', 'MakerNote Tag 0x0004', 'EXIF SubjectArea', 'Image ResolutionUnit', 'EXIF SensingMethod', 'Image DateTime', 'Image Orientation', 'EXIF ExifVersion', 'Image ExifOffset', 'GPS GPSImgDirectionRef', 'MakerNote Tag 0x0014', 'Thumbnail YResolution', 'EXIF DateTimeOriginal', 'MakerNote Tag 0x0005', 'EXIF LensMake', 'EXIF DateTimeDigitized', 'MakerNote Tag 0x0003', 'GPS GPSTimeStamp', 'EXIF ExposureTime', 'GPS Tag 0x001F', 'EXIF SubSecTimeOriginal', 'GPS GPSLatitude', 'Image Software', 'EXIF ApertureValue', 'GPS GPSDate', 'EXIF ExposureProgram', 'GPS GPSSpeed', 'EXIF ExifImageLength', 'EXIF MeteringMode', 'GPS GPSLongitudeRef', 'EXIF FocalLength', 'Image XResolution'])`
Traceback
```
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-14-949ba89a1248> in <module>()
16 # lon = tags["GPS GPSLongitude"]
17 # output['lon'].append(lon)
---> 18 output['lat'].append(tags['GPS GPSLatitude'])
19 for tag in tags.keys():
20 if tag in ('GPS GPSLongitude','GPS GPSLatitude'):
KeyError: 'GPS GPSLatitude'
```
Link to photo: [https://drive.google.com/a/cornell.edu/file/d/0B1DwcbbAH1yuTEs0cUhhODdlNnc/view](https://drive.google.com/a/cornell.edu/file/d/0B1DwcbbAH1yuTEs0cUhhODdlNnc/view])
Output of the print statement for this photo
```
IMG_6680.JPG
Key: GPS GPSLongitude, value [76, 29, 353/20]
Key: GPS GPSLatitude, value [42, 26, 5069/100]
``` | 2016/05/10 | [
"https://Stackoverflow.com/questions/37143664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5957741/"
] | `GPS GPSLatitude` and `GPS GPSLongitude` may not be present in all tag dicts.
Instead of accessing keys as `tags['GPS GPSLatitude']` & `tags['GPS GPSLongitude']` , you can also access these as `tags.get('GPS GPSLatitude')` & `tags.get('GPS GPSLongitude')` This wil return `None` instead of throwing error, where you can apply if-else condition also to verify where these keys are not present. | I think @BryanOakley has the right idea. If the key isn't in the dict, it isn't there. (Those fields are optional, and some files might not have the data.) So you can use the `dict.get(key, default=None)` approach, and replace the Key Error with a default value.
```
jpegs = [file for file in os.listdir(path) if file.endswith('.JPG')]
locns = []
for jpeg in jpegs:
with open(jpeg,'rb') as jpf:
exif = exifread.process_file(jpf)
lat = exif.get('GPS GPSLatitude', 'Not available')
lon = exif.get('GPS GPSLongitude', 'Not available')
locns.append((lat, lon))
``` | 2,881 |
58,673,628 | I have been leaning python and programming for not so long. So you may find my question silly.
I am reviewing generator and try to generate 'yes', 'no' infinitely just to understand the concept.
I have tried this code but having "yes" each time
```
def yes_or_no():
answer = ["yes","no"]
i=0
while True:
if i >=2:
i=0
yield answer[i]
i+=1
c=next(yes_or_no())
print(c)
print(c)
print(c)
print(c)
``` | 2019/11/02 | [
"https://Stackoverflow.com/questions/58673628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12308317/"
] | `yes_no()` produces the generator; you want to call `next` on the same generator each time, rather than printing the same first element over and over.
```
c = yes_no()
print(next(c))
print(next(c))
# etc.
```
That said, there's no need for a separate counter; just yield `yes`, then yield `no`, then repeat.
```
def yes_or_no():
while True:
yield "yes"
yield "no"
``` | You need to initialize the generator and then call `next` on the initialized generator object:
```
c = yes_or_no()
```
Now you need to call `next` on `c`:
```
print(next(c))
print(next(c))
```
---
In your current code `c=next(yes_or_no())`:
* `yes_or_no()` will initialize the generator and calling `next` on it will get the first `yes` and you're saving that `yes` as name `c`
* In the next lines, you're just printing same `yes` referred by `c` while doing `print(c)` | 2,882 |
19,351,065 | I'm trying to get a deeper understanding of how Python works, and I've been looking at the grammar shown at <http://docs.python.org/3.3/reference/grammar.html>.
I notice it says you would have to change parsermodule.c also, but truthfully I'm just not following what's going on here.
I understand that a grammar is a specification for how to read the language, but...I can't even tell what this is written in. It looks almost like Python but then it isn't.
I'm looking to get a better understanding of this specification and how it is used internally by Python to....do things. What depends on it (the answer is everything, but I mean specifically which aspect of the "engine" is processing it), what uses it, how does it tie in to compiling/running a script?
It's hard to believe that the whole language comes down to a two page specification... | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029146/"
] | That is basically an [EBNF](http://en.wikipedia.org/wiki/EBNF) (Extended Backus–Naur Form) specification. | When you write a program in a language, the very first thing your interpreter/compiler must do in order to go from a sequence of characters to actual action is to translate that sequence of characters in a higher complexity structure. To do so, first it chunks up your program in a sequence of tokens expressing what each "word" represents. For example, the construct
```
if foo == 3: print 'hello'
```
will be converted into
```
1,0-1,2: NAME 'if'
1,3-1,6: NAME 'foo'
1,7-1,9: OP '=='
1,10-1,11: NUMBER '3'
1,11-1,12: OP ':'
1,13-1,18: NAME 'print'
1,19-1,26: STRING "'hello'"
2,0-2,0: ENDMARKER ''
```
But note that even something like "if if if if" is correctly made into tokens
```
1,0-1,2: NAME 'if'
1,3-1,5: NAME 'if'
1,6-1,8: NAME 'if'
1,9-1,11: NAME 'if'
2,0-2,0: ENDMARKER ''
```
What follows the tokenization is the parsing into a higher level structure that analyzes if the tokens actually make sense taken together, something that the latter example does not, but the first does. To do so, the parser must recognize the actual meaning of the tokens (e.g. the if is a keyword, and foo is a variable), then build a tree out of the tokens, organizing them in a hierarchy and see if this hierarchy actually makes sense. Here is where the grammar you are seeing comes in. That grammar is in BNF, which is a notation to express the constructs the language can recognize. That grammar is digested by a program (for example, bison) which has the magic property of taking that grammar and generate actual C code that does the heavy work for you, normally by recognizing the tokens, organizing them, returning you a parse tree, or tell you where there's a mistake.
Short version: developing a language is about defining tokens and how these tokens are put together to give something meaningful. This is done through the grammar, which you use to generate the actual "parser" code with automated tools. | 2,884 |
53,515,926 | I have data stored in a parquet files and hive table partitioned by year, month, day. Thus, each parquet file is stored in `/table_name/year/month/day/` folder.
I want to read in data for only some of the partitions. I have list of paths to individual partitions as follows:
```py
paths_to_files = ['hdfs://data/table_name/2018/10/29',
'hdfs://data/table_name/2018/10/30']
```
And then try to do something like:
```py
df = sqlContext.read.format("parquet").load(paths_to_files)
```
However, then my data does not include the information about `year, month and day`, as this is not part of the data per se, rather the information is stored in the path to the file.
I could use sql context and a send hive query with some select statement with where on the year, month and day columns to select only data from partitions i am interested in. However, i'd rather avoid constructing SQL query in python as I am very lazy and don't like reading SQL.
**I have two questions:**
1. what is the optimal way (performance-wise) to read in the data stored as parquet, where information about year, month, day is not present in the parquet file, but is only included in the path to the file? (either send hive query using `sqlContext.sql('...')`, or use `read.parquet`,... anything really.
2. Can i somehow extract the partitioning columns when using the
approach i outlined above? | 2018/11/28 | [
"https://Stackoverflow.com/questions/53515926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7064628/"
] | Reading the direct file paths to the parent directory of the year partitions should be enough for a dataframe to determine there's partitions under it. However, it wouldn't know what to name the partitions without the directory structure `/year=2018/month=10`, for example.
Therefore, if you have Hive, then going via the metastore would be better because the partitions are named there, Hive stores extra useful information about your table, and then you're not reliant on knowing the direct path to the files on disk from the Spark code.
Not sure why you think you need to read/write SQL, though.
Use the Dataframe API instead, e.g
```py
df = spark.table("table_name")
df_2018 = df.filter(df['year'] == 2018)
df_2018.show()
``` | Your data isn't stored in a way optimal for parquet so you'd have to load files one by one and add the dates
Alternatively, you can move the files to a directory structure fit for parquet
( e.g. .../table/year=2018/month=10/day=29/file.parquet)
then you can read the parent directory (table) and filter on year, month, and day (and spark will only read the relevant directories) also you'd get these as attributes in your dataframe | 2,889 |
12,568,689 | I am new to python (2nd) day and working on a problem that asks me to Write a program that reads ASCII files (asks for file name as input), checks if it has more than
two words and prints out the two first words of the file on screen.
Its a little vague but I am going to assume the file is all str, deliminiated by spaces.
ex.
```
text1 text2 text text text
```
So far I have:
```
name = (raw_input("Please enter the name of the file: "))
f=open(name)
with codecs.open(name, encoding='utf-8') as f:
for line in f:
line = line.lstrip(BOM)
words=line.split()
print words
if len(words) > 2:
print 'There are more than two words'
firsttow = words[:2]
print firstrow
```
I am having problems writing the else statement, I want to have,
```
if len(words) > 2:
print 'There are more than two words'
firsttow = words[:2]
print firstrow
else:
if len(words) <2:
print 'There are under 2 words, no words will be shown'
```
How should this be added and is there any other ways to improve my code for this questions?
I really appreciate the help
Thanks in advance
\*Edit: Thanks for all the help, the last problem I had was when i run .py file, I want to be able to see the results before the cmd window closes.
Adding: `raw_input("Press return to close this window...")` does notwork and it closes right away. Any ideas?
Edit2\* This is my current code, still trying to work on having the cmd window open after
```
import codecs
BOM = codecs.BOM_UTF8.decode('utf8')
name = (raw_input("Please enter the name of the file: "))
with codecs.open(name, encoding='utf-8') as f:
words=[] #define words here
for line in f:
line = line.lstrip(BOM)
words.extend(line.split()) #append words from each line to words
if len(words) > 2:
print 'There are more than two words'
firstrow = words[:2]
print firstrow #indentation problem here
elif len(words) <2: #use if
print 'There are under 2 words, no words will be shown'
raw_input("Press return to close this window...")
``` | 2012/09/24 | [
"https://Stackoverflow.com/questions/12568689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1690243/"
] | That code should be written as:
```
if len(words) > 2:
print 'There are more than two words'
firsttow = words[:2]
print firstrow
elif len(words) <2:
print 'There are under 2 words, no words will be shown'
```
Note the indentation, and the use of `elif` (which means "else if"). | ```
with codecs.open(name, encoding='utf-8') as f:
words=[] #define words here
for line in f:
line = line.lstrip(BOM)
words.extend(line.split()) #append words from each line to words
if len(words) > 2:
print 'There are more than two words'
firsttow = words[:2]
print firstrow #indentation problem here
if len(words) <2: #use if
print 'There are under 2 words, no words will be shown'
``` | 2,890 |
5,093,153 | I'm wondering how to go about implementing a macro recorder for a python gui (probably PyQt, but ideally agnostic). Something much like in Excel but instead of getting VB macros, it would create python code. Previously I made something for Tkinter where all callbacks pass through a single class that logged actions. Unfortunately my class doing the logging was a bit ugly and I'm looking for a nicer one. While this did make a nice separation of the gui from the rest of the code, it seems to be unusual in terms of the usual signals/slots wiring. Is there a better way?
The intention is that a user can work their way through a data analysis procedure in a graphical interface, seeing the effect of their decisions. Later the recorded procedure could be applied to other data with minor modification and without needing the start up the gui. | 2011/02/23 | [
"https://Stackoverflow.com/questions/5093153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98967/"
] | Thinking in high level, this is what I'd do:
Develop a decorator function, with which I'd decorate every event-handling functions.
This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to mark Widget and Control instances as a special type of object. That is because in other runs these widgets won't be the same instances - ah, you can't even serialize a toolkit widget instances, be it Qt or otherwise.
When the time comes to play a macro, you fill-in the gaps replacing the widget-representating object with the instances of the actually running objects, and simply call the original functions with the remaining parameters.
In toolkits that have an specialized "event" parameter that is passed down to event-handling functions, you will have to take care of serializing and de-serializing this event as well.
I hope this can help. I could come up with some proof of concept code for that (although I am in a mood to use tkinter today - would have to read a lot to come up with a Qt4 example). | An example of what you're looking for is in [mayavi2](http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/application.html#automatic-script-generation). For your purposes, mayavi2's "script record" functionality will generate a Python script that can then be trivially modified for other cases. I hear that it works pretty well. | 2,891 |
2,032,706 | i have been trying to running some pinax code inside pydev eclipse
i keep on having this error
Error: Can't import Pinax. Make sure you are in a virtual environment that has Pinax installed or create one with pinax-boot.py.
my question is how do i run pinax inside eclipse using django built in server
i am python newbie | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81850/"
] | How about
```
map.connect ':user/:repo/commit/:sha', :action => :index
```
Or use `map.resource` instead of `map.connect` if you need a RESTful route.
In the controller, the URL information can be retrieved from params, for example `params[:user]` returns the username. | You can name your routes as you like, and specify which controllers and actions you'd like to use them with.
For example, you might have:
```
map.connect ':user/:repo/commit/:sha', :controller => 'transactions', :action => 'commit'
```
This would send the request to the 'commit' method in 'transactions' controller.
The other variables can then be accessed in your controller using params:
```
@user = User.find(params[:user])
@repo = Repo.find(params[:repo])
``` | 2,893 |
7,321,113 | I'm using Cairo/RSVG based solution for rasterizing SVG to PNG. It's already beeb described on StackOverflow in [Convert SVG to PNG in Python](https://stackoverflow.com/questions/6589358/convert-svg-to-png-in-python).
However, this solution doesn't seem to work with custom fonts.
I've found [this page describing embedding SVG fonts](http://frabru.de/c.php/article/SVGFonts-usage).
I've tried to include them from external SVG via XLink, as described in example. I've tried embedding the font directly in the same SVG file. Having failed with that, I've tried CSS Web Fonts syntax. None of the 3 methods works when rendering with Cairo (nor does it work in the Ubuntu's default viewer Eye of GNOME).
I've tried ImageMagick, with exactly same results as Cairo.
On the other hand with all 3 font embedding methods, fonts are rendered fine in WebKit, either using Google Chrome or [webkit2png.py](https://github.com/AdamN/python-webkit2png). However, if possible I'd like to avoid using QT WebKit on server, as it's non-trivial setup (including xvfb etc.), and I'm afraid that might not result very efficient nor stable.
Is there any alternative method of rendering SVG to PNG from Python? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7321113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] | I have spent a week researching this very issue and concluded that the best way to handle server-side rendering/rasterizing of SVG with custom fonts is to install those fonts on the server. The tools I tried (rsvg, imagemagick, phantomjs, qtwebkit...) could not handle web fonts and svg fonts.
Google has [several hundred fonts](http://code.google.com/p/googlefontdirectory/) (and growing) that one can download and use on a server.
* Download OTF or TTF fonts
* Install them on the server and refresh the font cache
* Replace the CSS definitions of the external fonts with font family names in your SVG docs.
And if you also need to use those same fonts in a web page, you could link to Google CDN directly for the WOFF files to conserve your own server time and network bandwidth. | You can try to use [inkscape](http://www.inkscape.org), perhaps this gives you better results:
```
inkscape inputfile.svg --export-png=exportfile.png
```
Running this from python is described here: [Calling an external command in Python](https://stackoverflow.com/questions/89228/how-to-call-external-command-in-python) | 2,896 |
66,977,521 | I want to run arbitrary "code" in an argument like an anonymous function in Python.
How to do this in one single line?
Lambdas seems that does not work since they only take one expression.
```
def call_func(callback):
callback()
def f():
pkg_set_status(package_name, status)
print('ok')
call_func(f)
```
Update:
Adding some context since the question is not entirely clear in my opinion.
I would like to run something like a multiline lambda or anonymous function.
Something like:
```
call_func(lambda:
# my multiline code here
pkg_set_status(package_name, status)
print('ok')
)
```
so that the argument itself is the anonymous function body...
Update2: found the answer here
<https://softwareengineering.stackexchange.com/questions/99243/why-doesnt-python-allow-multi-line-lambdas>
Looks like python does not support multiline lambdas by design. | 2021/04/06 | [
"https://Stackoverflow.com/questions/66977521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274630/"
] | The structure defined by myList with the `<ol>` elements is never actually added to the document. If you concatenate the `<ol>`, then the `<li>` entries, then `</ol>` all to wrapper.innerHTML then it should work.
For example something like...
```
var myList = "<ol>";
for (var i = 0; i < properties.length; i++) {
myList += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
myList += "</ol>";
wrapper.innerHTML = myList;
``` | If you would check your structure in dev tools you would see there was no `ol` element in finale result.
So you can create it:
```
var myList = document.createElement("ol");
```
Then fill it with `li`:
```
myList.innerHTML
```
And then insert it:
```
idk.insertAdjacentElement("afterbegin", myList);
```
```js
function onloadFunction() {
var properties = [{
unitNo: "C-8-1",
owner: "Foo Yoke Wai"
},
{
unitNo: "C-3A-3A",
owner: "Chia Kim Hooi"
},
{
unitNo: "B-18-8",
owner: "Heng Tee See"
},
{
unitNo: "A-10-10",
owner: "Tang So Ny"
},
{
unitNo: "B-19-10",
owner: "Tang Xiao Mi"
},
];
var idk = document.getElementById("wrapper");
var myList = document.createElement("ol");
for (var i = 0; i < properties.length; i++) {
myList.innerHTML += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
idk.insertAdjacentElement("afterbegin", myList);
}
```
```html
<html>
<body onload="onloadFunction()">
<head></head>
<div id="wrapper"></div>
</body>
</html>
``` | 2,899 |
46,966,690 | I have data like this:
```
0,tcp,http,SF,181,5450,0.11,0.00,0.00,0.00,,normal.
0,tcp,http,SF,239,486,0.05,0.00,0.00,0.00,normal.
0,tcp,http,SF,235,1337,0.03,0.00,0.00,0.00,normal.
0,tcp,http,SF,219,1337,0.03,0.00,0.00,0.00,normal.
```
The original data was stored in txt. I used list to store them in python. But the format is string. Then I want to change some columns of string into int like this:
```
'181' to 181
```
Could anyone can help me? Thank you! | 2017/10/27 | [
"https://Stackoverflow.com/questions/46966690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7428504/"
] | When accessing data or methods from within the vue object, use `this.thing`. In your case, that would be `this.strSlug(this.shop.name)`. | Does not work even with 'this.' because that function has not been defined at the time data is being initialized. I think you have to do it in the created() life-cycle hook. | 2,902 |
61,605,694 | I'm implementing a two-link acrobot simulation using pydrake and would like to enforce joint limits to prevent the lower link from colliding with the upper link. I've added the joint limits to the URDF and am parsing this URDF to generate an acrobot multibodyplant object. I've used functions to successfully verify that the joint limit is being parsed (position\_lower\_limits(), position\_upper\_limits()), but my simulation is not responding to those limits. I'd really appreciate some help in identifying why this may be.
I'm creating and simulating the acrobot multibodyplant as follows:
```
plt_is_interactive = SetupMatplotlibBackend()
builder = DiagramBuilder()
# instantiate the pendulum and the scene graph
double_pendulum, scene_graph = AddMultibodyPlantSceneGraph(
builder,
time_step=0.01 # discrete update period
)
# parse the urdf
urdf_path = 'double_pendulum_no_shoulder.urdf'
Parser(double_pendulum).AddModelFromFile(urdf_path)
double_pendulum.Finalize()
#Simulation Set-Up
# Set the constant torque
torque_system = builder.AddSystem(ConstantVectorSource([[0.]]))
builder.Connect(torque_system.get_output_port(0), double_pendulum.get_input_port(3))
visualizer = builder.AddSystem(
PlanarSceneGraphVisualizer(scene_graph, xlim=[-10., 10.], ylim=[-10., 10.], show=plt_is_interactive))
builder.Connect(scene_graph.get_pose_bundle_output_port(),
visualizer.get_input_port(0))
diagram = builder.Build()
simulator = Simulator(diagram)
context = simulator.get_mutable_context()
plant_context = diagram.GetMutableSubsystemContext(double_pendulum, context)
double_pendulum.SetPositionsAndVelocities(plant_context, [2, 0, 0, 0])
# Simulate
duration = 10.0 if get_ipython() else 0.1 # sets a shorter duration during testing
context.SetTime(0.0)
AdvanceToAndVisualize(simulator, visualizer, duration)
```
and my URDF contains the following line within the associated joint to attempt to enforce joint limits.
```
<limit lower="-2.35" upper="2.35"/>
``` | 2020/05/05 | [
"https://Stackoverflow.com/questions/61605694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13471747/"
] | I just tried to reproduce, and was also surprised that it doesn't appear to work.
Here is a runnable reproduction that violates the joint lower limit at the elbow, which is set to 0.0.
It also prints out the limit from the joint, confirming that the parsing worked.
<https://www.dropbox.com/s/2m12ws0g88t5uei/joint_limits_test.py?dl=0>
<https://www.dropbox.com/s/fdjb4uv4m2i17i8/double_pendulum.urdf?dl=0> | >
> ...but my simulation is not responding to those limits
>
>
>
what do you mean exactly?.
First, you should know that our joint limits are "soft", meaning that they are not constraints but more like stiff springs. `MultibodyPlant` computes the stiffness of these springs automatically for you to ensure the stability of our solvers.
It's a function of the time step. The smaller the time step, the stiffer the joint limits are; they converge to the rigid limit quadratically with time step.
That being said, I see your time step is pretty large (10 ms). It might be your limits are just too soft and that's what you observe in the simulation results.
Given you verified the correct parsing (I will trust you on that one), I'd suggest you run with a smaller time steps first as to verify this hypothesis. You should observe the quadratic convergence with time step. | 2,904 |
57,221,919 | I try to install `docker-ce` on `redhat 8` but it failed
first, I try
```
# systemctl enable docker
Failed to enable unit: Unit file docker.service does not exist.
```
So, I want to install `docker-ce` for the daemon
```
# yum install yum-utils
# yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
# yum repolist -v
# yum list docker-ce --showduplicates | sort -r
# yum install docker-ce
```
but in this step, I have got this :
```
# yum install docker-ce
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Last metadata expiration check: 0:02:58 ago on Fri 26 Jul 2019 02:11:48 PM UTC.
Error:
Problem: package docker-ce-3:19.03.1-3.el7.x86_64 requires containerd.io >= 1.2.2-3, but none of the providers can be installed
- cannot install the best candidate for the job
- package containerd.io-1.2.2-3.3.el7.x86_64 is excluded
- package containerd.io-1.2.2-3.el7.x86_64 is excluded
- package containerd.io-1.2.4-3.1.el7.x86_64 is excluded
- package containerd.io-1.2.5-3.1.el7.x86_64 is excluded
- package containerd.io-1.2.6-3.3.el7.x86_64 is excluded
(try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages)
```
I create a redhat account, but I have got this problem :
```
# subscription-manager register --force
Registering to: subscription.rhsm.redhat.com:443/subscription
Username: xxxxxxxxxxx
Password:
The system has been registered with ID: 6c07b574-2601-4a84-90d4-a9dfdc499c2f
The registered system name is: ip-172-31-11-95.us-east-2.compute.internal
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/dnf/repo.py", line 566, in load
ret = self._repo.load()
File "/usr/lib64/python3.6/site-packages/libdnf/repo.py", line 503, in load
return _repo.Repo_load(self)
RuntimeError: Failed to synchronize cache for repo 'rhui-client-config-server-8'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib64/python3.6/site-packages/subscription_manager/cache.py", line 173, in update_check
self._sync_with_server(uep, consumer_uuid)
File "/usr/lib64/python3.6/site-packages/subscription_manager/cache.py", line 477, in _sync_with_server
combined_profile = self.current_profile
File "/usr/lib64/python3.6/site-packages/subscription_manager/cache.py", line 430, in current_profile
module_profile = get_profile('modulemd').collect()
File "/usr/lib64/python3.6/site-packages/rhsm/profile.py", line 347, in get_profile
profile = PROFILE_MAP[profile_type]()
File "/usr/lib64/python3.6/site-packages/rhsm/profile.py", line 54, in __init__
self.content = self.__generate()
File "/usr/lib64/python3.6/site-packages/rhsm/profile.py", line 76, in __generate
base.fill_sack()
File "/usr/lib/python3.6/site-packages/dnf/base.py", line 400, in fill_sack
self._add_repo_to_sack(r)
File "/usr/lib/python3.6/site-packages/dnf/base.py", line 135, in _add_repo_to_sack
repo.load()
File "/usr/lib/python3.6/site-packages/dnf/repo.py", line 568, in load
raise dnf.exceptions.RepoError(str(e))
dnf.exceptions.RepoError: Failed to synchronize cache for repo 'rhui-client-config-server-8'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/sbin/subscription-manager", line 11, in <module>
load_entry_point('subscription-manager==1.23.8', 'console_scripts', 'subscription-manager')()
File "/usr/lib64/python3.6/site-packages/subscription_manager/scripts/subscription_manager.py", line 85, in main
return managercli.ManagerCLI().main()
File "/usr/lib64/python3.6/site-packages/subscription_manager/managercli.py", line 2918, in main
ret = CLI.main(self)
File "/usr/lib64/python3.6/site-packages/subscription_manager/cli.py", line 183, in main
return cmd.main()
File "/usr/lib64/python3.6/site-packages/subscription_manager/managercli.py", line 506, in main
return_code = self._do_command()
File "/usr/lib64/python3.6/site-packages/subscription_manager/managercli.py", line 1368, in _do_command
profile_mgr.update_check(self.cp, consumer['uuid'], True)
File "/usr/lib64/python3.6/site-packages/subscription_manager/cache.py", line 457, in update_check
return CacheManager.update_check(self, uep, consumer_uuid, force)
File "/usr/lib64/python3.6/site-packages/subscription_manager/cache.py", line 183, in update_check
raise Exception(_("Error updating system data on the server, see /var/log/rhsm/rhsm.log "
Exception: Error updating system data on the server, see /var/log/rhsm/rhsm.log for more details.
``` | 2019/07/26 | [
"https://Stackoverflow.com/questions/57221919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11841974/"
] | yum install docker-ce --no-best worked for me
( Installed: docker-ce-3:18.09.1-3.el7.x86\_64 and Skipped: docker-ce-3:19.03.1-3.el7.x86\_64) | My guess, due to a missing subscription you cannot download packages from repositories the docker-ce package needs. So first register for a development account with redhat, then subscribe your host using the subscription Manager (remember, no production usage allowed then) and then retry the installation.
Edit: Here are the subscription commands
```
subscription-manager register --username <yourname> --password <pw>
subscription-manager role --set="Red Hat Enterprise Linux Server"
subscription-manager service-level --set="Self-Support"
subscription-manager usage --set="Development/Test"
subscription-manager attach
```
Edit: sorry i answered too fast. Just tried on a new rhel8. docker-ce-18.06.3.ce-3.el7 is the most current Version for rhel 8 and installs fine | 2,906 |
28,299,754 | ```
a = [(24, 13), (23, 13), (22, 13), (21, 13), (20, 13),
(19, 13), (19, 14), (19, 15), (18, 15), (17, 15),
(16, 15), (15, 15), (14, 15), (13, 15), (13, 14),
(13, 13), (13, 12), (13, 11), (13, 10), (12, 10),
(11, 10), (10, 10), (9, 10), (8, 10), (7, 10),
(7, 9), (7, 8), (7, 7), (7, 6), (7, 5), (7, 4),
(6, 4), (5, 4), (4, 4)]
```
The above path (set of unique coordinates) has 6 turns.
Could anyone please help me code the same in python?
For example, for the above list `a` , the output should be `6`.
```
length = len(a)-3
print length
for i in range(0,length):
x1,y1 = a[i]
x2,y2 = a[i+1]
x3,y3 = a[i+2]
if y1 is y2:
if y1 is y3:
x_flag = 1
else:
x_flag = 0
if x_flag is 0:
flag1 += 1
print 'Turn'
print flag1
``` | 2015/02/03 | [
"https://Stackoverflow.com/questions/28299754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296482/"
] | Probably not the prettiest solution, but the straightforward way would be this:
```
a = [(24, 13), (23, 13), (22, 13), (21, 13), (20, 13),
(19, 13), (19, 14), (19, 15), (18, 15), (17, 15),
(16, 15), (15, 15), (14, 15), (13, 15), (13, 14),
(13, 13), (13, 12), (13, 11), (13, 10), (12, 10),
(11, 10), (10, 10), (9, 10), (8, 10), (7, 10),
(7, 9), (7, 8), (7, 7), (7, 6), (7, 5), (7, 4),
(6, 4), (5, 4), (4, 4)]
count = 0
direction = -1
for i in range(1,len(a)):
current_dir = 0 if a[i][0]-a[i-1][0] != 0 else 1
if direction != -1:
if current_dir != direction:
# print("changing direction")
count += 1
direction = current_dir
print count
```
It assumes you are only ever changing one direction (i.e. never moving diagonally). | you can convert the tuples to numpy array, and check if after two legs, you moved in both axis.
```
arr = np.array(a)
((np.abs(arr[2:] - arr[:-2])>0).sum(axis=1)==2).sum()
``` | 2,911 |
71,040,681 | I have a Rancher Deskop(dockerd) on M1 MacOS and when I am trying to build below dockerfile I am getting an error such as below. Here is the command how I am trying to build the image `docker build -t te-grafana-dashboards-toolchain --no-cache .`
I tried to change the platforms but nonae of them worked for me. I am a bit lost about this platform issue for M1 but any help will be appreciated, What I am doing wrong? What might the root cause of this?
```
Removing intermediate container 70af516d5d6b
---> a69229847153
Step 5/6 : RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
---> Running in 13545862fffe
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
Removing intermediate container 13545862fffe
```
Dockerfile
```
FROM --platform=linux/amd64 ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-amd64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-amd64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-amd64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb; ln -s $(go env GOPATH)/bin/jb /usr/bin/jb
WORKDIR /workspace
``` | 2022/02/08 | [
"https://Stackoverflow.com/questions/71040681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12530530/"
] | Incidentally, in case it's helpful to another who lands here, I have the same issue on an M1 Max MacBook Pro laptop attempting to do a `docker build` from a company repo that should be a pretty well traveled path, but I might be the only one (it's a small company) that has an ARM64 M1 "Apple Silicon" Mac. ***However I found the solution (well, a solution) to my situation was exactly the opposite of the solution to the OP's, and that was to add*** `--platform=linux/amd64` ***to the FROM line of the docker file.***
Otherwise it was using an ARM64 image to start from without me being the wiser but then later in the Dockerfile the build attempts to install and execute code compiled for x86\_64. Starting the build process by requesting the base image be `linux/amd64` ends up with then the base image having `/lib64/ld-linux-x86-64.so.2`. This probably means everything is being emulated as x86\_64 on the ARM64 CPU via `qemu-x86_64` and so if you have the option to start from an ARM64 image and can compile within the container during build time any software you can't install as ARM64 binaries, it'll probably go faster when you later run the container on the M1 based Mac. I'm not able to try that myself just yet for this case. | this resolved my issue.
```
FROM ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-arm64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-arm64.tar.gz -C /etc/golang; ln -s /etc/golang/go/bin/go /usr/bin/go; rm -f go1.17.linux-arm64.tar.gz
RUN GO111MODULE="on" go get github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb@latest; ln -s /root/go/bin/jb /usr/bin/jb
WORKDIR /workspace
``` | 2,913 |
10,851,121 | I am trying to use python to extract certain information from html code.
for example:
```
<a href="#tips">Visit the Useful Tips Section</a>
and I would like to get result : Visit the Useful Tips Section
<div id="menu" style="background-color:#FFD700;height:200px;width:100px;float:left;">
<b>Menu</b><br />
HTML<br />
CSS<br />
and I would like to get Menu HTML CSS
```
In other word, I wish to get everything between <>and<>
I am trying to write a python function that takes the html code as a string, and then extract information from there. I am stuck at string.split('<'). | 2012/06/01 | [
"https://Stackoverflow.com/questions/10851121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1401233/"
] | You should use a proper HTML parsing library, such as the [HTMLParser](http://docs.python.org/library/htmlparser.html) module. | ```
string = '<a href="#tips">Visit the Useful Tips Section</a>'
re.findall('<[^>]*>(.*)<[^>]*>', string) //return 'Visit the Useful Tips Section'
``` | 2,922 |
2,509,927 | i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful.... | 2010/03/24 | [
"https://Stackoverflow.com/questions/2509927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275695/"
] | You can use the [system](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/system.html) command to execute the Python code externally. To link it in more "natively" I think you'll have to go through C. That is, embed your Python code in C code and then expose it with a DLL to Matlab.
P.S. On windows you can also expose Python code to Matlab via COM | There is a library called [PyMat](http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html). It allows to call python code from matlab. | 2,930 |
39,136,134 | **cat test.py**
```
from importlib import import_module
bar = import_module('bar', package='project')
```
**ls project/**
```
__init__.py
__init__.pyc
bar.py
bar.pyc
```
**python test.py**
```
Traceback (most recent call last):
File "test.py", line 5, in <module>
bar = import_module('bar', package='project')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named bar
```
Listing imported modules (sys.modules) doesn't show any module *project*.
I can import *bar* using the python shell.
Any ideas? | 2016/08/25 | [
"https://Stackoverflow.com/questions/39136134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1252307/"
] | It needs a dot in front of bar .. :-(
```
bar = import_module('.bar', package='project')
``` | The documentation for [import\_lib](https://docs.python.org/2/library/importlib.html) says that
>
> If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import\_module('..mod', 'pkg.subpkg') will import pkg.mod).
>
>
>
Thus the expression can also be written as
```
bar = import_module('..bar',package='project.bar')
``` | 2,935 |
43,600,114 | Im using python 3.4 and I am trying to make a recursive guessing game. The game should take a min value and a max value and have a "magic" number. The game is going to generate a random number in between the range of x and y. Then ask the user to insert y for yes l for too low, and h for too high. if it is yes 'congratulations message', then exit. if it is too low, take the min val x, and add 1 to it and that will be the new min value. Same logic for h too high. Then re generate random number. Im getting stuck on where to call the recursion.
```
def recursive_guess(x,y,):
correct = False
while not correct:
print('I will guess a number y for yes, l for too low, h for too high')
guess = random.randrange(x, y)
print(guess)
anwser = input('y for yes l for low h for high')
if anwser == 'y':
print('Got it right')
correct = True
elif anwser == 'l':
guess = random.randrange(minVal + 1, maxVal)
elif anwser == 'h':
guess = random.randomrange(minVal, maxVal-1)
``` | 2017/04/25 | [
"https://Stackoverflow.com/questions/43600114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7916637/"
] | This can be done with a simple function using four `if` statements to avoid adding out-of-bounds values:
```
#include <stdio.h>
#define BOARD_SZ 10
int sum_neighborhood(int, int, int [][BOARD_SZ], int, int);
int main(void)
{
int board[BOARD_SZ][BOARD_SZ] = { { 1, 0, 0, 1, 1, 1, 1, 1, 0, 1 },
{ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 1, 0, 1, 1, 1 },
{ 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 0, 1, 1, 0 },
{ 1, 1, 1, 1, 1, 1, 0, 0, 1, 1 },
{ 0, 1, 0, 0, 1, 0, 1, 0, 1, 0 },
{ 0, 1, 0, 0, 0, 1, 1, 0, 0, 1 },
{ 1, 1, 0, 1, 1, 0, 1, 0, 0, 0 } };
printf("Sum at [0][0] is %d\n",
sum_neighborhood(0, 0, board, BOARD_SZ, BOARD_SZ));
printf("Sum at [0][1] is %d\n",
sum_neighborhood(0, 1, board, BOARD_SZ, BOARD_SZ));
printf("Sum at [5][3] is %d\n",
sum_neighborhood(5, 3, board, BOARD_SZ, BOARD_SZ));
return 0;
}
int sum_neighborhood(int row, int col, int arr[][BOARD_SZ], int rows, int cols)
{
int sum = arr[row][col];
if (row - 1 >= 0) {
sum += arr[row-1][col];
}
if (row + 1 < rows) {
sum += arr[row+1][col];
}
if (col - 1 >= 0) {
sum += arr[row][col-1];
}
if (col + 1 < cols) {
sum += arr[row][col+1];
}
return sum;
}
```
Program output:
```none
Sum at [0][0] is 2
Sum at [0][1] is 2
Sum at [5][3] is 5
``` | ```
int add(const int **arr, size_t nrows, size_t ncols)
{
int sum = 0;
for (size_t i = 0; i < nrows; ++i)
for (size_t j = 0; j < ncols; ++j)
sum += arr[i][j];
return sum;
}
```
Use a pair of nested loops to walk the rows and columns. | 2,936 |
11,463,749 | I visited <http://www.sublimetext.com> today and was intrigued by the screencast animation the website has on its opening page. It looks like a mashup between video and slideshow. I've seen them at other modern websites as well, but I assumed it was some HTML5 video tag trickery. But when I looked at the source of sublimetext webpage, I was confused.
The animation on this page is created on a HTML5 2D canvas with plain javascript using base PNG images. Each slide is loaded from a PNG file. The animation is achieved by modifying only handful of pixels from the image. The animation javascript applied these changes on the original PNGs at regular intervals. You will find these deltas stored in \*\_timeline variables in the script.
My question is what tool can generate such deltas? How can one record one's desktop screen and create such base PNG + animation deltas?
I like this approach because it seems most efficient format for screencasts, where changes in consecutive frames are minimal.
**Update 1** I know there are techniques to achieve this using GIF (Check <https://askubuntu.com/q/107726>), but what cool tool can generate this javascript code that can convert PNG deltas to animation. Googling hasn't helped me find it out.
**Update 2** The author of the screencast (and sublimetext) replied to my question on sublimetext forum. He did it using a custom python script and plans to write a blog post about it sometime <http://www.sublimetext.com/forum/viewtopic.php?p=34252#p34252> | 2012/07/13 | [
"https://Stackoverflow.com/questions/11463749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174527/"
] | Jon Skinner, the creator of Sublime Text wrote about the process [on his website](http://www.sublimetext.com/~jps/animated_gifs_the_hard_way.html)
He also published the encoder he wrote [on GitHub](https://github.com/sublimehq/anim_encoder) | look at one of their images and you'll understand how it works:
<http://www.sublimetext.com/anim/command_palette_packed.png>
they just cutting and inserting appropriate portions of image into the appropriate positions of canvas element, but if your question is how to make such image, I don't have an idea.
I guess with some software, not by hand, but I don't know such soft... | 2,938 |
52,678,981 | I'm new to programing on python and working with scrapy. I am facing an error with the web crawling. I have used similar help pages on this site and even followed a tutorial from beginning to end to no avail, any help will be appreciated.
Error says: Spider error processing http://quotes.toscrape.com/> (referer: None) Traceback (most recent call last):
I found some similar code and similar one is runing well
but what i write isn't
Here is my code:
```
#-*- coding: utf-8 -*-
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["quotes.toscrape.com"]
start_urls = (
'http://quotes.toscrape.com/',
)
def parse(self, response):
quotes = response.xpath('//*[@class="quote"]')
for quote in quotes:
text = quote.xpath('.//*[@class="text"]/text()').extract_first()
author = quote.xpath('.//*[@itemprop="author"]/text()').extract_first()
tags = quote.xpath('.//*[@itemprop="keywords"]/@content').extract_first()
print '\n'
print text
print author
print tags
print '\n'
next_page_url = response.xpath('//*[@class="next"]/a/@href').extract_first()
absolute_next_page_url = response.urljoin(next_page_url)
yield scrapy.Request(absolute_next_page_url)
```
Here is command promp:
```
C:\Users\cancun\Desktop\Dosyalar\Coding\Phyton\Spider\quotes_spider>scrapy crawl quotes
2018-10-06 14:42:07 [scrapy.utils.log] INFO: Scrapy 1.5.1 started (bot: quotes_spider)
2018-10-06 14:42:07 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.0, w3lib 1.19.0, Twisted 18.7.0, Python 2.7.15 |Anaconda, Inc.| (default, May 1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)], pyOpenSSL 18.0.0 (OpenSSL 1.0.2o 27 Mar 2018), cryptography 2.2.2, Platform Windows-10-10.0.16299
2018-10-06 14:42:07 [scrapy.crawler] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'quotes_spider.spiders', 'SPIDER_MODULES': ['quotes_spider.spiders'], 'BOT_NAME': 'quotes_spider'}
2018-10-06 14:42:07 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
2018-10-06 14:42:07 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2018-10-06 14:42:07 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2018-10-06 14:42:07 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-10-06 14:42:07 [scrapy.core.engine] INFO: Spider opened
2018-10-06 14:42:07 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-10-06 14:42:07 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6024
2018-10-06 14:42:07 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/> (referer: None)
2018-10-06 14:42:07 [scrapy.core.scraper] ERROR: Spider error processing <GET http://quotes.toscrape.com/> (referer: None)
Traceback (most recent call last):
File "c:\programdata\anaconda2\lib\site-packages\scrapy\utils\defer.py", line 102, in iter_errback
yield next(it)
File "c:\programdata\anaconda2\lib\site-packages\scrapy\spidermiddlewares\offsite.py", line 30, in process_spider_output
for x in result:
File "c:\programdata\anaconda2\lib\site-packages\scrapy\spidermiddlewares\referer.py", line 339, in <genexpr>
return (_set_referer(r) for r in result or ())
File "c:\programdata\anaconda2\lib\site-packages\scrapy\spidermiddlewares\urllength.py", line 37, in <genexpr>
return (r for r in result or () if _filter(r))
File "c:\programdata\anaconda2\lib\site-packages\scrapy\spidermiddlewares\depth.py", line 58, in <genexpr>
return (r for r in result or () if _filter(r))
File "C:\Users\cancun\Desktop\Dosyalar\Coding\Phyton\Spider\quotes_spider\quotes_spider\spiders\quotes.py", line 20, in parse
print text
File "c:\programdata\anaconda2\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u201c' in position 0: character maps to <undefined>
2018-10-06 14:42:07 [scrapy.core.engine] INFO: Closing spider (finished)
2018-10-06 14:42:07 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 218,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 2333,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2018, 10, 6, 11, 42, 7, 594000),
'log_count/DEBUG': 2,
'log_count/ERROR': 1,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'spider_exceptions/UnicodeEncodeError': 1,
'start_time': datetime.datetime(2018, 10, 6, 11, 42, 7, 309000)}
2018-10-06 14:42:07 [scrapy.core.engine] INFO: Spider closed (finished)
```
Thanks! | 2018/10/06 | [
"https://Stackoverflow.com/questions/52678981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10465578/"
] | The problem is your command prompt uses [cp437](https://en.wikipedia.org/wiki/Code_page_437) character set, which doesn't support some characters that you have just scraped (for example, “ and ”)
I don't think it is possible to print that characters to windows shell (maybe new PowerShells support it, I don't know). You may create a new file, select a rich character set for it, and write all your output there:
```
import io
out_file = io.open('output.txt', 'a', encoding='UTF-8')
```
If you really want to use the default character encoding that your operating system uses, create the file like that:
```
import io
out_file = io.open('output.txt', 'a', errors='backslashreplace')
```
With the latter option, you will see something like that:
```
\u201cThe world as we have created it is a process of our thinking.\u201d
``` | I change a little my code and its work the way expected here is updated code:
```
#-*- coding: utf-8 -*-
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["quotes.toscrape.com"]
start_urls = (
'http://quotes.toscrape.com/',
)
def parse(self, response):
quotes = response.xpath('//*[@class="quote"]')
for quote in quotes:
text = quote.xpath('.//*[@class="text"]/text()').extract_first()
author = quote.xpath('.//*[@itemprop="author"]/text()').extract_first()
tags = quote.xpath('.//*[@itemprop="keywords"]/@content').extract_first()
yield{'Text':text,
'Author':author,
'Tags':tags}
next_page_url = response.xpath('//*[@class="next"]/a/@href').extract_first()
absolute_next_page_url = response.urljoin(next_page_url)
yield scrapy.Request(absolute_next_page_url)
```
Thanks for all the support!!! | 2,939 |
356,138 | I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.
I've tried `sys.stdout = os.fdopen(1, 'w')`, but anything written there won't get to my browser.
The same application works without difficulty under Apache.
I'm using the Microsoft-provided FastCGI extension for IIS documented here: <http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/>
I am using these settings in fcgiext.ini:
```
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
```
Can anyone tell what's wrong or tell me where I should look to find out?
All suggestions greatly appreciated... | 2008/12/10 | [
"https://Stackoverflow.com/questions/356138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44992/"
] | Forgive me if this is a dumb question, but I notice this line in your config file:
>
> Arguments=-u C:\app\app\_wsgi.py
>
>
>
Are you running a WSGI application or a FastCGI app? There *is* a difference. In WSGI, writing to stdout isn't a good idea. Your program should have an application object that can be called with an environment dict and a start\_response function (for more info, see [PEP 333](http://www.python.org/dev/peps/pep-0333/)). At any rate, your application's method of returning will be to return an iterable object that contains the response body, not writing to stdout.
Either way, you should also consider using [isapi-wsgi](http://code.google.com/p/isapi-wsgi/). I've never used it myself, but I hear good things about it. | On windows, it's possible to launch a proces without a valid stdin and stdout. For example, if you execute a python script with pythonw.exe, the stdout is invdalid and if you insist on writing to it, it will block after 140 characters or something.
Writing to another destination than stdout looks like the safest solution. | 2,940 |
41,231,316 | I've been trying to write this reduce method and I can't find a nice way to do it in java. I managed in python but it makes use of lots of python stuff and porting that to java seems like a real pain. Is there a more java way to do it?
Here's some test code, that should show what I mean if the title wasn't clear.
My python test code:
```
def reduce_(duplicated):
def get_factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
factors = sorted(list(get_factors(len(duplicated))))
for factor in factors:
chunks = set([tuple(duplicated[i:i + factor]) for i in xrange(0, len(duplicated), factor)])
if len(chunks) == 1:
return list(chunks.pop())
return duplicated
def verify(expected, duplicated):
try:
result = reduce_(duplicated)
assert (expected == result)
print expected, "passed"
except AssertionError:
print "expected", expected, "!=", duplicated
#should return the same
verify([1, 2, 3], [1,2,3])
verify([1,2], [1,2])
verify([1,1,2], [1,1,2])
verify([5,8,8], [5,8,8])
verify([8], [8])
verify([1,8,1], [1,8,1])
verify([5,2,2,5], [5,2,2,5])
verify([5,5,2,2], [5,5,2,2])
# repeated only once
verify([1, 2, 3], [1,2,3,1,2,3])
verify([1,2], [1,2,1,2])
verify([1,1,2], [1,1,2,1,1,2])
verify([5,8,8], [5,8,8,5,8,8])
verify([8], [8,8])
verify([1,8,1], [1,8,1,1,8,1])
verify([5,2,2,5], [5,2,2,5,5,2,2,5])
verify([5,5,2,2], [5,5,2,2,5,5,2,2])
# repeated twice
verify([1, 2, 3], [1,2,3,1,2,3,1,2,3])
verify([1,2], [1,2,1,2,1,2])
verify([1,1,2], [1,1,2,1,1,2,1,1,2])
verify([5,8,8], [5,8,8,5,8,8,5,8,8])
verify([8], [8,8,8])
verify([1,8,1], [1,8,1,1,8,1,1,8,1])
verify([5,2,2,5], [5,2,2,5,5,2,2,5,5,2,2,5])
verify([5,5,2,2], [5,5,2,2,5,5,2,2,5,5,2,2])
```
which you can run here: <https://repl.it/EthR/0>
And some Java test code for you which you can run here <https://www.compilejava.net/>
```
import java.util.*;
public class HelloWorld
{
public static <T> T[] reduce(T[] duplicated)
{
return duplicated; // implement me!
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
// should return the same
verify(new Integer[]{1, 2, 3}, new Integer[]{1,2,3});
verify(new Integer[]{1,2}, new Integer[]{1,2});
verify(new Integer[]{1,1,2}, new Integer[]{1,1,2});
verify(new Integer[]{5,8,8}, new Integer[]{5,8,8});
verify(new Integer[]{8}, new Integer[]{8});
verify(new Integer[]{1,8,1}, new Integer[]{1,8,1});
verify(new Integer[]{5,2,2,5}, new Integer[]{5,2,2,5});
verify(new Integer[]{5,5,2,2}, new Integer[]{5,5,2,2});
// repeated only once
verify(new Integer[]{1, 2, 3}, new Integer[]{1,2,3,1,2,3});
verify(new Integer[]{1,2}, new Integer[]{1,2,1,2});
verify(new Integer[]{1,1,2}, new Integer[]{1,1,2,1,1,2});
verify(new Integer[]{5,8,8}, new Integer[]{5,8,8,5,8,8});
verify(new Integer[]{8}, new Integer[]{8,8});
verify(new Integer[]{1,8,1}, new Integer[]{1,8,1,1,8,1});
verify(new Integer[]{5,2,2,5}, new Integer[]{5,2,2,5,5,2,2,5});
verify(new Integer[]{5,5,2,2}, new Integer[]{5,5,2,2,5,5,2,2});
// repeated twice
verify(new Integer[]{1, 2, 3}, new Integer[]{1,2,3,1,2,3,1,2,3});
verify(new Integer[]{1,2}, new Integer[]{1,2,1,2,1,2});
verify(new Integer[]{1,1,2}, new Integer[]{1,1,2,1,1,2,1,1,2});
verify(new Integer[]{5,8,8}, new Integer[]{5,8,8,5,8,8,5,8,8});
verify(new Integer[]{8}, new Integer[]{8,8,8});
verify(new Integer[]{1,8,1}, new Integer[]{1,8,1,1,8,1,1,8,1});
verify(new Integer[]{5,2,2,5}, new Integer[]{5,2,2,5,5,2,2,5,5,2,2,5});
verify(new Integer[]{5,5,2,2}, new Integer[]{5,5,2,2,5,5,2,2,5,5,2,2});
}
public static <T> void verify(final T[] expected, final T[] duplicated)
{
if (expected == null || duplicated == null) throw new ComparisonException("Cannot be null");
final T[] result = reduce(duplicated);
if (result == null) throw new ComparisonException("Cannot be null");
if (expected.length != result.length)
{
throw new ComparisonException("lengths do not match in " + Arrays.toString(expected) + " and " + Arrays.toString(result));
}
for (int i = 0; i < expected.length; i++)
{
if (!result[i].equals(expected[i]))
{
throw new ComparisonException("Elem [" + i + "] does not match in " + Arrays.toString(expected) + " and " + Arrays.toString(result));
}
}
System.out.println(Arrays.toString(expected) + " passed: " + Arrays.toString(result));
}
public static class ComparisonException extends RuntimeException
{
public ComparisonException(String message){ super(message);}
}
}
``` | 2016/12/19 | [
"https://Stackoverflow.com/questions/41231316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4058774/"
] | Not sure about "nice", but it works:
```
public static <T> T[] reduce(T[] duplicated)
{
int len = duplicated.length;
for (int i = 1; i <= len / 2; i++) {
if (len % i == 0) {
if (checkFactors(i, duplicated)) {
return Arrays.copyOf(duplicated, i);
}
}
}
return duplicated;
}
public static <T> boolean checkFactors(int factor, T[] arr) {
int len = arr.length;
for (int j = 1; j < len / factor; j++) {
if (!rangeCompare(j * factor, factor, arr)) {
return false;
}
}
return true;
}
public static <T> boolean rangeCompare(int off, int len, T[] arr) {
for (int i = 0; i < len; i++) {
if (!arr[i].equals(arr[off + i])) {
return false;
}
}
return true;
}
``` | So you want to test if an array is a smaller array repeated - now if, by your definition, `bigArray.length % smallArray.length != 0` means that it is NOT the smaller array repeated, I can give you a solution. In other words: If the smaller array doesn't fit inside the bigger array an even number of times, does that mean that it is NOT the smaller array repeated? If that's true, try this:
```
public boolean isArrayAnotherArrayRepeated(ArrayType[] bigArray, ArrayType[] smallType) {
double numberOfTimesSmallFitsInBig = bigArray.length / smallArray.length;
if (numberOfTimesSmallFitsInBig % 1 == 0)
{
//checks the condition mentioned above, i.e. that small doesn't fit into big an even number of times
return false;
}
for (int i = 0; i < (int) numberOfTimesSmallFitsInBig; i++)
{
for (int h = 0; h < smallArray.length; h++)
{
if (smallArray[h] != bigArray[i+h]) {
//note that you may have to use .equals here, if you don't want to compare references or primitive data types.
//that would then look like "if (!smallArray[h].equals(bigArray[i+h]))"
return false;
}
}
}
return true;
}
```
If this solution doesn't fit your needs, comment on my answer and I'll try to think of something else. It's late right now, though, otherwise I'd do so right now ^^
(Note that I've never done anything with Python, so I didn't bother trying to understand your code) | 2,946 |
46,028,830 | I've been fooling around with `__slots__` and searching about them a little, but I'm still confused about some specifics:
I'm aware that `__slots__` generates some kind of descriptors:
```py
>>> class C:
... __slots__ = ('x',)
...
>>> C.x
<member 'x' of 'C' objects>
>>> C.x.__get__
<method-wrapper '__get__' of member_descriptor object at 0x7f001de183a8>
>>> C.x.__get__
<method-wrapper '__get__' of member_descriptor object at 0x7f001de183a8>
```
But I was wondering: where are the values actually stored?
Because the common recipe/idiom I've seen so far for descriptors is:
```py
>>> class Descr:
...
... def __init__(self, attrname):
... self.attrname = attrname
...
... def __get__(self, obj, cls):
... return obj.__dict__[self.attrname]
...
... def __set__(self, obj, val):
... obj.__dict__[self.attrname] = val
...
... class C:
...
... def __init__(self, x):
... self.x = x
```
When used in addition with `__slots__`, there are two problems:
1. Clash with names:
```py
>>> class C:
...
... __slots__ = ('x',)
...
... def __init__(self, x):
... self.x = x
...
... x = Descr('x')
...
Traceback (most recent call last)
...
ValueError: 'x' in __slots__ conflicts with class variable
```
So a workaround is to name the actual attribute '\_x'.
2. No `__dict__` (unless you explicitly add it to `__slots__`):
```py
>>> class C:
...
... __slots__ = ('_x',)
...
... def __init__(self, x):
... self._x = x
...
... x = Descr('_x')
...
>>> c = C(0)
>>> c.x
Traceback (most recent call last)
...
AttributeError: 'C' object has no attribute '__dict__'
```
So you have to use `getattr()` and `setattr()` instead.
You can end with a generic descriptor wich can work with `__dict__` and `__slots__`:
```py
class WorksWithDictAndSlotsDescriptor:
def __init__(self, attr_name):
self.attr_name = attr_name
def __get__(self, instance, owner):
try:
return instance.__dict__[self.attr_name]
except AttributeError:
return getattr(instance, self.attr_name)
def __set__(self, instance, value):
try:
instance.__dict__[self.attr_name] = value
except AttributeError:
setattr(instance, self.attr_name, value)
```
(Which won't work as excepted if there is both `__slots__` and `__dict__`.)
But recently I've found a way to hijack the `__get__` and `__set__` method with a wrapper:
```py
def slot_wrapper(cls, slotname, slot, descriptor):
'''Wrapper replacing a slot descriptor with another one'''
class InnerDescr(descriptor):
def __get__(self, obj, cls):
print("Hijacking __get__ method of a member-descriptor")
return slot.__get__(obj, cls)
def __set__(self, obj, val):
print("Hijacking __set__ method of a member-descriptor")
slot.__set__(obj, val)
return InnerDescr(slotname, cls)
```
(The use case is to add type checking and data validation, plus enforcing encapsulation.)
So after the creation of a class (or before using a metaclass) you can keep the same name for the slot and your descriptor.
Works well, but feels a little dirty... I think it may be better to implement my own slots to keep using one name for the descriptor. But I don't know how.
So here are some questions:
1. Where are the values actually stored (since there is no dict)? I was thinking it's something implemented in C and not directly accessible with Python code.
2. How can I implement a pure python equivalent without losing performance optimization?
3. Is it preferable to stick with my wrapper? | 2017/09/04 | [
"https://Stackoverflow.com/questions/46028830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7770274/"
] | >
> Where are actually storerd the values (since there is no dict) ? I was thinking it's something implemented in C and not directly accessible with Python code.
>
>
>
Memory is allocated for the `PyObject *` pointers directly in the object itself. You can see the handling in [`Objects/typeobject.c`](https://github.com/python/cpython/blob/3.6/Objects/typeobject.c#L2621-L2652). The generated descriptors will access the memory reserved for their slot in an object of the appropriate type.
>
> How can I implement a pure python equivalent without losing performance optimization?
>
>
>
You cannot. The closest you can get is something like extending `tuple`.
>
> It is prefarable to stick with my wrapper?
>
>
>
No. Don't name your slots the same thing as an attribute you want to be handled by some other descriptor. Doing so is like naming two non-slot descriptors the same thing; you're expressing two contradictory intentions for how you want to handle the attribute with that name. | looking at your overall outlook, I've been working on performative solutions for custom setters on member descriptors for some time now, and this is the best I've come up with so far:
(tested with Anaconda 2.3.0 (Python 3.4.3) on wine, and Python 3.5.2 on linux)
**Note: This solution does not attempt to be pythonic, nor does it serve as a direct answer to the question, but rather an alternative implementation to the desired result.**
```
class A(object):
__slots__ = ( 'attr', )
attrget = A['attr'].__get__
attrset = A['attr'].__set__
def setter( obj, val ):
if type( val ) is int:
attrset( obj, val )
else:
raise TypeError( 'int type expected, got %s'%type( val ) )
setattr( A, 'attr', property( attrget, setter ) )
# ^ this is safer than A.__dict__['attr'] as a mapping_proxy is read-only
```
**Fun Fact:** For `i = A()`, while `i.attr` is less efficient (more CPU spikes), it's actually about ~20ns faster (relative to my machine) compared to the basic member\_descriptor on average.
The same also applies to `i.attr = 0` without the custom setter.
(feel free to test for yourself, timeit should work similarly (except it includes the time for the for loop). (note that my tests didn't change the value), and make sure to run multiple tests)
here's the test results for Python 3.5.2 on linux:
```
10000 iterations; threshold of min + 250ns:
________code___|_______min______|_______max______|_______avg______|_efficiency
⡇⢠⠀⠀⠀⠀⠀⠀⠀⠀⡄⠀⢰⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⠀⠀⠀⠀⠀
⣿⣾⣴⣄⣤⣄⣄⣰⣦⣤⣧⣰⣼⣤⣤⣆⡀⡀⢀⣄⣠⣀⣴⣶⣦⣤⣤⣦⣶⣄⣄⣠⣄⣴⣤⣶⣸⣦⣤⣤⣴⣴⣴⣷⣶⣴⣦⣤⣶⣆⣤⣤⣦⣶⣤⣴⣠⣷⣤⣶⣾⣷⣤⣆
i.mdsc = 1 | 564.964ns | 17341.983ns | 638.568ns | 88.473%
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⢠⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⠀⠀⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⣷⣶⣶⣴⣤⣤⣦⣶⣶⣦⣧⣼⣼⣴⣄⣦⡄⣄⣀⣄⣴⡄⣼⣾⣶⣦⣴⣧⣶⣄⣄⣴⣦⣾⣴⣴⣤⣦⣆⣶⣴⣤⣴⣷⣿⣼⣾⣦⣷⣦⣧⣾⣦⣿⣤⣴⣤⣿⣤⣧⣾⣷⣶⣧
i.prop = 1 | 538.013ns | 8267.001ns | 624.045ns | 86.214%
10000 iterations; threshold of min + 175ns:
____code___|_______min______|_______max______|_______avg______|_efficiency
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡆
⣇⣴⣠⣤⣠⣄⣤⣄⣀⣀⣀⡀⣀⣀⣀⣄⣠⣠⣄⣦⣤⣤⣄⣤⣤⣠⣤⣧⣤⣤⣠⣤⣤⣤⣤⣤⣤⣼⣤⣤⣤⣶⣤⣶⣦⣤⣀⣄⣤⣤⣤⣤⣤⣤⣤⣤⣤⣶⣦⣷⣤⣶⣄⣧
i.mdsc | 364.962ns | 27579.023ns | 411.621ns | 88.665%
⡇⢠⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⠀⠀⠀⠀⠀⠀
⣷⣾⣦⣦⣴⣠⣿⣦⣠⣠⣄⣀⣄⡄⣠⣴⣠⣤⣴⣴⣦⣼⣤⣦⣤⣤⣤⣧⣴⣶⣦⣶⣶⣶⣶⣶⣦⣶⣶⣶⣷⣿⣷⣿⣷⣾⣶⣶⣶⣾⣾⣾⣶⣶⣴⣶⣴⣾⣷⣿⣿⣷⣶⣶
i.prop | 341.039ns | 2000.015ns | 400.054ns | 85.248%
```
Finally, if you downvote this answer, please explain why.
(please do not downvote if your tests do not compare to mine)
^ my results are just an example to show a small boost in performance, and should not be taken at face value. | 2,948 |
65,767,823 | I am new to using terminal in Mac. When I type any python3 command it only checks the users folder on my PC, HOW can I change the directory to open a folder in the users section and check for the .py file there? | 2021/01/18 | [
"https://Stackoverflow.com/questions/65767823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15026906/"
] | Access the desired path using `cd` command
```
cd path/to/access
```
Then you can run the python command to run the scripts. | If you know the name of the folder in which you want to check, you can change the current python directory using: `os.chdir`
<https://docs.python.org/3/library/os.html#os.chdir>
In that case it doesn't matter from where you're running your python script. | 2,949 |
62,292,262 | I am making a simple program in Python and I want from one file import a class that I made in another class. My code is the following:
```
#file cPoint.py
import math
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def printC(self):
print ("(",self.x,",",self.y,")")
```
and my other file is:
```
#file pointTest
import cPoint
def main():
p=Point(3,4)
p.printC()
if __name__=="__main__":
main()
```
The problem is that when I run my program from the file pointTest, by the way both of them are in the same directory, I got the following error:
```
File "E:\python\pointTest.py", line 15, in <module>
main()
File "E:\python\pointTest.py", line 11, in main
p=Point(3,4)
NameError: name 'Point' is not defined
```
When I test my program all in the same file it works, and also when I call the class from the command prompt by using:
```
import cPoint
p=Point(3,4)
p.printC()
( 3 , 4 )
```
what am I missing? I am using WinPython in Anaconda. | 2020/06/09 | [
"https://Stackoverflow.com/questions/62292262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1960266/"
] | Create another row above your column title with the following formula. This will isolate the number, which can then be sorted according to its numerical value (tested, see screenshot below):
```
=LEFT(RIGHT(A3;LEN(A3)-16);LEN(A3)-21)
```
[](https://i.stack.imgur.com/VQm16.png) | Try putting a zero in front of the single digits. Pad with more zeros if you have higher numbers.
56g\_flux\_data39(01)1992, 56g\_flux\_data39(02)1992, 56g\_flux\_data39(03)1992, all the way to 56g\_flux\_data39(11)1992 | 2,952 |
61,169,193 | I have a python code that prints Arabic text on vscode terminal, the output in the terminal appears in "unreadable" format.
code:
```
print('مرحبا')
```
output:
```
مرحبا
```
How can I solve this issue? | 2020/04/12 | [
"https://Stackoverflow.com/questions/61169193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3261292/"
] | to have a `String` variable formatted as {"Head1","Head2","Head3";1,2,3;4,5,6;7,8,9}, you can do as follows
```
Dim sValue As String, r As Range
For Each r In ThisWorkbook.Names("MyRange").RefersToRange.Rows
sValue = sValue & Join(Application.Transpose(Application.Transpose(r.Value)), ",") & ";"
Next
sValue = "{" & Left(sValue, Len(sValue) - 1) & "}"
```
while to store a named range in an array is much simpler (and I'd say, easy to use):
```
Dim sValue As Variant
sValue = ThisWorkbook.Names("MyRange").RefersToRange.Value
``` | I think you are looking for
```
sValue = ThisWorkbook.Names("MyRange"),name
```
to find all names on Activesheet:
```
Sub test_names()
Dim wsName As String
wsName = ActiveSheet.Name
Dim nameRange As Variant
For Each nameRange In ThisWorkbook.Names
Set rngName = Range(nameRange)
wsParentName = rngName.Parent.CodeName
If (wsParentName = wsName) Then
Debug.Print "Found range " & nameRange.Name
End If
Next nameRange
End Sub
``` | 2,953 |
16,569,784 | I'm using a *private* view in my Django project for an AJAX request.
```python
def HereIsSomeJSON(request, label):
if not request.method == "POST":
raise PermissionDenied
# Here is the job of my AJAX, basically feeding a JSON
json = {...}
return HttpResponse(json, "application/json")
```
Using JavaScript, I request for the AJAX with jQuery as so:
```js
function FeedMeWithJSON() {
// Django needs his Cross-Site Request Forgery token to welome POST datas
oPostDatas = {
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
jQuery.post("/url/to/HereIsSomeJSON", oPostDatas, function(oData, sStatus) {
// Here is the job to be done with the fetched JSON
}, "json");
}
```
Everything works just fine thanks to the `request.method` verification I do in the view. The user isn't able to manually (by entering my AJAX url in his browser) access to my view.
However, as I will need more AJAX views I was wondering if I was doing the right thing. So I thought of creating a custom Django decorator which I could use above every one of my AJAX views.
Is is the good way of protecting my *private* views ? And if so, how do I do it ?
Thanks,
Edit
====
---
Apparently, this was not clear enough. I am using a Django view to do an AJAX request. But I don't want the user to be able to type in the URL to read database contents. I know one could always use `curl` or something similar to send POST datas and thus bypassing my thing, even though he would have to send the right `{% csrf_token %}`.
Plus, in *a near future* the *login* feature will be implemented and I will add the `@login_required` decorator.
Thanks, | 2013/05/15 | [
"https://Stackoverflow.com/questions/16569784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1824222/"
] | Your approach of requiring POST for your ajax views is basically OK, and there is an [existing decorator](https://docs.djangoproject.com/en/dev/topics/http/decorators/) to handle it:
```
from django.views.decorators.http import require_POST
@require_POST
def my_view(request):
# I can assume now that only POST requests make it this far
# ...
pass
```
Also, there is an easier way to handle adding CSRF tokens to your jQuery AJAX calls, documented [here](https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax). The basic idea is that you read the CSRF token from the cookie, and use the `beforeSend` option in `$.ajaxSetup` to add it to your all of your `$.ajax` calls (including shortcut syntax like `$.post`).
Since this code isn't relying on template variables, it doesn't have to be in an inline `<script>` tag.
```
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
``` | As [@armonge](https://stackoverflow.com/users/407762/armonge) said, just checking for POST method doesn't do any protection. Suppose you need some checks, that user is registered and maybe have some permissions or needed properties. For this purpose, such decorator can be used (probably needs to be customized):
```
def apply_permissions(view_func):
def _wrapped_view(request, *args, **kwargs):
# it is possible to add some other checks, that return booleans
# or do it in a separate `if` statement
# for example, check for some user permissions or properties
permissions = [
request.is_ajax(),
request.method == "POST",
request.user.is_authenticated()
]
if not all(permissions):
raise PermissionDenied
return view_func(request, *args, **kwargs)
return _wrapped_view
@apply_permissions
def HereIsSomeJSON(request, label):
# your code here without any permissions checks
# Here is the job of my AJAX, basically feeding a JSON
``` | 2,954 |
5,523,279 | it seems that I have some trouble understanding the semantics of the SUID bit, perhaps someone can help me clarify the situation.
My understanding of the semantic of the SUID bit are as follows:
When I set the SUID bit with a file, then the file will be executed as the owner of the file and not as the caller of the file. So to test this behavior I wrote the following python script:
```
#!/usr/bin/python3 -O
import os
def main():
print('Real UserID: %d' % os.getuid())
print('Effective UserID: %d' % os.geteuid())
if __name__ == '__main__':
main()
```
After that I created a user named "testuser" with the corresponding group "testuser" and adjusted the file permissions (chown testuser file, chgrp testuser file, chmod u+s,g+x file). Next I added my main user to the "testuser" group so that I can execute the file as a member of the group. After all that the file permissions looked like this:
```
-rwsr-xr-- 1 testuser testuser 168 2011-04-02 13:35 procred.py*
```
So when I am login as the testuser the script produces the output:
```
Real UserID: 1001
Effective UserID: 1001
```
...and when I run the script as my main user the script outputs:
```
Real UserID: 1000
Effective UserID: 1000
```
Now as of my understanding the script should have run as the user with the uid 1001 (the owner of the file) in the latter execution. Am I getting the whole concept wrong or where is my mistake? | 2011/04/02 | [
"https://Stackoverflow.com/questions/5523279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350403/"
] | Setting the SUID bit on a \*.py file does not help in any way here since the script is executed by the Python interpreter which must be set SUID in this case. Using 'sudo' is your better friend here. | Setting SUID does not work for scripts, because the kernel sees the #! (shebang - magic number 0x23 0x21 - man magic) and drops the privileges before calling the interpreter /usr/bin/python with the script as input. A way around is setting the python interpreter SUID root and add functionality to change privileges to the user owning the script before executing the script, in case SUID bit is set. Doing this in a naive way will impose security problems. How to do it in a smart way can be found here: <http://perldoc.perl.org/perlsec.html>
Additional Links:
* <http://www.in-ulm.de/~mascheck/various/shebang/>
* <https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts> | 2,956 |
55,683,072 | Actually, i'm very new to python and working on some image problem statement. Stuck in a problem and not able to get out of this.
I have data frame like:
```
Image RGB max_1 max_2 max_3
file1 [[224,43,234][22,5,224][234,254,220]] 234 224 254
file2 [[22,143,113][221,124,224][234,254,123]] 143 224 254
file3 [[44,45,2][2,5,4][34,254,220]] 45 5 254
file4 [[224,243,34][22,5,24][24,25,20]] 243 24 25
file5 [[210,13,34][22,5,224][234,254,220]] 210 224 254
```
I tried `np.max()` but it gave me unexpected results that means for the first row this gave me output `254`, and so on.
I'm expecting the output as column max\_1, max\_2, and max\_3. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55683072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7721819/"
] | You can do something like this perhaps:
```
file1 = [[224,43,234],[22,5,224],[234,254,220]]
for idx, inner_list in enumerate(file1):
print('max_'+str(idx+1)+' : '+str(max(inner_list)))
``` | You said you have a data frame, so I assume it's a `pandas` `DataFrame` object.
In which case, you can use list comprehension to take the max from each sub-list in the list, and assign each element to a new column (this loop isn't elegant but will work):
```
df['max_colors'] = df['RGB'].apply(lambda x: [np.max(color) for color in x])
for i in range(3):
df['max_'+str(i)] = df['max_colors'].apply(lambda x: x[i])
``` | 2,959 |
59,333,904 | (I'm very new to both python and stackoverflow.)
```
def A():
def B():
print("I'm B")
A.B = B
A()
A.B()
```
output:
```
"I'm B"
```
This works well. What I want is to put that in a class like this(doesn't work. I just tried..)
```
class Student:
def A(self):
def B():
print("I'm B")
self.A.B = B
```
I have no Idea how to make the class and how to call the sub function in the class. | 2019/12/14 | [
"https://Stackoverflow.com/questions/59333904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386013/"
] | You don't need to reference *self* because the inner function *B* is defined there. It should be like this:
```
class Student:
def A(self):
def B():
print("I'm B")
B()
``` | I never use classes, but could you do it this way?
```
class A:
def __call__(self): // so you can call it like a function
def B():
print("i am B")
B()
call_A = A() // make the class callable
call_A() // call it
``` | 2,969 |
21,175,923 | The problem I am tackle with is to find the first occurrence node in its inorder traversal in a BST.
The code I have is given below
```
def Inorder_search_recursive(node,key):
if not node:
return None
InOrder_search_recursive(node.lChild)
if node.value==key:
return node
InOrder_search_recursive(node.rChild)
```
This code always return None, what's wrong with it. I think I've return node when I find a node with value k. Why cannot python pass this node???Thanks in advance | 2014/01/17 | [
"https://Stackoverflow.com/questions/21175923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1824922/"
] | When you call yourself recursively, like this:
```
InOrder_search_recursive(node.lChild)
```
That's just a normal function call, like any other. It just calls the function and gets back a result. It doesn't automatically `return` the value from that function, or do anything else.
So, you do the left-subtree search, ignore the results, then go on to check `node.value == key`, and, if that fails, you do the right-subtree search, again ignore the results, and fall off the end of the function, meaning you return `None`.
To make this work, you need to `return` the value you got back. But, of course, only if it's `not None`.
Also, you forgot to pass the `key` argument down to the recursive call, so you're just going to get a `TypeError`. (I'm guessing your real code doesn't have this problem, but since you didn't show us your real code, or a working example, I can't be sure…)
So:
```
def Inorder_search_recursive(node, key):
if not node:
return None
result = InOrder_search_recursive(node.lChild, key)
if result is not None:
return result
if node.value==key:
return node
return InOrder_search_recursive(node.rChild, key)
```
(You don't need the `not None` check for the right-side search, because if it returns `None`, we have nothing else to try and are just going to return `None` anyway.) | Since your problem is `to find the first occurrence node in its inorder traversal`, you should 1) traverse the tree in-order and 2) stop when you find the first occurrence.
```
def search(node, key):
if node is None:
return None
# Search the left subtree and return early if key is found
n = search(node.lChild, key)
if n is not None:
return n
# Check middle and return early if key is found
if node.value == key:
return node
# Search right subtree
return search(node.rChild, key)
``` | 2,972 |
24,488,891 | I have a django app and trying to set it up with gunicorn first and later with supervisor and nginx.
The app is running with the normal django command perfectly like `python manage.py runserver`
I installed the gunicorn using pip like `pip install gunicorn` and django version is `1.5.3`
when i run the below command inside the virtual env like below
`gunicorn hello.wsgi:application -b xx.xxx.xxx.xx:8000` and faced the error
```
Traceback (most recent call last):
File "/root/Envs/proj/bin/gunicorn", line 9, in <module>
load_entry_point('gunicorn==19.0.0', 'console_scripts', 'gunicorn')()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 166, in run
super(Application, self).run()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 71, in run
Arbiter(self).run()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 169, in run
self.manage_workers()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 477, in manage_workers
self.spawn_workers()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 537, in spawn_workers
time.sleep(0.1 * random.random())
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 209, in handle_chld
self.reap_workers()
File "/root/Envs/proj/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 459, in reap_workers
raise HaltServer(reason, self.WORKER_BOOT_ERROR)
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
```
So why actually the above error is encountered and whats the fix ? | 2014/06/30 | [
"https://Stackoverflow.com/questions/24488891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342109/"
] | You didn't show a full output. It probably looks like
```
$ gunicorn elcarweb.wsgi
[2015-10-27 21:01:47 +0000] [5429] [INFO] Starting gunicorn 19.2.1
[2015-10-27 21:01:47 +0000] [5429] [INFO] Listening at: http://127.0.0.1:8000 (5429)
[2015-10-27 21:01:47 +0000] [5429] [INFO] Using worker: sync
[2015-10-27 21:01:47 +0000] [5434] [INFO] Booting worker with pid: 5434
[2015-10-27 21:01:47 +0000] [5434] [ERROR] Exception in worker process:
Traceback (most recent call last):
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 503, in spawn_worker
worker.init_process()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/workers/base.py", line 116, in init_process
self.wsgi = self.app.wsgi()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/util.py", line 355, in import_app
__import__(module)
ImportError: No module named elcarweb.wsgi
Traceback (most recent call last):
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 503, in spawn_worker
worker.init_process()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/workers/base.py", line 116, in init_process
self.wsgi = self.app.wsgi()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/util.py", line 355, in import_app
__import__(module)
ImportError: No module named elcarweb.wsgi
[2015-10-27 21:01:47 +0000] [5434] [INFO] Worker exiting (pid: 5434)
Traceback (most recent call last):
File "/home/tomek/Elcar/elcarweb/env/bin/gunicorn", line 11, in <module>
sys.exit(run())
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/base.py", line 189, in run
super(Application, self).run()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run
Arbiter(self).run()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 170, in run
self.manage_workers()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 473, in manage_workers
self.spawn_workers()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 537, in spawn_workers
time.sleep(0.1 * random.random())
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 210, in handle_chld
self.reap_workers()
File "/home/tomek/Elcar/elcarweb/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 455, in reap_workers
raise HaltServer(reason, self.WORKER_BOOT_ERROR)
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
```
Last trackback is almost the same, but before You see required informations:
```
ImportError: No module named elcarweb.wsgi
```
If You see this error, then solution is run gunicorn with `--chdir=/your/app/dir` parameter. | For anyone facing the same issue, the problem is usually something in django itself.
Activate your venv and run ./manage.py runserver
This will usually give you a more detailed error message. | 2,974 |
2,337,216 | Besides wrapping all your code in `try` `except`, is there any way of achieving the same thing as running your script like `python -mpdb script`? I'd like to be able to see what went wrong when an exception gets raised. | 2010/02/25 | [
"https://Stackoverflow.com/questions/2337216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] | If you do not want to modify the source then yOu could run it from [ipython](http://ipython.scipy.org/moin/) - an enhanced interactive python shell.
e.g. run ipython then execute `%pdb on` to enable post-mortem debugging. `%run scriptname` will then run the script and automatically enter the debugger on any uncaught exceptions.
Alternatively `%run -d scriptname` will start the script in the debugger. | `import pdb; pdb.set_trace()`
Source: <http://docs.python.org/library/pdb.html> | 2,984 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.