qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
listlengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
|---|---|---|---|---|---|
39,961,414
|
I am new to learning regex in python and I'm wondering how do I use regex in python to store the integers(positive and negative) i want into a list!
For example
This is the data in a list.
```
data =
[u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=-5,B=5)',
u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=5,Y=5)',
u'\x1b[0m[\x1b[1m\x1b[10m\xbb\x1b[0m\x1b[36m]\x1b[0m : ']
```
How do I extract the integer values of A and B (negative and positive) and store them in a variable so that I can work with the numbers?
I tried smth like this but the list is empty ..
```
for line in data[0]:
pattern = re.compile("([A-Z]=(-?\d+?),[A-Z]=(-?\d+?))")
store = pattern.findall(line)
print store
```
Thank you and appreciate it
|
2016/10/10
|
[
"https://Stackoverflow.com/questions/39961414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6949864/"
] |
When you use `$(".form-control")`, jquery select all `.form-control` element. But you need to select target element using `this` variable in event function and use [`.prev()`](https://api.jquery.com/prev/) to select previous element.
```js
$(".show").mousedown(function(){
$(this).prev().attr('type','text');
}).mouseup(function(){
$(this).prev().attr('type','password');
}).mouseout(function(){
$(this).prev().attr('type','password');
});
```
|
**In react We simply do with**
---
We probably need to use the onMouseDown and onMouseUp, onMouseOut events
```
onMouseDown={handleShowPassword}
onMouseUp={handleShowPassword}
onMouseOut={handleShowPasswordHideOnMouseOut}
```
|
39,961,414
|
I am new to learning regex in python and I'm wondering how do I use regex in python to store the integers(positive and negative) i want into a list!
For example
This is the data in a list.
```
data =
[u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=-5,B=5)',
u'\x1b[0m[\x1b[1m\x1b[0m\xbb\x1b[0m\x1b[36m]\x1b[0m (A=5,Y=5)',
u'\x1b[0m[\x1b[1m\x1b[10m\xbb\x1b[0m\x1b[36m]\x1b[0m : ']
```
How do I extract the integer values of A and B (negative and positive) and store them in a variable so that I can work with the numbers?
I tried smth like this but the list is empty ..
```
for line in data[0]:
pattern = re.compile("([A-Z]=(-?\d+?),[A-Z]=(-?\d+?))")
store = pattern.findall(line)
print store
```
Thank you and appreciate it
|
2016/10/10
|
[
"https://Stackoverflow.com/questions/39961414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6949864/"
] |
Just target the previous input instead of all inputs with the given class
```js
$(".form-control").on("keyup", function() {
if ($(this).val())
$(this).next(".show").show();
else
$(this).next(".show").hide();
}).trigger('keyup');
$(".show").mousedown(function() {
$(this).prev(".form-control").prop('type', 'text');
}).mouseup(function() {
$(this).prev(".form-control").prop('type', 'password');
}).mouseout(function() {
$(this).prev(".form-control").prop('type', 'password');
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="resetting_form" method="post" action="">
<div class="form-group has-feedback">
<input type="password" id="password_first" required="required" placeholder="New Password" class="form-control">
<span class="show">show</span>
</div>
<div class="form-group has-feedback">
<input type="password" id="password_second" required="required" placeholder="Repeat Password" class="form-control">
<span class="show">show</span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
```
|
**In react We simply do with**
---
We probably need to use the onMouseDown and onMouseUp, onMouseOut events
```
onMouseDown={handleShowPassword}
onMouseUp={handleShowPassword}
onMouseOut={handleShowPasswordHideOnMouseOut}
```
|
69,516,584
|
i am running npm install command on my project but getting error
>
> Build failed with error code: 1
>
>
>
Part of the log posted below.
```
0 verbose cli [
0 verbose cli 'C:\\Program Files\\nodejs\\node.exe',
0 verbose cli 'C:\\Users\\vined\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
0 verbose cli 'install'
0 verbose cli ]
1 info using npm@8.0.0
2 info using node@v16.9.1
3 timing npm:load:whichnode Completed in 1ms
4 timing config:load:defaults Completed in 5ms
5 timing config:load:file:C:\Users\vined\AppData\Roaming\npm\node_modules\npm\npmrc Completed in 7ms
6 timing config:load:builtin Completed in 7ms
7 timing config:load:cli Completed in 6ms
8 timing config:load:env Completed in 1ms
9 timing config:load:file:E:\plugin-applepay-master\.npmrc Completed in 1ms
10 timing config:load:project Completed in 9ms
11 timing config:load:file:C:\Users\vined\.npmrc Completed in 2ms
12 timing config:load:user Completed in 3ms
13 timing config:load:file:C:\Users\vined\AppData\Roaming\npm\etc\npmrc Completed in 0ms
14 timing config:load:global Completed in 1ms
15 timing config:load:validate Completed in 5ms
16 timing config:load:credentials Completed in 3ms
17 timing config:load:setEnvs Completed in 3ms
18 timing config:load Completed in 43ms
19 timing npm:load:configload Completed in 43ms
20 timing npm:load:setTitle Completed in 6ms
21 timing npm:load:setupLog Completed in 1ms
22 timing config:load:flatten Completed in 11ms
23 timing npm:load:cleanupLog Completed in 8ms
24 timing npm:load:configScope Completed in 0ms
25 timing npm:load:projectScope Completed in 2ms
26 timing npm:load Completed in 76ms
27 timing arborist:ctor Completed in 3ms
28 timing idealTree:init Completed in 3609ms
29 warn old lockfile The package-lock.json file was created with an old version of npm,
29 warn old lockfile so supplemental metadata must be fetched from the registry.
29 warn old lockfile
29 warn old lockfile This is a one-time fix-up, please be patient...
30 silly inflate node_modules/@tridnguyen/config
31 silly inflate node_modules/@webassemblyjs/ast
32 http fetch GET 200 https://registry.npmjs.org/@webassemblyjs%2Fast 891ms (cache revalidated)
33 silly inflate node_modules/@webassemblyjs/floating-point-hex-parser
34 http fetch GET 200 https://registry.npmjs.org/@webassemblyjs%2Ffloating-point-hex-parser 153ms (cache revalidated)
35 silly inflate node_modules/@webassemblyjs/helper-api-error
36 http fetch GET 200 https://registry.npmjs.org/@webassemblyjs%2Fhelper-api-error 155ms (cache revalidated)
37 silly inflate node_modules/@webassemblyjs/helper-buffer
38 http fetch GET 200 https://registry.npmjs.org/@webassemblyjs%2Fhelper-buffer 184ms (cache revalidated)
39 silly inflate node_modules/@webassemblyjs/helper-code-frame
40 http fetch GET 200 https://registry.npmjs.org/@webassemblyjs%2Fhelper-code-frame 115ms (cache revalidated)
3313 timing reifyNode:node_modules/events Completed in 56407ms
3314 timing reifyNode:node_modules/optimist Completed in 56748ms
3315 timing reifyNode:node_modules/es6-map Completed in 56420ms
3316 timing reifyNode:node_modules/argparse Completed in 56262ms
3317 timing reifyNode:node_modules/dwupload/node_modules/yargs Completed in 56467ms
3318 timing reifyNode:node_modules/iconv-lite Completed in 56651ms
3319 timing reifyNode:node_modules/stylelint/node_modules/table Completed in 57303ms
3320 timing reifyNode:node_modules/public-encrypt Completed in 57110ms
3321 timing reifyNode:node_modules/source-map Completed in 57327ms
3322 timing reifyNode:node_modules/cacache Completed in 56598ms
3323 timing reifyNode:node_modules/uglify-js Completed in 57809ms
3324 timing reifyNode:node_modules/terser/node_modules/source-map Completed in 57789ms
3325 timing reifyNode:node_modules/stylelint/node_modules/source-map Completed in 57764ms
3326 timing reifyNode:node_modules/terser-webpack-plugin/node_modules/source-map Completed in 57799ms
3327 timing reifyNode:node_modules/uglify-js/node_modules/source-map Completed in 57833ms
3328 timing reifyNode:node_modules/postcss-reporter/node_modules/source-map Completed in 57525ms
3329 timing reifyNode:node_modules/postcss-sass/node_modules/source-map Completed in 57540ms
3330 timing reifyNode:node_modules/webpack-sources/node_modules/source-map Completed in 58016ms
3331 timing reifyNode:node_modules/postcss-loader/node_modules/source-map Completed in 57507ms
3332 timing reifyNode:node_modules/dom-serializer/node_modules/entities Completed in 57096ms
3333 timing reifyNode:node_modules/postcss-modules-values/node_modules/source-map Completed in 57555ms
3334 timing reifyNode:node_modules/sugarss/node_modules/source-map Completed in 57841ms
3335 timing reifyNode:node_modules/postcss-modules-scope/node_modules/source-map Completed in 57565ms
3336 timing reifyNode:node_modules/postcss-modules-extract-imports/node_modules/source-map Completed in 57556ms
3337 timing reifyNode:node_modules/postcss-safe-parser/node_modules/source-map Completed in 57598ms
3338 timing reifyNode:node_modules/postcss-scss/node_modules/source-map Completed in 57615ms
3339 timing reifyNode:node_modules/postcss-modules-local-by-default/node_modules/source-map Completed in 57573ms
3340 timing reifyNode:node_modules/css/node_modules/source-map Completed in 57087ms
3341 timing reifyNode:node_modules/handlebars/node_modules/source-map Completed in 57240ms
3342 timing reifyNode:node_modules/icss-utils/node_modules/source-map Completed in 57289ms
3343 timing reifyNode:node_modules/source-map-support/node_modules/source-map Completed in 57832ms
3344 timing reifyNode:node_modules/stylelint-scss/node_modules/postcss-selector-parser Completed in 58076ms
3345 timing reifyNode:node_modules/stylelint/node_modules/postcss-selector-parser Completed in 58064ms
3346 timing reifyNode:node_modules/schema-utils/node_modules/ajv-keywords Completed in 58034ms
3347 timing reifyNode:node_modules/stylelint/node_modules/ajv-keywords Completed in 58129ms
3348 timing reifyNode:node_modules/webpack/node_modules/ajv-keywords Completed in 58363ms
3349 timing reifyNode:node_modules/terser-webpack-plugin/node_modules/ajv-keywords Completed in 58232ms
3350 timing reifyNode:node_modules/domhandler Completed in 57567ms
3351 timing reifyNode:node_modules/json-schema Completed in 58264ms
3352 timing reifyNode:node_modules/stream-http Completed in 59326ms
3353 timing reifyNode:node_modules/diff Completed in 59764ms
3354 timing reifyNode:node_modules/pako Completed in 60450ms
3355 timing reifyNode:node_modules/es6-set Completed in 60124ms
3356 timing reifyNode:node_modules/@webassemblyjs/ast Completed in 59888ms
3357 timing reifyNode:node_modules/sshpk Completed in 60786ms
3358 timing reifyNode:node_modules/js-yaml Completed in 60636ms
3359 timing reifyNode:node_modules/terser Completed in 61207ms
3360 timing reifyNode:node_modules/cosmiconfig/node_modules/js-yaml Completed in 60646ms
3361 timing reifyNode:node_modules/stylelint/node_modules/js-yaml Completed in 61401ms
3362 timing reifyNode:node_modules/enhanced-resolve Completed in 60729ms
3363 timing reifyNode:node_modules/yargs Completed in 61701ms
3364 timing reifyNode:node_modules/shelljs Completed in 61498ms
3365 timing reifyNode:node_modules/escodegen/node_modules/source-map Completed in 61116ms
3366 timing reifyNode:node_modules/jszip Completed in 61402ms
3367 timing reifyNode:node_modules/postcss Completed in 61593ms
3368 timing reifyNode:node_modules/sgmf-scripts/node_modules/shelljs Completed in 61827ms
3369 timing reifyNode:node_modules/remark-stringify Completed in 61911ms
3370 timing reifyNode:node_modules/chai Completed in 61596ms
3371 timing reifyNode:node_modules/postcss-modules-values/node_modules/postcss Completed in 62197ms
3372 timing reifyNode:node_modules/postcss-scss/node_modules/postcss Completed in 62232ms
3373 timing reifyNode:node_modules/postcss-safe-parser/node_modules/postcss Completed in 62227ms
3374 timing reifyNode:node_modules/postcss-modules-scope/node_modules/postcss Completed in 62210ms
3375 timing reifyNode:node_modules/stylelint/node_modules/postcss Completed in 62474ms
3376 timing reifyNode:node_modules/postcss-modules-local-by-default/node_modules/postcss Completed in 62218ms
3377 timing reifyNode:node_modules/icss-utils/node_modules/postcss Completed in 61909ms
3378 timing reifyNode:node_modules/sugarss/node_modules/postcss Completed in 62507ms
3379 timing reifyNode:node_modules/postcss-modules-extract-imports/node_modules/postcss Completed in 62221ms
3380 timing reifyNode:node_modules/postcss-loader/node_modules/postcss Completed in 62209ms
3381 timing reifyNode:node_modules/postcss-sass/node_modules/postcss Completed in 62271ms
3382 timing reifyNode:node_modules/postcss-reporter/node_modules/postcss Completed in 62264ms
3383 warn deprecated buffer@4.9.1: This version of 'buffer' is out-of-date. You must update to v4.9.2 or newer
3384 timing reifyNode:node_modules/node-libs-browser/node_modules/buffer Completed in 62235ms
3385 timing reifyNode:node_modules/remark-parse Completed in 64660ms
3386 timing reifyNode:node_modules/nan Completed in 64578ms
3387 timing reifyNode:node_modules/bluebird Completed in 64116ms
3388 timing reifyNode:node_modules/sinon Completed in 64900ms
3389 timing reifyNode:node_modules/node-notifier Completed in 64751ms
3390 timing reifyNode:node_modules/proxyquire Completed in 64949ms
3391 timing reifyNode:node_modules/coa Completed in 64496ms
3392 timing reifyNode:node_modules/eslint-plugin-import Completed in 64649ms
3393 timing reifyNode:node_modules/cacache/node_modules/bluebird Completed in 64551ms
3394 timing reifyNode:node_modules/acorn-jsx/node_modules/acorn Completed in 64749ms
3395 timing reifyNode:node_modules/postcss-less Completed in 65491ms
3396 timing reifyNode:node_modules/csso Completed in 65141ms
3397 timing reifyNode:node_modules/table Completed in 66025ms
3398 timing reifyNode:node_modules/crc Completed in 65252ms
3399 timing reifyNode:node_modules/escope Completed in 65347ms
3400 timing reifyNode:node_modules/mocha Completed in 65706ms
3401 warn deprecated istanbul@0.4.5: This module is no longer maintained, try this instead:
3401 warn deprecated npm i nyc
3401 warn deprecated Visit https://istanbul.js.org/integrations for other alternatives.
3402 timing reifyNode:node_modules/istanbul Completed in 65794ms
3403 timing reifyNode:node_modules/autoprefixer Completed in 65865ms
3404 warn deprecated svgo@0.7.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
3405 timing reifyNode:node_modules/svgo Completed in 66839ms
3406 timing reifyNode:node_modules/uri-js Completed in 66975ms
3407 timing reifyNode:node_modules/sgmf-scripts Completed in 67253ms
3408 timing reifyNode:node_modules/stylelint/node_modules/autoprefixer Completed in 67610ms
3409 timing reifyNode:node_modules/istanbul/node_modules/resolve Completed in 68223ms
3410 timing reifyNode:node_modules/schema-utils/node_modules/ajv Completed in 70277ms
3411 timing reifyNode:node_modules/webpack/node_modules/ajv Completed in 70600ms
3412 timing reifyNode:node_modules/terser-webpack-plugin/node_modules/ajv Completed in 70472ms
3413 timing reifyNode:node_modules/har-validator/node_modules/ajv Completed in 69904ms
3414 timing reifyNode:node_modules/stylelint/node_modules/ajv Completed in 70477ms
3415 timing reifyNode:node_modules/resolve Completed in 70397ms
3416 warn deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.
3417 timing reifyNode:node_modules/tar Completed in 70821ms
3418 timing reifyNode:node_modules/ajv Completed in 70421ms
3419 timing reifyNode:node_modules/neo-async Completed in 70973ms
3420 timing reifyNode:node_modules/type Completed in 71535ms
3421 timing reifyNode:node_modules/node-gyp Completed in 71977ms
3422 timing reifyNode:node_modules/extract-text-webpack-plugin/node_modules/async Completed in 71756ms
3423 timing reifyNode:node_modules/archiver/node_modules/async Completed in 71520ms
3424 timing reifyNode:node_modules/handlebars Completed in 72430ms
3425 timing reifyNode:node_modules/stylelint-scss Completed in 74065ms
3426 timing reifyNode:node_modules/babel-runtime Completed in 75225ms
3427 timing reifyNode:node_modules/eslint Completed in 78354ms
3428 timing reifyNode:node_modules/webpack Completed in 79374ms
3429 timing reifyNode:node_modules/node-sass Completed in 79028ms
3430 warn deprecated webdriverio@4.14.4: outdated version, please use @next
3431 timing reifyNode:node_modules/webdriverio Completed in 86402ms
3432 timing reifyNode:node_modules/stylelint Completed in 86352ms
3433 timing reifyNode:node_modules/cleave.js Completed in 88431ms
3434 timing reifyNode:node_modules/caniuse-lite Completed in 89944ms
3435 timing reifyNode:node_modules/es5-ext Completed in 90823ms
3436 timing reifyNode:node_modules/caniuse-db Completed in 91715ms
3437 timing reifyNode:node_modules/lodash Completed in 92690ms
3438 warn deprecated core-js@2.6.10: core-js@<3.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.
3439 timing reifyNode:node_modules/core-js Completed in 94192ms
3440 timing reify:unpack Completed in 95219ms
3441 timing reify:unretire Completed in 4ms
3442 timing build:queue Completed in 240ms
3443 timing build:link:node_modules/atob Completed in 596ms
3444 timing build:link:node_modules/acorn-jsx/node_modules/acorn Completed in 559ms
3445 timing build:link:node_modules/node-gyp/node_modules/semver Completed in 557ms
3446 timing build:link:node_modules/sass-loader/node_modules/semver Completed in 556ms
3447 timing build:link:node_modules/sgmf-scripts/node_modules/shelljs Completed in 555ms
3448 timing build:link:node_modules/stylelint/node_modules/autoprefixer Completed in 554ms
3449 timing build:link:node_modules/webpack/node_modules/acorn Completed in 552ms
3450 timing build:link:node_modules/acorn Completed in 607ms
3451 timing build:link:node_modules/browserslist Completed in 603ms
3452 timing build:link:node_modules/cssesc Completed in 602ms
3453 timing build:link:node_modules/csso Completed in 634ms
3454 timing build:link:node_modules/errno Completed in 634ms
3455 timing build:link:node_modules/escodegen Completed in 633ms
3456 timing build:link:node_modules/eslint Completed in 631ms
3457 timing build:link:node_modules/esprima Completed in 630ms
3458 timing build:link:node_modules/gonzales-pe Completed in 628ms
3459 timing build:link:node_modules/he Completed in 626ms
3460 timing build:link:node_modules/handlebars Completed in 627ms
3461 timing build:link:node_modules/in-publish Completed in 626ms
3462 timing build:link:node_modules/istanbul Completed in 624ms
3463 timing build:link:node_modules/js-yaml Completed in 623ms
3464 timing build:link:node_modules/jsesc Completed in 622ms
3465 timing build:link:node_modules/json5 Completed in 622ms
3466 timing build:link:node_modules/mkdirp Completed in 620ms
3467 timing build:link:node_modules/mocha Completed in 619ms
3468 timing build:link:node_modules/node-gyp Completed in 618ms
3469 timing build:link:node_modules/miller-rabin Completed in 620ms
3470 timing build:link:node_modules/node-sass Completed in 617ms
3471 timing build:link:node_modules/nopt Completed in 614ms
3472 timing build:link:node_modules/onchange Completed in 613ms
3473 timing build:link:node_modules/regjsparser Completed in 612ms
3474 timing build:link:node_modules/rimraf Completed in 611ms
3475 timing build:link:node_modules/sass-graph Completed in 611ms
3476 timing build:link:node_modules/semver Completed in 610ms
3477 timing build:link:node_modules/sgmf-scripts Completed in 609ms
3478 timing build:link:node_modules/sha.js Completed in 609ms
3479 timing build:link:node_modules/shelljs Completed in 608ms
3480 timing build:link:node_modules/specificity Completed in 607ms
3481 timing build:link:node_modules/sshpk Completed in 607ms
3482 timing build:link:node_modules/strip-indent Completed in 606ms
3483 timing build:link:node_modules/stylelint Completed in 605ms
3484 timing build:link:node_modules/svgo Completed in 604ms
3485 timing build:link:node_modules/terser Completed in 603ms
3486 timing build:link:node_modules/tree-kill Completed in 602ms
3487 timing build:link:node_modules/uglify-js Completed in 602ms
3488 timing build:link:node_modules/uuid Completed in 601ms
3489 timing build:link:node_modules/webdriverio Completed in 599ms
3490 timing build:link:node_modules/watch Completed in 600ms
3491 timing build:link:node_modules/webpack Completed in 598ms
3492 timing build:link:node_modules/which Completed in 597ms
3493 timing build:link:node_modules/window-size Completed in 597ms
3494 timing build:link:node_modules/cosmiconfig/node_modules/esprima Completed in 596ms
3495 timing build:link:node_modules/cosmiconfig/node_modules/js-yaml Completed in 594ms
3496 timing build:link:node_modules/stylelint/node_modules/browserslist Completed in 590ms
3497 timing build:link:node_modules/stylelint/node_modules/esprima Completed in 590ms
3498 timing build:link:node_modules/stylelint/node_modules/js-yaml Completed in 588ms
3499 timing build:link:node_modules/dwupload Completed in 885ms
3500 timing build:link Completed in 891ms
3501 info run node-sass@4.12.0 install node_modules/node-sass node scripts/install.js
3502 info run node-sass@4.12.0 install { code: 0, signal: null }
3503 timing build:run:install:node_modules/node-sass Completed in 2303ms
3504 timing build:run:install Completed in 2304ms
3505 info run core-js@2.6.10 postinstall node_modules/core-js node postinstall || echo "ignore"
3506 info run node-sass@4.12.0 postinstall node_modules/node-sass node scripts/build.js
3507 info run core-js@2.6.10 postinstall { code: 0, signal: null }
3508 timing build:run:postinstall:node_modules/core-js Completed in 822ms
3509 info run node-sass@4.12.0 postinstall { code: 1, signal: null }
3510 timing reify:rollback:createSparse Completed in 23958ms
3511 timing reify:rollback:retireShallow Completed in 0ms
3512 timing command:install Completed in 265527ms
3513 verbose stack Error: command failed
3513 verbose stack at ChildProcess.<anonymous> (C:\Users\vined\AppData\Roaming\npm\node_modules\npm\node_modules\@npmcli\promise-spawn\index.js:64:27)
3513 verbose stack at ChildProcess.emit (node:events:394:28)
3513 verbose stack at maybeClose (node:internal/child_process:1064:16)
3513 verbose stack at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
3514 verbose pkgid node-sass@4.12.0
3515 verbose cwd E:\plugin-applepay-master
3516 verbose Windows_NT 10.0.19043
3517 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\vined\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install"
3518 verbose node v16.9.1
3519 verbose npm v8.0.0
3520 error code 1
3521 error path E:\plugin-applepay-master\node_modules\node-sass
3522 error command failed
3523 error command C:\WINDOWS\system32\cmd.exe /d /s /c node scripts/build.js
3524 error Building: C:\Program Files\nodejs\node.exe E:\plugin-applepay-master\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
3525 error gyp info it worked if it ends with ok
3525 error gyp verb cli [
3525 error gyp verb cli 'C:\\Program Files\\nodejs\\node.exe',
3525 error gyp verb cli 'E:\\plugin-applepay-master\\node_modules\\node-gyp\\bin\\node-gyp.js',
3525 error gyp verb cli 'rebuild',
3525 error gyp verb cli '--verbose',
3525 error gyp verb cli '--libsass_ext=',
3525 error gyp verb cli '--libsass_cflags=',
3525 error gyp verb cli '--libsass_ldflags=',
3525 error gyp verb cli '--libsass_library='
3525 error gyp verb cli ]
3525 error gyp info using node-gyp@3.8.0
3525 error gyp info using node@16.9.1 | win32 | x64
3525 error gyp verb command rebuild []
3525 error gyp verb command clean []
3525 error gyp verb clean removing "build" directory
3525 error gyp verb command configure []
3525 error gyp verb check python checking for Python executable "python2" in the PATH
3525 error gyp verb `which` failed Error: not found: python2
3525 error gyp verb `which` failed at getNotFoundError (E:\plugin-applepay-master\node_modules\which\which.js:13:12)
3525 error gyp verb `which` failed at F (E:\plugin-applepay-master\node_modules\which\which.js:68:19)
3525 error gyp verb `which` failed at E (E:\plugin-applepay-master\node_modules\which\which.js:80:29)
3525 error gyp verb `which` failed at E:\plugin-applepay-master\node_modules\which\which.js:89:16
3525 error gyp verb `which` failed at E:\plugin-applepay-master\node_modules\isexe\index.js:42:5
3525 error gyp verb `which` failed at E:\plugin-applepay-master\node_modules\isexe\windows.js:36:5
3525 error gyp verb `which` failed at FSReqCallback.oncomplete (node:fs:198:21)
3525 error gyp verb `which` failed python2 Error: not found: python2
3525 error gyp verb `which` failed at getNotFoundError (E:\plugin-applepay-master\node_modules\which\which.js:13:12)
3525 error gyp verb `which` failed at F (E:\plugin-applepay-master\node_modules\which\which.js:68:19)
3525 error gyp verb `which` failed at E (E:\plugin-applepay-master\node_modules\which\which.js:80:29)
3525 error gyp verb `which` failed at E:\plugin-applepay-master\node_modules\which\which.js:89:16
3525 error gyp verb `which` failed at E:\plugin-applepay-master\node_modules\isexe\index.js:42:5
3525 error gyp verb `which` failed at E:\plugin-applepay-master\node_modules\isexe\windows.js:36:5
3525 error gyp verb `which` failed at FSReqCallback.oncomplete (node:fs:198:21) {
3525 error gyp verb `which` failed code: 'ENOENT'
3525 error gyp verb `which` failed }
3525 error gyp verb check python checking for Python executable "python" in the PATH
3525 error gyp verb `which` succeeded python C:\Python310\python.EXE
3525 error gyp ERR! configure error
3525 error gyp ERR! stack Error: Command failed: C:\Python310\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
3525 error gyp ERR! stack File "<string>", line 1
3525 error gyp ERR! stack import sys; print "%s.%s.%s" % sys.version_info[:3];
3525 error gyp ERR! stack ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3525 error gyp ERR! stack SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
3525 error gyp ERR! stack
3525 error gyp ERR! stack at ChildProcess.exithandler (node:child_process:397:12)
3525 error gyp ERR! stack at ChildProcess.emit (node:events:394:28)
3525 error gyp ERR! stack at maybeClose (node:internal/child_process:1064:16)
3525 error gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5)
3525 error gyp ERR! System Windows_NT 10.0.19043
3525 error gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "E:\\plugin-applepay-master\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
3525 error gyp ERR! cwd E:\plugin-applepay-master\node_modules\node-sass
3525 error gyp ERR! node -v v16.9.1
3525 error gyp ERR! node-gyp -v v3.8.0
3525 error gyp ERR! not ok
3525 error Build failed with error code: 1
3526 verbose exit 1
```
******Below is my package.Json******
```
{
"name": "plugin_applepay",
"version": "6.0.0",
"description": "ApplePay plugin for Storefront Reference Architecture",
"main": "index.js",
"scripts": {
"test": "sgmf-scripts --test",
"compile:scss": "sgmf-scripts --compile css",
"compile:js": "sgmf-scripts --compile js",
"build": "npm run compile:js && npm run compile:scss",
"upload": "sgmf-scripts --upload",
"uploadCartridge": "sgmf-scripts --uploadCartridge plugin_applepay",
"lint": "sgmf-scripts --lint js && sgmf-scripts --lint css"
},
"repository": {
"type": "git",
"url": "git+https://github.com/SalesforceCommerceCloud/plugin-applepay.git"
},
"author": "Ilya Volodin <ivolodin@demandware.com>",
"license": "MIT",
"homepage": "https://github.com/SalesforceCommerceCloud/plugin-applepay",
"devDependencies": {
"chai": "^3.5.0",
"cleave.js": "1.5.0",
"css-loader": "^0.28.11",
"eslint": "^3.19.0",
"eslint-config-airbnb-base": "^5.0.3",
"eslint-plugin-import": "^1.16.0",
"mocha": "^5.2.0",
"mocha-junit-reporter": "^1.12.0",
"node-sass": "^4.12.0",
"postcss-loader": "^2.1.6",
"proxyquire": "1.7.4",
"sass-loader": "^7.3.1",
"sgmf-scripts": "^2.3.0",
"shelljs": "^0.7.7",
"sinon": "^1.17.7",
"stylelint": "^8.4.0",
"stylelint-config-standard": "^17.0.0",
"stylelint-scss": "^2.5.0"
},
"browserslist": [
"last 2 versions",
"ie >= 10"
],
"paths": {
"base": "../storefront-reference-architecture/cartridges/app_storefront_base/"
}
}
```
It was working fine till 15 days back. I had re-installed my windows and it stopped working any think to do with windows ENV variable.
|
2021/10/10
|
[
"https://Stackoverflow.com/questions/69516584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16418162/"
] |
You can create a second list that stores the valid index values.
```
import random
our = [3, 3, 0, 3, 3, 7]
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
# index: [0, 1, 3, 4]
random_index = random.choice(index)
```
**EDIT:** You can perform a sanity check for a non-zero value being present.
The `any()` function returns `True` if any element of an iterable is `True`. `0` is treated as `False` and all non-zero numbers are `True`.
```
valid_index = any(our[:-1])
if valid_index:
index = []
for i in range(0, len(our)-1) :
if our[i] != 0 :
index.append(i)
```
|
You can use a while loop to check if the number equals 0 or not.
```
import random
our = [3, 6, 2, 0, 3, 0, 5]
random_number = 0
while random_number == 0:
random_index = random.randint(0, len(our)-2)
random_number = our[random_index]
print(random_number)
```
|
16,276,913
|
at the moment I do:
```
def get_inet_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('mysite.com', 80))
return s.getsockname()[0]
```
This was based on:
[Finding local IP addresses using Python's stdlib](https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib)
However, This looks a bit dubious. As far as I can tell, it opens a socket to mysite.com:80, and then returns the first address for that socket, assuming it to be an IPv4 address. This seems a bit dodgy... i dont think we can ever guaranteee that to be the case.
Thats my first question, is it safe? On an IPv6-enable server, could the IPv6 address ever be returned unexpectedly?
My second question, is how do I get the IPv6 address in a similar way. Im going to modify the function to take an optional ipv6 paramater.
|
2013/04/29
|
[
"https://Stackoverflow.com/questions/16276913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194306/"
] |
The question is, do you just want to connect, or do you really want the address?
If you just want to connect, you can do
```
s = socket.create_connection(('mysite.com', 80))
```
and have the connection established.
However, if you are interested in the address, you can go one of these ways:
```
def get_ip_6(host, port=0):
import socket
# search only for the wanted v6 addresses
result = socket.getaddrinfo(host, port, socket.AF_INET6)
return result # or:
return result[0][4][0] # just returns the first answer and only the address
```
or, to be closer to [another, already presented solution](https://stackoverflow.com/a/16277577/296974):
```
def get_ip_6(host, port=0):
# search for all addresses, but take only the v6 ones
alladdr = socket.getaddrinfo(host,port)
ip6 = filter(
lambda x: x[0] == socket.AF_INET6, # means its ip6
alladdr
)
# if you want just the sockaddr
# return map(lambda x:x[4],ip6)
return list(ip6)[0][4][0]
```
|
You should be using the function [socket.getaddrinfo()](http://docs.python.org/2/library/socket.html#socket.getaddrinfo)
Example code to get IPv6
```
def get_ip_6(host,port=80):
# discard the (family, socktype, proto, canonname) part of the tuple
# and make sure the ips are unique
alladdr = list(
set(
map(
lambda x: x[4],
socket.getaddrinfo(host,port)
)
)
)
ip6 = filter(
lambda x: ':' in x[0], # means its ip6
alladdr
)
return ip6
```
|
4,093,118
|
Is there a way to increment the year on filtered objects using the update() method?
I am using:
```
python 2.6.5
django 1.2.1 final
mysql Ver 14.14 Distrib 5.1.41
```
I know it's possible to do something like this:
```
today = datetime.datetime.today()
for event in Event.objects.filter(end_date__lt=today).iterator():
event.start_date = festival.start_date + datetime.timedelta(365)
event.end_date = festival.end_date + datetime.timedelta(365)
event.save()
```
However, in some cases, I would prefer to use the update() method.
```
# This does not work..
Event.objects.all().update(
start_date=F('start_date') + datetime.timedelta(365),
end_date=F('end_date') + datetime.timedelta(365)
)
```
With the example above, I get:
```
Warning: Truncated incorrect DOUBLE value: '365 0:0:0'
```
The sql query it's trying to make is:
```
UPDATE `events_event` SET `start_date` = `events_event`.`start_date` + 365 days, 0:00:00, `end_date` = `events_event`.`end_date` + 365 days, 0:00:00
```
I found something in the mysql guide, but this is raw sql!
```
SELECT DATE_ADD('2008-12-15', INTERVAL 1 YEAR);
```
Any idea?
|
2010/11/04
|
[
"https://Stackoverflow.com/questions/4093118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208347/"
] |
One potential cause of *"Warning: Data truncated for column X"* exception is the use of non-whole day values for the timedelta being added to the **DateField** - it is fine in python, but fails when written to the mysql db. If you have a **DateTimeField**, it works too, since the precision of the persisted field matches the precision of the timedelta.
I.e.:
```
>>> from django.db.models import F
>>> from datetime import timedelta
>>> from myapp.models import MyModel
>>> [field for field in MyModel._meta.fields if field.name == 'valid_until'][0]
<django.db.models.fields.DateField object at 0x3d72fd0>
>>> [field for field in MyModel._meta.fields if field.name == 'timestamp'][0]
<django.db.models.fields.DateTimeField object at 0x43756d0>
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3))
1L
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3.5))
Traceback (most recent call last):
...
Warning: Data truncated for column 'valid_until' at row 1
>>> MyModel.objects.filter(pk=1).update(timestamp=F('timestamp') + timedelta(days=3.5))
1L
```
|
Quick but ugly:
```
>>> a.created.timetuple()
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=2, tm_hour=2, tm_min=35, tm_se
c=14, tm_wday=3, tm_yday=307, tm_isdst=-1)
>>> time = list(a.created.timetuple())
>>> time[0] = time[0] + 1
>>> time
[2001, 11, 2, 2, 35, 14, 3, 307, -1]
>>>
```
|
4,093,118
|
Is there a way to increment the year on filtered objects using the update() method?
I am using:
```
python 2.6.5
django 1.2.1 final
mysql Ver 14.14 Distrib 5.1.41
```
I know it's possible to do something like this:
```
today = datetime.datetime.today()
for event in Event.objects.filter(end_date__lt=today).iterator():
event.start_date = festival.start_date + datetime.timedelta(365)
event.end_date = festival.end_date + datetime.timedelta(365)
event.save()
```
However, in some cases, I would prefer to use the update() method.
```
# This does not work..
Event.objects.all().update(
start_date=F('start_date') + datetime.timedelta(365),
end_date=F('end_date') + datetime.timedelta(365)
)
```
With the example above, I get:
```
Warning: Truncated incorrect DOUBLE value: '365 0:0:0'
```
The sql query it's trying to make is:
```
UPDATE `events_event` SET `start_date` = `events_event`.`start_date` + 365 days, 0:00:00, `end_date` = `events_event`.`end_date` + 365 days, 0:00:00
```
I found something in the mysql guide, but this is raw sql!
```
SELECT DATE_ADD('2008-12-15', INTERVAL 1 YEAR);
```
Any idea?
|
2010/11/04
|
[
"https://Stackoverflow.com/questions/4093118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208347/"
] |
One potential cause of *"Warning: Data truncated for column X"* exception is the use of non-whole day values for the timedelta being added to the **DateField** - it is fine in python, but fails when written to the mysql db. If you have a **DateTimeField**, it works too, since the precision of the persisted field matches the precision of the timedelta.
I.e.:
```
>>> from django.db.models import F
>>> from datetime import timedelta
>>> from myapp.models import MyModel
>>> [field for field in MyModel._meta.fields if field.name == 'valid_until'][0]
<django.db.models.fields.DateField object at 0x3d72fd0>
>>> [field for field in MyModel._meta.fields if field.name == 'timestamp'][0]
<django.db.models.fields.DateTimeField object at 0x43756d0>
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3))
1L
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3.5))
Traceback (most recent call last):
...
Warning: Data truncated for column 'valid_until' at row 1
>>> MyModel.objects.filter(pk=1).update(timestamp=F('timestamp') + timedelta(days=3.5))
1L
```
|
```
from dateutil.relativedelta import relativedelta
yourdate = datetime.datetime(2010, 11, 4, 10, 14, 54, 518749)
yourdate += relativedelta(years=+1)
```
Relativedelta takes many time arguments, from seconds to years...
|
4,093,118
|
Is there a way to increment the year on filtered objects using the update() method?
I am using:
```
python 2.6.5
django 1.2.1 final
mysql Ver 14.14 Distrib 5.1.41
```
I know it's possible to do something like this:
```
today = datetime.datetime.today()
for event in Event.objects.filter(end_date__lt=today).iterator():
event.start_date = festival.start_date + datetime.timedelta(365)
event.end_date = festival.end_date + datetime.timedelta(365)
event.save()
```
However, in some cases, I would prefer to use the update() method.
```
# This does not work..
Event.objects.all().update(
start_date=F('start_date') + datetime.timedelta(365),
end_date=F('end_date') + datetime.timedelta(365)
)
```
With the example above, I get:
```
Warning: Truncated incorrect DOUBLE value: '365 0:0:0'
```
The sql query it's trying to make is:
```
UPDATE `events_event` SET `start_date` = `events_event`.`start_date` + 365 days, 0:00:00, `end_date` = `events_event`.`end_date` + 365 days, 0:00:00
```
I found something in the mysql guide, but this is raw sql!
```
SELECT DATE_ADD('2008-12-15', INTERVAL 1 YEAR);
```
Any idea?
|
2010/11/04
|
[
"https://Stackoverflow.com/questions/4093118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208347/"
] |
One potential cause of *"Warning: Data truncated for column X"* exception is the use of non-whole day values for the timedelta being added to the **DateField** - it is fine in python, but fails when written to the mysql db. If you have a **DateTimeField**, it works too, since the precision of the persisted field matches the precision of the timedelta.
I.e.:
```
>>> from django.db.models import F
>>> from datetime import timedelta
>>> from myapp.models import MyModel
>>> [field for field in MyModel._meta.fields if field.name == 'valid_until'][0]
<django.db.models.fields.DateField object at 0x3d72fd0>
>>> [field for field in MyModel._meta.fields if field.name == 'timestamp'][0]
<django.db.models.fields.DateTimeField object at 0x43756d0>
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3))
1L
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3.5))
Traceback (most recent call last):
...
Warning: Data truncated for column 'valid_until' at row 1
>>> MyModel.objects.filter(pk=1).update(timestamp=F('timestamp') + timedelta(days=3.5))
1L
```
|
Have you seen this: [Increasing a datetime field with queryset.update](https://stackoverflow.com/questions/3843250/increasing-a-datetime-field-with-queryset-update) ? I also remember successfully using queryset .update() with timedelta with MySQL backend.
|
58,537,324
|
For multiple `csv` files in a folder, I hope to loop all files ends with `csv` and merge as one excel file, here I give two examples:
**first.csv**
```
date a b
0 2019.1 1.0 NaN
1 2019.2 NaN 2.0
2 2019.3 3.0 2.0
3 2019.4 3.0 NaN
```
**second.csv**
```
date c d
0 2019.1 1.0 NaN
1 2019.2 5.0 2.0
2 2019.3 3.0 7.0
3 2019.4 6.0 NaN
4 2019.5 NaN 10.0
```
**...**
My desired output is like this, merging them based on `date`:
```
date a b c d
0 2019/1/31 1.0 NaN 1.0 NaN
1 2019/2/28 NaN 2.0 5.0 2.0
2 2019/3/31 3.0 2.0 3.0 7.0
3 2019/4/30 3.0 NaN 6.0 NaN
4 2019/5/31 NaN NaN NaN 10.0
```
I have edited the following code, but obviously there are some parts about `date` convert and merge `dfs` are incorrect:
```
import numpy as np
import pandas as pd
import glob
dfs = pd.DataFrame()
for file_name in glob.glob("*.csv"):
# print(file_name)
df = pd.read_csv(file_name, engine='python', skiprows=2, encoding='utf-8')
df = df.dropna()
df = df.dropna(axis = 1)
df['date'] = pd.to_datetime(df['date'], format='%Y.%m')
...
dfs = pd.merge(df1, df2, on = 'date', how= "outer")
# save the data frame
writer = pd.ExcelWriter('output.xlsx')
dfs.to_excel(writer,'sheet1')
writer.save()
```
Please help me. Thank you.
|
2019/10/24
|
[
"https://Stackoverflow.com/questions/58537324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8410477/"
] |
You can use Linq to perform your shift, here is a simple method you can use
```
public int[] shiftRight(int[] array, int shift)
{
var result = new List<int>();
var toTake = array.Take(shift);
var toSkip = array.Skip(shift);
result.AddRange(toSkip);
result.AddRange(toTake);
return result.ToArray();
}
```
|
If this is only for strings and the wraparound is necessary I would suggest to use `str.Substring(0,shift)`
and append it to `str.Substring(shift)` (don't try to reinvent the weel)
(some info about the substring method: [String.Substring](https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8) )
otherwise the reason why it did not work is because you only saved the first value of the array instead of all the values you wanted to shift.
---
Do not save only the first value in the array
```cs
var x = strArray[0];
```
use
```cs
string[] x = new string[shift];
for (int i = 0; i < shift; i++)
{
x[i] = strArray[i];
}
```
instead so you collect all the values you need to add to the end.
>
> EDIT: forgot the shifting
>
>
>
Shift the old data to the left
```cs
for (int i = 0; i < strArray.Length-shift; i++)
{
strArray[i] = strArray[i+shift];
}
```
And replace
```cs
strArray[strArray.Length - shift] = x;
```
for
```cs
for(int i = 0; i < x.Length; i++){
int newlocation = (strArray.Length - shift)+i;
strArray[newlocation] = x[i];
}
```
also replace the print loop for
```cs
Console.WriteLine(string.Join(" ", strArray));
```
its easier and makes it one line instead of three lines of code.
(also the docs for the Join function [string.Join](https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8))
|
58,537,324
|
For multiple `csv` files in a folder, I hope to loop all files ends with `csv` and merge as one excel file, here I give two examples:
**first.csv**
```
date a b
0 2019.1 1.0 NaN
1 2019.2 NaN 2.0
2 2019.3 3.0 2.0
3 2019.4 3.0 NaN
```
**second.csv**
```
date c d
0 2019.1 1.0 NaN
1 2019.2 5.0 2.0
2 2019.3 3.0 7.0
3 2019.4 6.0 NaN
4 2019.5 NaN 10.0
```
**...**
My desired output is like this, merging them based on `date`:
```
date a b c d
0 2019/1/31 1.0 NaN 1.0 NaN
1 2019/2/28 NaN 2.0 5.0 2.0
2 2019/3/31 3.0 2.0 3.0 7.0
3 2019/4/30 3.0 NaN 6.0 NaN
4 2019/5/31 NaN NaN NaN 10.0
```
I have edited the following code, but obviously there are some parts about `date` convert and merge `dfs` are incorrect:
```
import numpy as np
import pandas as pd
import glob
dfs = pd.DataFrame()
for file_name in glob.glob("*.csv"):
# print(file_name)
df = pd.read_csv(file_name, engine='python', skiprows=2, encoding='utf-8')
df = df.dropna()
df = df.dropna(axis = 1)
df['date'] = pd.to_datetime(df['date'], format='%Y.%m')
...
dfs = pd.merge(df1, df2, on = 'date', how= "outer")
# save the data frame
writer = pd.ExcelWriter('output.xlsx')
dfs.to_excel(writer,'sheet1')
writer.save()
```
Please help me. Thank you.
|
2019/10/24
|
[
"https://Stackoverflow.com/questions/58537324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8410477/"
] |
You can use Linq to perform your shift, here is a simple method you can use
```
public int[] shiftRight(int[] array, int shift)
{
var result = new List<int>();
var toTake = array.Take(shift);
var toSkip = array.Skip(shift);
result.AddRange(toSkip);
result.AddRange(toTake);
return result.ToArray();
}
```
|
Here is quick fix for you. please check following code.
I shift element to left by 1 position you can change code as par your requirement.
Input array: 1 2 3 4 5 6
Input how many times to shift left: 1
Output : 2 3 4 5 6 1
```
int[] nums = {1, 2, 3, 4, 5, 6};
Console.WriteLine("\nArray1: [{0}]", string.Join(", ", nums));
var temp = nums[0];
for (var i = 0; i < nums.Length - 1; i++)
{
nums[i] = nums[i + 1];
}
nums[nums.Length - 1] = temp;
Console.WriteLine("\nAfter rotating array becomes: [{0}]", string.Join(", ", nums));
```
|
67,539,918
|
After installing Flask, When I used
`from flask import Flask`
to check if flask is properly installed or not, it gave the following error
```
>>> from flask import Flask
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/flask/__init__.py", line 3, in <module>
from werkzeug.exceptions import abort
File "/usr/local/lib/python3.5/dist-packages/werkzeug/__init__.py", line 1, in <module>
from .serving import run_simple
File "/usr/local/lib/python3.5/dist-packages/werkzeug/serving.py", line 151
server: "BaseWSGIServer"
^
SyntaxError: invalid syntax
```
How to solve this issue.
|
2021/05/14
|
[
"https://Stackoverflow.com/questions/67539918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12194111/"
] |
Flask is now at 2.0.0, which has ratcheted forward on requirements.
If you're on a system that is still on Python3.5, your alternative is to install the most recent in the 1.x line, and put
```
Flask==1.1.4
```
in your `requirements.txt`, or
```
venv/bin/pip install Flask==1.1.4
```
to install it manually.
|
The error indicates that you're running Python 3.5. Variable annotations that the library is attempting to use weren't [introduced until 3.6 though](https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations).
Upgrade to at least 3.6 to solve this. 3.9 is available too, so unless you need to use an older version for some reason, you might as well just to a full upgrade of your version.
|
67,539,918
|
After installing Flask, When I used
`from flask import Flask`
to check if flask is properly installed or not, it gave the following error
```
>>> from flask import Flask
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/flask/__init__.py", line 3, in <module>
from werkzeug.exceptions import abort
File "/usr/local/lib/python3.5/dist-packages/werkzeug/__init__.py", line 1, in <module>
from .serving import run_simple
File "/usr/local/lib/python3.5/dist-packages/werkzeug/serving.py", line 151
server: "BaseWSGIServer"
^
SyntaxError: invalid syntax
```
How to solve this issue.
|
2021/05/14
|
[
"https://Stackoverflow.com/questions/67539918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12194111/"
] |
Flask is now at 2.0.0, which has ratcheted forward on requirements.
If you're on a system that is still on Python3.5, your alternative is to install the most recent in the 1.x line, and put
```
Flask==1.1.4
```
in your `requirements.txt`, or
```
venv/bin/pip install Flask==1.1.4
```
to install it manually.
|
Flask is now at 2.0.0, and has ratcheted forward on requirements.
If you're on a system that is still on Python3.5, you are out of luck for 2.0.0. Your alternative is to install the most recent in the 1.x line.
Specify
```
Flask==1.4.4
```
if you're using `requirements.txt`, or
```
venv/bin/pip install Flask==1.1.4
```
to install it manually.
|
37,316,731
|
I have a bash script which reads variable from environment and then passes it to the python script like this
```
#!/usr/bin/env bash
if [ -n "${my_param}" ]
then
my_param_str="--my_param ${my_param}"
fi
python -u my_script.py ${my_param_str}
```
Corresponding python script look like this
```
parser = argparse.ArgumentParser(description='My script')
parser.add_argument('--my_param',
type=str,
default='')
parsed_args = parser.parse_args()
print(parsed_args.description)
```
I want to provide string with dash characters "Some -- string" as an argument, but it doesn't work via bash script, but calling directly through command line works ok.
```
export my_param="Some -- string"
./launch_my_script.sh
```
gives an error `unrecognized arguments: -- string` and
`python my_script.py --my_param "Some -- string"` works well.
I've tried to play with **nargs** and escape `my_param_str="--my_param '${my_param}'"` this way, but both solutions didn't work.
Any workaround for this case? Or different approach how to handle this?
|
2016/05/19
|
[
"https://Stackoverflow.com/questions/37316731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1744914/"
] |
For the limited example you can basically get the same behavior just using
```
arg = os.environ.get('my_param', '')
```
where the first argument to `get` is the variable name and the second is the default value used should the var not be in the environment.
|
The quotes you write around the string do not get preserved when you assign a Bash string variable:
```
$ export my_param="Some -- string"
$ echo $my_param
Some -- string
```
You need to place the quotes around the variable again when you use it to create the `my_param_str`:
```
my_param_str="--my_param \"${my_param}\""
```
|
37,316,731
|
I have a bash script which reads variable from environment and then passes it to the python script like this
```
#!/usr/bin/env bash
if [ -n "${my_param}" ]
then
my_param_str="--my_param ${my_param}"
fi
python -u my_script.py ${my_param_str}
```
Corresponding python script look like this
```
parser = argparse.ArgumentParser(description='My script')
parser.add_argument('--my_param',
type=str,
default='')
parsed_args = parser.parse_args()
print(parsed_args.description)
```
I want to provide string with dash characters "Some -- string" as an argument, but it doesn't work via bash script, but calling directly through command line works ok.
```
export my_param="Some -- string"
./launch_my_script.sh
```
gives an error `unrecognized arguments: -- string` and
`python my_script.py --my_param "Some -- string"` works well.
I've tried to play with **nargs** and escape `my_param_str="--my_param '${my_param}'"` this way, but both solutions didn't work.
Any workaround for this case? Or different approach how to handle this?
|
2016/05/19
|
[
"https://Stackoverflow.com/questions/37316731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1744914/"
] |
Your bash needs to look like this:
```
if [ -n "${my_param}" ]
then
my_param_str="--my_param \"${my_param}\""
fi
echo ${my_param_str}|xargs python -u my_script.py
```
Otherwise, the quotes around the parameter string will not be preserved, and "Some", "--" and "thing" will be passed as three separate arguments.
|
For the limited example you can basically get the same behavior just using
```
arg = os.environ.get('my_param', '')
```
where the first argument to `get` is the variable name and the second is the default value used should the var not be in the environment.
|
37,316,731
|
I have a bash script which reads variable from environment and then passes it to the python script like this
```
#!/usr/bin/env bash
if [ -n "${my_param}" ]
then
my_param_str="--my_param ${my_param}"
fi
python -u my_script.py ${my_param_str}
```
Corresponding python script look like this
```
parser = argparse.ArgumentParser(description='My script')
parser.add_argument('--my_param',
type=str,
default='')
parsed_args = parser.parse_args()
print(parsed_args.description)
```
I want to provide string with dash characters "Some -- string" as an argument, but it doesn't work via bash script, but calling directly through command line works ok.
```
export my_param="Some -- string"
./launch_my_script.sh
```
gives an error `unrecognized arguments: -- string` and
`python my_script.py --my_param "Some -- string"` works well.
I've tried to play with **nargs** and escape `my_param_str="--my_param '${my_param}'"` this way, but both solutions didn't work.
Any workaround for this case? Or different approach how to handle this?
|
2016/05/19
|
[
"https://Stackoverflow.com/questions/37316731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1744914/"
] |
Your bash needs to look like this:
```
if [ -n "${my_param}" ]
then
my_param_str="--my_param \"${my_param}\""
fi
echo ${my_param_str}|xargs python -u my_script.py
```
Otherwise, the quotes around the parameter string will not be preserved, and "Some", "--" and "thing" will be passed as three separate arguments.
|
The quotes you write around the string do not get preserved when you assign a Bash string variable:
```
$ export my_param="Some -- string"
$ echo $my_param
Some -- string
```
You need to place the quotes around the variable again when you use it to create the `my_param_str`:
```
my_param_str="--my_param \"${my_param}\""
```
|
50,420,139
|
I am using python to generate a query text which I then send to the `SQL server`. The query is created in a function that accepts a list of strings which are then inserted into the query.
The query looks like:
```
SELECT *
FROM DB
WHERE last_word in ('red', 'phone', 'robin')
```
The issue is that here I have just 3 words, `red`, `phone`, and `robin`, but in another use case I have over 4,000 words and the response takes about 2 hours. How can I rewrite this query to make it more performant?
|
2018/05/18
|
[
"https://Stackoverflow.com/questions/50420139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367204/"
] |
How many rows do you have in "DB"? Are there more "last\_word"s matching the 4000 words in the IN clause than not? If so, it would be better to use NOT IN, to exclude instead of include. Also, try to never use SELECT \* since this wildcard is very unperformant, it's better to explicitly define the columns you want to include in your query.
You could also try to put the 4000 words to match on in a (temporary) table or a CTE and then join on it, since joins usually work better than large loads of data within the IN clause. With this, I still recommend to not use the wildcard in the SELECT statement.
|
Try doing something like this:
```
SELECT *
FROM DB INNER JOIN WORDS_TABLE
ON DB.WORDS = WORDS_TABLE.WORDS;
```
Instead of the `*` use whatever you want to get.
`JOIN` in this case will be faster than the `IN` as you will have to write another inner query if you are using a table.
|
50,420,139
|
I am using python to generate a query text which I then send to the `SQL server`. The query is created in a function that accepts a list of strings which are then inserted into the query.
The query looks like:
```
SELECT *
FROM DB
WHERE last_word in ('red', 'phone', 'robin')
```
The issue is that here I have just 3 words, `red`, `phone`, and `robin`, but in another use case I have over 4,000 words and the response takes about 2 hours. How can I rewrite this query to make it more performant?
|
2018/05/18
|
[
"https://Stackoverflow.com/questions/50420139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367204/"
] |
How many rows do you have in "DB"? Are there more "last\_word"s matching the 4000 words in the IN clause than not? If so, it would be better to use NOT IN, to exclude instead of include. Also, try to never use SELECT \* since this wildcard is very unperformant, it's better to explicitly define the columns you want to include in your query.
You could also try to put the 4000 words to match on in a (temporary) table or a CTE and then join on it, since joins usually work better than large loads of data within the IN clause. With this, I still recommend to not use the wildcard in the SELECT statement.
|
Put your data into a temp table or CTE. This would make for easier addition of new data. Likewise, you’ll have to do an inner join to your source table to make sure you capture everything.
Hope this helps.
|
50,420,139
|
I am using python to generate a query text which I then send to the `SQL server`. The query is created in a function that accepts a list of strings which are then inserted into the query.
The query looks like:
```
SELECT *
FROM DB
WHERE last_word in ('red', 'phone', 'robin')
```
The issue is that here I have just 3 words, `red`, `phone`, and `robin`, but in another use case I have over 4,000 words and the response takes about 2 hours. How can I rewrite this query to make it more performant?
|
2018/05/18
|
[
"https://Stackoverflow.com/questions/50420139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367204/"
] |
optimization strategies:
1. add an index on `last_word`
```
CREATE INDEX ON db(last_word)
```
2. store the filter words in a table and use a `WHERE exists` (or inner join)
```
WITH words (word) AS (
VALUES ('red'), ('phone'), ('robin')
)
SELECT *
FROM db
WHERE EXISTS (SELECT TRUE FROM words WHERE word = last_word)
```
or
```
WITH words (word) AS (
VALUES ('red'), ('phone'), ('robin')
)
SELECT db.*
FROM db
JOIN words ON db.last_word = words.word
```
The `WHERE EXISTS` here should be *slightly* faster than `JOIN`
|
How many rows do you have in "DB"? Are there more "last\_word"s matching the 4000 words in the IN clause than not? If so, it would be better to use NOT IN, to exclude instead of include. Also, try to never use SELECT \* since this wildcard is very unperformant, it's better to explicitly define the columns you want to include in your query.
You could also try to put the 4000 words to match on in a (temporary) table or a CTE and then join on it, since joins usually work better than large loads of data within the IN clause. With this, I still recommend to not use the wildcard in the SELECT statement.
|
50,420,139
|
I am using python to generate a query text which I then send to the `SQL server`. The query is created in a function that accepts a list of strings which are then inserted into the query.
The query looks like:
```
SELECT *
FROM DB
WHERE last_word in ('red', 'phone', 'robin')
```
The issue is that here I have just 3 words, `red`, `phone`, and `robin`, but in another use case I have over 4,000 words and the response takes about 2 hours. How can I rewrite this query to make it more performant?
|
2018/05/18
|
[
"https://Stackoverflow.com/questions/50420139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367204/"
] |
optimization strategies:
1. add an index on `last_word`
```
CREATE INDEX ON db(last_word)
```
2. store the filter words in a table and use a `WHERE exists` (or inner join)
```
WITH words (word) AS (
VALUES ('red'), ('phone'), ('robin')
)
SELECT *
FROM db
WHERE EXISTS (SELECT TRUE FROM words WHERE word = last_word)
```
or
```
WITH words (word) AS (
VALUES ('red'), ('phone'), ('robin')
)
SELECT db.*
FROM db
JOIN words ON db.last_word = words.word
```
The `WHERE EXISTS` here should be *slightly* faster than `JOIN`
|
Try doing something like this:
```
SELECT *
FROM DB INNER JOIN WORDS_TABLE
ON DB.WORDS = WORDS_TABLE.WORDS;
```
Instead of the `*` use whatever you want to get.
`JOIN` in this case will be faster than the `IN` as you will have to write another inner query if you are using a table.
|
50,420,139
|
I am using python to generate a query text which I then send to the `SQL server`. The query is created in a function that accepts a list of strings which are then inserted into the query.
The query looks like:
```
SELECT *
FROM DB
WHERE last_word in ('red', 'phone', 'robin')
```
The issue is that here I have just 3 words, `red`, `phone`, and `robin`, but in another use case I have over 4,000 words and the response takes about 2 hours. How can I rewrite this query to make it more performant?
|
2018/05/18
|
[
"https://Stackoverflow.com/questions/50420139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367204/"
] |
optimization strategies:
1. add an index on `last_word`
```
CREATE INDEX ON db(last_word)
```
2. store the filter words in a table and use a `WHERE exists` (or inner join)
```
WITH words (word) AS (
VALUES ('red'), ('phone'), ('robin')
)
SELECT *
FROM db
WHERE EXISTS (SELECT TRUE FROM words WHERE word = last_word)
```
or
```
WITH words (word) AS (
VALUES ('red'), ('phone'), ('robin')
)
SELECT db.*
FROM db
JOIN words ON db.last_word = words.word
```
The `WHERE EXISTS` here should be *slightly* faster than `JOIN`
|
Put your data into a temp table or CTE. This would make for easier addition of new data. Likewise, you’ll have to do an inner join to your source table to make sure you capture everything.
Hope this helps.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
using pieces from both @hharnisc and @mick-t answers.
```
pip install python-ldap \
--global-option=build_ext \
--global-option="-I$(xcrun --show-sdk-path)/usr/include/sasl"
```
|
I had the same problem. I'm using Macports on my Mac and I have cyrus-sasl2 installed which provides sasl.h in /opt/local/include/sasl/. You can pass options to build\_ext using pip's global-option argument. To pass the include PATH to /opt/local/include/sasl/sasl.h run pip like this:
`pip install python-ldap --global-option=build_ext --global-option="-I/opt/local/include/sasl"`
Alternatively you could point it to whatever the output from `xcrun --show-sdk-path` provides. On my box that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk`
Then you need to determine the PATH to the sasl header files. For me that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/sasl/`
Let me know if that helps or you need a hand.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
I used a combination of posts I found about this problem (including this one) to eventually come up with this (copied from a larger script):
```
export XC_SDK=$(xcrun --show-sdk-path)
export USR_INC=$XC_SDK/usr/include
export PATH=$USR_INC:$PATH
echo "installing python-ldap"
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install python-ldap
```
You can test it with `python -c "import ldap"`
The main reason I didn't follow the advice of @hharnisc was that on my local machine /usr/local had not moved, so I just temporarily put $XC\_SDK before it on the path, and that seems to work.
some sources:
[how to install PIL on Macosx 10.9?](https://stackoverflow.com/questions/22449304/how-to-install-pil-on-macosx-10-9?rq=1)
|
I got this error when running buildout.
I fixed it, first finding the sasl.h file:
```
mdfind -name sasl.h
```
then defining the corresponding CFLAGS environment variable:
```
export CFLAGS="-I/opt/local/include/sasl"
```
and finally running buildout again.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
I had the same problem. I'm using Macports on my Mac and I have cyrus-sasl2 installed which provides sasl.h in /opt/local/include/sasl/. You can pass options to build\_ext using pip's global-option argument. To pass the include PATH to /opt/local/include/sasl/sasl.h run pip like this:
`pip install python-ldap --global-option=build_ext --global-option="-I/opt/local/include/sasl"`
Alternatively you could point it to whatever the output from `xcrun --show-sdk-path` provides. On my box that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk`
Then you need to determine the PATH to the sasl header files. For me that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/sasl/`
Let me know if that helps or you need a hand.
|
I used a combination of posts I found about this problem (including this one) to eventually come up with this (copied from a larger script):
```
export XC_SDK=$(xcrun --show-sdk-path)
export USR_INC=$XC_SDK/usr/include
export PATH=$USR_INC:$PATH
echo "installing python-ldap"
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install python-ldap
```
You can test it with `python -c "import ldap"`
The main reason I didn't follow the advice of @hharnisc was that on my local machine /usr/local had not moved, so I just temporarily put $XC\_SDK before it on the path, and that seems to work.
some sources:
[how to install PIL on Macosx 10.9?](https://stackoverflow.com/questions/22449304/how-to-install-pil-on-macosx-10-9?rq=1)
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
**A workaround**
/usr/include appears to have moved
```
$ xcrun --show-sdk-path
$ sudo ln -s <the_path_from_above_command>/usr/include /usr/include
```
Now run pip install!
|
I had the same problem. I'm using Macports on my Mac and I have cyrus-sasl2 installed which provides sasl.h in /opt/local/include/sasl/. You can pass options to build\_ext using pip's global-option argument. To pass the include PATH to /opt/local/include/sasl/sasl.h run pip like this:
`pip install python-ldap --global-option=build_ext --global-option="-I/opt/local/include/sasl"`
Alternatively you could point it to whatever the output from `xcrun --show-sdk-path` provides. On my box that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk`
Then you need to determine the PATH to the sasl header files. For me that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/sasl/`
Let me know if that helps or you need a hand.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
In my particular case, I couldn't simply use the `pip` arguments noted in other answers because I'm using it with `tox` to install dependencies from a requirements.txt file, and I need my tox.ini to remain compatible with non-Mac environments.
I was able to resolve this in much simpler fashion: exporting `CFLAGS` such that it adds an include path to the sasl headers already installed by Xcode:
```
$ pip install python-ldap
...
building '_ldap' extension
creating build/temp.macosx-10.10-x86_64-2.7
creating build/temp.macosx-10.10-x86_64-2.7/Modules
clang -fno-strict-aliasing -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DHAVE_SASL -DHAVE_TLS -DHAVE_LIBLDAP_R -DHAVE_LIBLDAP_R -DLDAPMODULE_VERSION=2.4.19 -IModules -I/opt/openldap-RE24/include -I/usr/include/sasl -I/usr/include -I/Users/bc/.pyenv/versions/2.7.10/include/python2.7 -c Modules/LDAPObject.c -o build/temp.macosx-10.10-x86_64-2.7/Modules/LDAPObject.o
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
#include <sasl.h>
^
1 error generated.
error: command 'clang' failed with exit status 1
$ export CFLAGS="-I$(xcrun --show-sdk-path)/usr/include/sasl"
$ pip install python-ldap
...
Successfully installed python-ldap-2.4.19
```
Depending on whether or not you use any userspace-friendly Python tools (I use [pyenv](https://github.com/yyuu/pyenv)), you may have to prefix your pip commands with `sudo`.
|
I used a combination of posts I found about this problem (including this one) to eventually come up with this (copied from a larger script):
```
export XC_SDK=$(xcrun --show-sdk-path)
export USR_INC=$XC_SDK/usr/include
export PATH=$USR_INC:$PATH
echo "installing python-ldap"
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install python-ldap
```
You can test it with `python -c "import ldap"`
The main reason I didn't follow the advice of @hharnisc was that on my local machine /usr/local had not moved, so I just temporarily put $XC\_SDK before it on the path, and that seems to work.
some sources:
[how to install PIL on Macosx 10.9?](https://stackoverflow.com/questions/22449304/how-to-install-pil-on-macosx-10-9?rq=1)
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
**A workaround**
/usr/include appears to have moved
```
$ xcrun --show-sdk-path
$ sudo ln -s <the_path_from_above_command>/usr/include /usr/include
```
Now run pip install!
|
I got this error when running buildout.
I fixed it, first finding the sasl.h file:
```
mdfind -name sasl.h
```
then defining the corresponding CFLAGS environment variable:
```
export CFLAGS="-I/opt/local/include/sasl"
```
and finally running buildout again.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
using pieces from both @hharnisc and @mick-t answers.
```
pip install python-ldap \
--global-option=build_ext \
--global-option="-I$(xcrun --show-sdk-path)/usr/include/sasl"
```
|
In my particular case, I couldn't simply use the `pip` arguments noted in other answers because I'm using it with `tox` to install dependencies from a requirements.txt file, and I need my tox.ini to remain compatible with non-Mac environments.
I was able to resolve this in much simpler fashion: exporting `CFLAGS` such that it adds an include path to the sasl headers already installed by Xcode:
```
$ pip install python-ldap
...
building '_ldap' extension
creating build/temp.macosx-10.10-x86_64-2.7
creating build/temp.macosx-10.10-x86_64-2.7/Modules
clang -fno-strict-aliasing -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DHAVE_SASL -DHAVE_TLS -DHAVE_LIBLDAP_R -DHAVE_LIBLDAP_R -DLDAPMODULE_VERSION=2.4.19 -IModules -I/opt/openldap-RE24/include -I/usr/include/sasl -I/usr/include -I/Users/bc/.pyenv/versions/2.7.10/include/python2.7 -c Modules/LDAPObject.c -o build/temp.macosx-10.10-x86_64-2.7/Modules/LDAPObject.o
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
#include <sasl.h>
^
1 error generated.
error: command 'clang' failed with exit status 1
$ export CFLAGS="-I$(xcrun --show-sdk-path)/usr/include/sasl"
$ pip install python-ldap
...
Successfully installed python-ldap-2.4.19
```
Depending on whether or not you use any userspace-friendly Python tools (I use [pyenv](https://github.com/yyuu/pyenv)), you may have to prefix your pip commands with `sudo`.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
In my particular case, I couldn't simply use the `pip` arguments noted in other answers because I'm using it with `tox` to install dependencies from a requirements.txt file, and I need my tox.ini to remain compatible with non-Mac environments.
I was able to resolve this in much simpler fashion: exporting `CFLAGS` such that it adds an include path to the sasl headers already installed by Xcode:
```
$ pip install python-ldap
...
building '_ldap' extension
creating build/temp.macosx-10.10-x86_64-2.7
creating build/temp.macosx-10.10-x86_64-2.7/Modules
clang -fno-strict-aliasing -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DHAVE_SASL -DHAVE_TLS -DHAVE_LIBLDAP_R -DHAVE_LIBLDAP_R -DLDAPMODULE_VERSION=2.4.19 -IModules -I/opt/openldap-RE24/include -I/usr/include/sasl -I/usr/include -I/Users/bc/.pyenv/versions/2.7.10/include/python2.7 -c Modules/LDAPObject.c -o build/temp.macosx-10.10-x86_64-2.7/Modules/LDAPObject.o
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
#include <sasl.h>
^
1 error generated.
error: command 'clang' failed with exit status 1
$ export CFLAGS="-I$(xcrun --show-sdk-path)/usr/include/sasl"
$ pip install python-ldap
...
Successfully installed python-ldap-2.4.19
```
Depending on whether or not you use any userspace-friendly Python tools (I use [pyenv](https://github.com/yyuu/pyenv)), you may have to prefix your pip commands with `sudo`.
|
I got this error when running buildout.
I fixed it, first finding the sasl.h file:
```
mdfind -name sasl.h
```
then defining the corresponding CFLAGS environment variable:
```
export CFLAGS="-I/opt/local/include/sasl"
```
and finally running buildout again.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
I had the same problem. I'm using Macports on my Mac and I have cyrus-sasl2 installed which provides sasl.h in /opt/local/include/sasl/. You can pass options to build\_ext using pip's global-option argument. To pass the include PATH to /opt/local/include/sasl/sasl.h run pip like this:
`pip install python-ldap --global-option=build_ext --global-option="-I/opt/local/include/sasl"`
Alternatively you could point it to whatever the output from `xcrun --show-sdk-path` provides. On my box that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk`
Then you need to determine the PATH to the sasl header files. For me that's:
`/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/sasl/`
Let me know if that helps or you need a hand.
|
I got this error when running buildout.
I fixed it, first finding the sasl.h file:
```
mdfind -name sasl.h
```
then defining the corresponding CFLAGS environment variable:
```
export CFLAGS="-I/opt/local/include/sasl"
```
and finally running buildout again.
|
22,079,173
|
I can't seem to be able to get the python ldap module installed on my OS X Mavericks 10.9.1 machine.
Kernel details:
uname -a
Darwin 13.0.0 Darwin Kernel Version 13.0.0: Thu Sep 19 22:22:27 PDT 2013; root:xnu-2422.1.72~6/RELEASE\_X86\_64 x86\_64
I tried what was suggested here:
<http://projects.skurfer.com/posts/2011/python_ldap_lion/>
But when I try to use pip I get a different error
Modules/LDAPObject.c:18:10: fatal error: 'sasl.h' file not found
\*#include sasl.h
I also tried what was suggested here:
[python-ldap OS X 10.6 and Python 2.6](https://stackoverflow.com/questions/6475118/python-ldap-os-x-10-6-and-python-2-6)
But with the same error.
I am hoping someone could help me out here.
|
2014/02/27
|
[
"https://Stackoverflow.com/questions/22079173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865366/"
] |
using pieces from both @hharnisc and @mick-t answers.
```
pip install python-ldap \
--global-option=build_ext \
--global-option="-I$(xcrun --show-sdk-path)/usr/include/sasl"
```
|
I used a combination of posts I found about this problem (including this one) to eventually come up with this (copied from a larger script):
```
export XC_SDK=$(xcrun --show-sdk-path)
export USR_INC=$XC_SDK/usr/include
export PATH=$USR_INC:$PATH
echo "installing python-ldap"
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install python-ldap
```
You can test it with `python -c "import ldap"`
The main reason I didn't follow the advice of @hharnisc was that on my local machine /usr/local had not moved, so I just temporarily put $XC\_SDK before it on the path, and that seems to work.
some sources:
[how to install PIL on Macosx 10.9?](https://stackoverflow.com/questions/22449304/how-to-install-pil-on-macosx-10-9?rq=1)
|
2,249,162
|
I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions?
|
2010/02/12
|
[
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You could do something like the following:
```
<% form_for @user, :url => { :action => "update" } do |user_form| %>
...
<% user_form.fields_for :profiles do |profiles_fields| %>
Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
<% end %>
<% end %>
```
But since you already have an association, then might as well use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)'
|
You can use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)' to do this; but there's a little trick in forms:
You must use the singular, and call fields\_for for each profile, like this:
```
<% form_for @user do |f| -%>
<% @user.profiles.each do %>
<% f.fields_for :profile_attributes, profile do |ff| -%>
<% end %>
```
Notice that is **:profile\_attributes**, instead of just **:profile**.
|
2,249,162
|
I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions?
|
2010/02/12
|
[
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You could do something like the following:
```
<% form_for @user, :url => { :action => "update" } do |user_form| %>
...
<% user_form.fields_for :profiles do |profiles_fields| %>
Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
<% end %>
<% end %>
```
But since you already have an association, then might as well use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)'
|
You should watch [RailsCasts Nested Model Form](http://railscasts.com/episodes/196-nested-model-form-part-1).
thanks [Ryan Bates](http://workingwithrails.com/person/6491-ryan-bates) great work.
|
2,249,162
|
I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions?
|
2010/02/12
|
[
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You could do something like the following:
```
<% form_for @user, :url => { :action => "update" } do |user_form| %>
...
<% user_form.fields_for :profiles do |profiles_fields| %>
Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
<% end %>
<% end %>
```
But since you already have an association, then might as well use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)'
|
<http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for>
This api dock link list many Nested Attributes Examples including one-to-one, one-to-many. It's very helpful!
|
2,249,162
|
I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions?
|
2010/02/12
|
[
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You should watch [RailsCasts Nested Model Form](http://railscasts.com/episodes/196-nested-model-form-part-1).
thanks [Ryan Bates](http://workingwithrails.com/person/6491-ryan-bates) great work.
|
You can use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)' to do this; but there's a little trick in forms:
You must use the singular, and call fields\_for for each profile, like this:
```
<% form_for @user do |f| -%>
<% @user.profiles.each do %>
<% f.fields_for :profile_attributes, profile do |ff| -%>
<% end %>
```
Notice that is **:profile\_attributes**, instead of just **:profile**.
|
2,249,162
|
I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions?
|
2010/02/12
|
[
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
<http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for>
This api dock link list many Nested Attributes Examples including one-to-one, one-to-many. It's very helpful!
|
You can use '[accepts\_nested\_attributes\_for](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)' to do this; but there's a little trick in forms:
You must use the singular, and call fields\_for for each profile, like this:
```
<% form_for @user do |f| -%>
<% @user.profiles.each do %>
<% f.fields_for :profile_attributes, profile do |ff| -%>
<% end %>
```
Notice that is **:profile\_attributes**, instead of just **:profile**.
|
2,249,162
|
I'm currently indexing my music collection with python. Ideally I'd like my output file to be formatted as;
```
"Artist;
Album;
Tracks - length - bitrate - md5
Artist2;
Album2;
Tracks - length - bitrate - md5"
```
But I can't seem to work out how to achieve this. Any suggestions?
|
2010/02/12
|
[
"https://Stackoverflow.com/questions/2249162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You should watch [RailsCasts Nested Model Form](http://railscasts.com/episodes/196-nested-model-form-part-1).
thanks [Ryan Bates](http://workingwithrails.com/person/6491-ryan-bates) great work.
|
<http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for>
This api dock link list many Nested Attributes Examples including one-to-one, one-to-many. It's very helpful!
|
9,394,947
|
I have been having a few issues using the quadrature function in python 2.7 (part of the scipy.integrate module). The equation I am trying to integrate is simply:
```
x/(d^2) - (x^2)
```
The integration is between limits a and b. However, I need to do the integration at 40 different values of d and am not sure how to pass in the second argument so as to loop the integration over the values of d. Any help would be much appreciated and is quadrature the best way to evaluate this problem.
|
2012/02/22
|
[
"https://Stackoverflow.com/questions/9394947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171835/"
] |
```
In [9]: from scipy.integrate import quad
In [10]: a = 0
In [11]: b = 1
In [12]: [quad(lambda x, d: x/(d**2)-x**2, a, b, args=d) for d in range(2, 5)]
Out[12]:
[(-0.20833333333333334, 2.3717550132075781e-15),
(-0.27777777777777773, 3.0886887822595405e-15),
(-0.30208333333333337, 3.3546344203581545e-15)]
```
Change the `for d in range(2, 5)` as required.
|
```
from numpy import arange
from scipy.integrate import quad
beg = 0.
end = 4.
res = []
for d in arange(1., 40.):
res.append(quad(lambda x: x/(d**2.)-(x**2.), beg, end))
```
You can then access the results by
```
print res[0]
```
or even
```
print res
```
|
9,394,947
|
I have been having a few issues using the quadrature function in python 2.7 (part of the scipy.integrate module). The equation I am trying to integrate is simply:
```
x/(d^2) - (x^2)
```
The integration is between limits a and b. However, I need to do the integration at 40 different values of d and am not sure how to pass in the second argument so as to loop the integration over the values of d. Any help would be much appreciated and is quadrature the best way to evaluate this problem.
|
2012/02/22
|
[
"https://Stackoverflow.com/questions/9394947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171835/"
] |
```
from numpy import arange
from scipy.integrate import quad
beg = 0.
end = 4.
res = []
for d in arange(1., 40.):
res.append(quad(lambda x: x/(d**2.)-(x**2.), beg, end))
```
You can then access the results by
```
print res[0]
```
or even
```
print res
```
|
If you want exact symbolic integration, you'll need to turn to [SymPy](http://docs.sympy.org/dev/modules/integrals/integrals.html). Try
```
import sympy
x = sympy.Symbol('x')
a = sympy.Symbol('a')
b = sympy.Symbol('b')
d = sympy.Symbol('d')
res = sympy.integrate(x / (d**2 - x**2), (x, a, b))
print(res)
```
This returns
```
log(a**2 - d**2)/2 - log(b**2 - d**2)/2
```
which you can most easily use to evaluate your data.
|
9,394,947
|
I have been having a few issues using the quadrature function in python 2.7 (part of the scipy.integrate module). The equation I am trying to integrate is simply:
```
x/(d^2) - (x^2)
```
The integration is between limits a and b. However, I need to do the integration at 40 different values of d and am not sure how to pass in the second argument so as to loop the integration over the values of d. Any help would be much appreciated and is quadrature the best way to evaluate this problem.
|
2012/02/22
|
[
"https://Stackoverflow.com/questions/9394947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171835/"
] |
```
In [9]: from scipy.integrate import quad
In [10]: a = 0
In [11]: b = 1
In [12]: [quad(lambda x, d: x/(d**2)-x**2, a, b, args=d) for d in range(2, 5)]
Out[12]:
[(-0.20833333333333334, 2.3717550132075781e-15),
(-0.27777777777777773, 3.0886887822595405e-15),
(-0.30208333333333337, 3.3546344203581545e-15)]
```
Change the `for d in range(2, 5)` as required.
|
If you want exact symbolic integration, you'll need to turn to [SymPy](http://docs.sympy.org/dev/modules/integrals/integrals.html). Try
```
import sympy
x = sympy.Symbol('x')
a = sympy.Symbol('a')
b = sympy.Symbol('b')
d = sympy.Symbol('d')
res = sympy.integrate(x / (d**2 - x**2), (x, a, b))
print(res)
```
This returns
```
log(a**2 - d**2)/2 - log(b**2 - d**2)/2
```
which you can most easily use to evaluate your data.
|
217,900
|
i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful
|
2008/10/20
|
[
"https://Stackoverflow.com/questions/217900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
] |
Read the [unit testing framework section](http://www.python.org/doc/2.5.2/lib/module-unittest.html) of the [Python Library Reference](http://www.python.org/doc/2.5.2/lib/lib.html).
A [basic example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) from the documentation:
```
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def testshuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def testchoice(self):
element = random.choice(self.seq)
self.assert_(element in self.seq)
def testsample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assert_(element in self.seq)
if __name__ == '__main__':
unittest.main()
```
|
Here's an [example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) and you might want to read a little more on [pythons unit testing](http://www.python.org/doc/2.5.2/lib/module-unittest.html).
|
217,900
|
i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful
|
2008/10/20
|
[
"https://Stackoverflow.com/questions/217900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
] |
Read the [unit testing framework section](http://www.python.org/doc/2.5.2/lib/module-unittest.html) of the [Python Library Reference](http://www.python.org/doc/2.5.2/lib/lib.html).
A [basic example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) from the documentation:
```
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def testshuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def testchoice(self):
element = random.choice(self.seq)
self.assert_(element in self.seq)
def testsample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assert_(element in self.seq)
if __name__ == '__main__':
unittest.main()
```
|
It's probably best to start off with the given `unittest` example. Some standard best practices:
* put all your tests in a `tests` folder at the root of your project.
* write one test module for each python module you're testing.
* test modules should start with the word `test`.
* test methods should start with the word `test`.
When you've become comfortable with `unittest` (and it shouldn't take long), there are some nice extensions to it that will make life easier as your tests grow in number and scope:
* [nose](http://somethingaboutorange.com/mrl/projects/nose/) -- easily find and run all your tests, and more.
* [testoob](http://testoob.sourceforge.net/) -- colorized output (and more, but that's why I use it).
* [pythoscope](http://pythoscope.org/) -- haven't tried it, but this will automatically generate (failing) test stubs for your application. Should save a lot of time writing boilerplate code.
|
217,900
|
i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful
|
2008/10/20
|
[
"https://Stackoverflow.com/questions/217900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17451/"
] |
It's probably best to start off with the given `unittest` example. Some standard best practices:
* put all your tests in a `tests` folder at the root of your project.
* write one test module for each python module you're testing.
* test modules should start with the word `test`.
* test methods should start with the word `test`.
When you've become comfortable with `unittest` (and it shouldn't take long), there are some nice extensions to it that will make life easier as your tests grow in number and scope:
* [nose](http://somethingaboutorange.com/mrl/projects/nose/) -- easily find and run all your tests, and more.
* [testoob](http://testoob.sourceforge.net/) -- colorized output (and more, but that's why I use it).
* [pythoscope](http://pythoscope.org/) -- haven't tried it, but this will automatically generate (failing) test stubs for your application. Should save a lot of time writing boilerplate code.
|
Here's an [example](http://www.python.org/doc/2.5.2/lib/minimal-example.html) and you might want to read a little more on [pythons unit testing](http://www.python.org/doc/2.5.2/lib/module-unittest.html).
|
64,529,777
|
I have developed an Azure ARM template to deploy an Ubuntu Linux machine that once provisioned a bash script will run to install a particular software. The software involves downloading some packages as well as pass an input parameter from the user in order to complete the configuration. The issue I am facing is that the script extension seems to work intermittently. I deployed it successfully once, and now it keeps failing all the time. Here is the error it returns after a few seconds that the custom script starts executing:
```
{
"code": "DeploymentFailed",
"message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.",
"details": [
{
"code": "Conflict",
"message": "{\r\n \"status\": \"Failed\",\r\n \"error\": {\r\n \"code\": \"ResourceDeploymentFailure\",\r\n \"message\": \"The resource operation completed with terminal provisioning state 'Failed'.\",\r\n \"details\": [\r\n {\r\n \"code\": \"VMExtensionProvisioningError\",\r\n \"message\": \"VM has reported a failure when processing extension 'metaport-onboard'. Error message: \\\"Enable failed: failed to execute command: command terminated with exit status=1\\n[stdout]\\nReading package lists...\\nBuilding dependency tree...\\nReading state information...\\nsoftware-properties-common is already the newest version (0.96.24.32.14).\\nsoftware-properties-common set to manually installed.\\nThe following packages were automatically installed and are no longer required:\\n grub-pc-bin linux-headers-4.15.0-121\\nUse 'sudo apt autoremove' to remove them.\\n0 upgraded, 0 newly installed, 0 to remove and 18 not upgraded.\\nReading package lists...\\nBuilding dependency tree...\\nReading state information...\\nSome packages could not be installed. This may mean that you have\\nrequested an impossible situation or if you are using the unstable\\ndistribution that some required packages have not yet been created\\nor been moved out of Incoming.\\nThe following information may help to resolve the situation:\\n\\nThe following packages have unmet dependencies:\\n python3-pip : Depends: python3-distutils but it is not installable\\n Recommends: build-essential but it is not installable\\n Recommends: python3-dev (>= 3.2) but it is not installable\\n Recommends: python3-setuptools but it is not installable\\n Recommends: python3-wheel but it is not installable\\n\\n[stderr]\\n+ sudo apt-get -qq -y update\\n+ sudo apt-get -q -y install software-properties-common\\n+ sudo apt-get -q -y install python3-pip\\nE: Unable to correct problems, you have held broken packages.\\nNo passwd entry for user 'mpadmin'\\n\\\"\\r\\n\\r\\nMore information on troubleshooting is available at https://aka.ms/VMExtensionCSELinuxTroubleshoot \"\r\n }\r\n ]\r\n }\r\n}"
}
]
}
```
Below is the portion of the template where I defined the extension
```
{
"type": "Microsoft.Compute/virtualMachines",
"name": "[variables('vmName')]",
"apiVersion": "2019-12-01",
"location": "[variables('location')]",
"dependsOn": [
"[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]",
"[resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworkName'))]",
"[resourceId('Microsoft.Network/natGateways', variables('natGatewayName'))]",
"[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[parameters('virtualMachineSize')]"
},
"osProfile": {
"computerName": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPasswordOrKey')]",
"linuxConfiguration": "[if(equals(parameters('authenticationType'), 'password'), json('null'), variables('linuxConfiguration'))]"
},
"storageProfile": {
"imageReference": {
"publisher": "[variables('imagePublisher')]",
"offer": "[variables('imageOffer')]",
"sku": "[variables('imageSKU')]",
"version": "[variables('imageVersion')]"
},
"osDisk": {
"name": "[concat(variables('vmName'), '_OSDisk')]",
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": {
"storageAccountType": "[variables('storageAccountType')]"
}
}
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
}
},
"resources": [
{
"name": "metaport-onboard",
"type": "extensions",
"apiVersion": "2019-03-01",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.Compute/virtualMachines/', variables('vmName'))]",
"[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]",
"[resourceId('Microsoft.Network/virtualNetworks', parameters('virtualNetworkName'))]",
"[resourceId('Microsoft.Network/natGateways', variables('natGatewayName'))]",
"[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]"
],
"properties": {
"publisher": "Microsoft.Azure.Extensions",
"type": "CustomScript",
"typeHandlerVersion": "2.1",
"autoUpgradeMinorVersion": true,
"settings": {
"fileUris": [
"https://raw.githubusercontent.com/willguibr/azure/main/Latest/MetaPort-Standalone-NATGW-v1.0/install_metaport.sh"
]
},
"protectedSettings": {
"commandToExecute": "[concat('sh install_metaport.sh ', parameters('metaTokenCode'))]"
}
}
}
]
}
]
}
```
The full template package is [here](https://github.com/willguibr/azure/tree/main/Latest/MetaPort-Standalone-NATGW-v1.0).
Anyone have any idea on how to prevent this issue or implement any correction that may be necessary?
|
2020/10/25
|
[
"https://Stackoverflow.com/questions/64529777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14497508/"
] |
I ended up using this code
```
import * as React from "react";
import Form from "@rjsf/material-ui";
import {FormProps, ObjectFieldTemplateProps} from "@rjsf/core";
import Button from "@material-ui/core/Button/Button";
import styles from './LSForm.module.scss';
import Grid from "@material-ui/core/Grid/Grid";
interface Props extends FormProps<any> {
submitButtonText?: string
showSuccessMessage?: boolean
hide?: boolean
columns?: number
spacing?: 0 | 6 | 4 | 3 | 1 | 2 | 5 | 7 | 8 | 9 | 10 | undefined
}
const LSForm: React.FC<Props> = (props) => {
const getColumns = () => {
if (props.columns === 1) {
return 12;
}
if (props.columns === 2) {
return 6;
}
if (props.columns === 3) {
return 4;
}
if (props.columns === 4) {
return 3;
}
// Default one colum
return 12;
};
const getSpacing = (): 0 | 6 | 4 | 3 | 1 | 2 | 5 | 7 | 8 | 9 | 10 | undefined => {
let spacing: 0 | 6 | 4 | 3 | 1 | 2 | 5 | 7 | 8 | 9 | 10 | undefined = 0;
if (props.spacing != null) {
spacing = props.spacing;
}
return spacing;
};
const ObjectFieldTemplate = (props: ObjectFieldTemplateProps) => {
return (
<div>
<Grid container spacing={getSpacing()}>
{props.title}
{props.description}
{props.properties.map(element => {
return <Grid item xs={getColumns()}><div className="property-wrapper">{element.content}</div></Grid>
})}
</Grid>
</div>
);
};
return (
<>
{ !props.hide &&
<Form {...props} ObjectFieldTemplate={ObjectFieldTemplate}>
{ props.children &&
<div className={styles.actionBar}>
{props.children}
</div>
}
{ !props.children &&
<div className={styles.actionBar}>
<Button type={"submit"} disabled={props.disabled} variant="contained" color="primary">{ props.submitButtonText ? props.submitButtonText : "Speichern"}</Button>
</div>
}
</Form>
}
</>
);
};
export default LSForm;
```
User it as follow:
...
```
return (
<>
<LSForm schema={schema}
hide={hideForm}
spacing={3}
columns={3}
uiSchema={uiSchema}
onSubmit={(data) => onSubmit(data)}>
<Button type={"submit"} variant="contained" color="primary">Login</Button>
<Button variant="contained" color="primary">Forgot Password</Button>
</LSForm>
</>
);
```
...
|
I found a solution which is not my prefered one:
```
const ObjectFieldTemplate = (props: ObjectFieldTemplateProps) => {
return (
<div>
{props.title}
{props.description}
{props.properties.map(element => {
return <div className="property-wrapper">{element.content}</div>
})}
</div>
);
}
<Form ObjectFieldTemplate={ObjectFieldTemplate}>
```
Invetigating several hours of googling i found another solution:
```
const uiSchema = {
"email": {
"ui:widget": "email",
'ui:column': 'xs6'
},
"password": {
"ui:widget": "password",
'ui:column': 'xs6'
}
};
```
Problem here: ui:coumn: xs6 only works with bootstrap theme. Cause i am using material ui, this approach cannot be used or i miss something to get this running.
For more or better solutions i would really appriciate
|
68,835,056
|
I have a python script that I compiled to an EXE, one of the purposes of it is to extract a 7z file and save it to a destination.
If I'm running it from PyCharm everything works great, this is the code:
```
def delete_old_version_rename_new(self):
winutils.delete(self.old_version)
print("Extracting...")
Archive(f"{self.new_version}_0.7z").extractall(f"{self.destination}")
print("Finished")
os.rename(self.new_version, self.new_name)
```
I used pyinstaller to compile the program and used to command `pyinstaller --onefile --paths {path to site packages} main.py`
Thanks!
|
2021/08/18
|
[
"https://Stackoverflow.com/questions/68835056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14895566/"
] |
Single-file executables self-extract to a temporary folder and run from there, so any relative paths will be relative to that folder *not* the location of executable you originally ran.
My solution is a code snippet such as this:
```
if getattr(sys, 'frozen', False):
app_path = os.path.dirname(sys.executable)
else:
app_path = os.path.dirname(os.path.abspath(__file__))
```
which gives you the location of the executable in the single-file executable case or the location of the script in the case of running from source.
See the PyInstaller documentation [here](https://pyinstaller.readthedocs.io/en/stable/runtime-information.html).
|
Eventually i just used a 7z command line i took from <https://superuser.com/questions/95902/7-zip-and-unzipping-from-command-line>
and used os.system() to initialize it.
Since my program is command line based it worked even better since its providing a status on the extraction process.
Only downside is i have to move the 7z.exe to the directory of my program.
|
49,677,269
|
I'm trying to create an email template in Django which uses [Materialize.css](http://materializecss.com/). Here is the template code:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Activation</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
/* Use the same logo size and positioning as in the eBay email to families */
img.logo {
width: 80px;
margin: 30px 20px;
}
body {
background-color: #f3f3f3;
}
/* Align the column with the logo */
.col.lucy-col {
padding-left: 20px;
padding-right: 20px;
}
.card-title h4 {
margin-top: 0px;
}
/* Use Materialize's default light blue color for card-action links (instead of an orange one) */
.card-action.lucy-card-action a {
color: #039be5 !important;
}
/* Make the table more compact vertically */
td {
padding-top: 10px;
padding-bottom: 10px;
}
</style>
</head>
<body>
<img class="logo" src="https://s3-us-west-1.amazonaws.com/lucy-prod/images/logo.png" alt="LUCY"/>
<!-- Materialize table within a Materialize card (cf. http://materializecss.com/cards.html and http://materializecss.com/table.html) -->
<div class="row">
<div class="col lucy-col s12 m6">
<div class="card">
<div class="card-content">
<span class="card-title"><h4>New Activation</h4></span>
<table class="striped">
<tbody>
<tr>
<td><b>Name</b></td>
<td>{{ first_name }} {{ last_name }}</td>
</tr>
<tr>
<td><b>Birth parent</b></td>
<td>{{ birth_parent }}</td>
</tr>
<tr>
<td><b>Email</b></td>
<td><a href="mailto:{{email}}">{{ email }}</a></td>
</tr>
<tr>
<td><b>Phone</b></td>
<td>{{ phone }}</td>
</tr>
<tr>
<td><b>Address</b></td>
<td>{{ address|linebreaksbr }}</td>
</tr>
<tr>
<td><b>Company</b></td>
<td>{{ company }}</td>
</tr>
<tr>
<td><b>Company email</b></td>
<td><a href="mailto:{{ company_email }}">{{ company_email }}</a></td>
</tr>
<tr>
<td><b>Stage</b></td>
<td>{{ stage }}</td>
</tr>
<tr>
<td><b>Baby arrived?</b></td>
<td>{{ date }}</td>
</tr>
<tr>
<td><b>First child?</b></td>
<td>{{ is_first_child }}</td>
</tr>
<tr>
<td><b>Tell us more</b></td>
<td>{{ tell_us_more|linebreaksbr }}</td>
</tr>
</tbody>
</table>
</div>
<div class="card-action lucy-card-action">
<a href={{ url }}>Case Management</a>
</div>
</div>
</div>
</div>
</body>
</html>
```
When I hook it up to a view (passing in some dummy context), here is how it looks:
[](https://i.stack.imgur.com/TE033.png)
I'm trying to get this into an email using [`premailer`](https://pypi.python.org/pypi/premailer/3.1.1). Here is the code snippet where I'm sending the email:
```
from premailer import transform
from django.mail import EmailMultiAlternatives
...
message_html = transform(render_to_string('emails/activate_to_delivery.html', context))
email = EmailMultiAlternatives(
subject='A new family has activated!',
body=message_text,
from_email=settings.DEFAULT_FROM_EMAIL,
to=self._get_recipients(family),
reply_to=[family.point_of_contact_email])
email.attach_alternative(message_html, "text/html")
email.send()
```
However, when I send an email (through a `TestCase`), I get a bunch of `WARNING`s and `ERROR`s (of which I've included a subset below):
```
(venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py test activation.tests.ActivationEmailTest
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
WARNING Property: Unknown Property name. [18:3: word-wrap]
WARNING Property: Unknown Property name. [6:28081: -ms-text-size-adjust]
WARNING Property: Unknown Property name. [6:28107: -webkit-text-size-adjust]
WARNING Property: Unknown Property name. [6:28301: -webkit-box-sizing]
WARNING Property: Unknown Property name. [6:28463: -webkit-text-decoration-skip]
WARNING Property: Unknown Property name. [6:28557: -webkit-text-decoration]
WARNING Property: Unknown Property name. [6:28598: -moz-text-decoration]
ERROR Property: Invalid value for "CSS Level 2.1" property: underline dotted [6:28636: text-decoration]
WARNING Property: Unknown Property name. [6:29334: -webkit-appearance]
ERROR Property: Invalid value for "CSS3 Basic User Interface Module" property: 1px dotted ButtonText [6:29628: outline]
WARNING Property: Unknown Property name. [6:29704: -webkit-box-sizing]
WARNING Property: Unknown Property name. [6:29938: -webkit-box-sizing]
WARNING Property: Unknown Property name. [6:30114: -webkit-appearance]
WARNING Property: Unknown Property name. [6:30252: -webkit-appearance]
WARNING Property: Unknown Property name. [6:30305: -webkit-appearance]
WARNING Property: Unknown Property name. [6:30474: -webkit-box-sizing]
WARNING Property: Unknown Property name. [6:30545: -webkit-box-sizing]
ERROR Property: Invalid value for "CSS3 Basic User Interface Module" property: inherit [6:30572: box-sizing]
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name.
WARNING Property: Unknown Property name. [1:18: -ms-text-size-adjust]
WARNING Property: Unknown Property name. [1:44: -webkit-text-size-adjust]
WARNING Property: Unknown Property name. [1:30: -webkit-text-decoration-skip]
WARNING Property: Unknown Property name. [1:1: -webkit-box-sizing]
WARNING Property: Unknown Property name. [1:36: -webkit-tap-highlight-color]
ERROR Property: Invalid value for "CSS Level 2.1" property: 2.28rem [1:1: font-size]
ERROR Property: Invalid value for "CSS Level 2.1" property: 1.52rem 0 0.912rem 0 [1:36: margin]
WARNING Property: Unknown Property name. [1:1: -webkit-box-shadow]
ERROR Property: Invalid value for "CSS Level 2.1" property: 0.5rem 0 1rem 0 [1:19: margin]
WARNING Property: Unknown Property name. [1:64: -webkit-transition]
WARNING Property: Unknown Property name. [1:108: transition]
WARNING Property: Unknown Property name. [1:12: -webkit-box-sizing]
ERROR Property: Invalid value for "CSS Level 2.1" property: 0 0.75rem [1:64: padding]
.
----------------------------------------------------------------------
Ran 1 test in 7.051s
OK
Destroying test database for alias 'default'...
```
If I check my inbox, the email looks like this:
[](https://i.stack.imgur.com/9lUOR.png)
Is there any way to fix this - that is, to use Materialize in emails? (In my case, it only has to work for GMail).
|
2018/04/05
|
[
"https://Stackoverflow.com/questions/49677269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995862/"
] |
E-mails do not support all CSS functions, I recommend you create your own CSS with alternative functions to achieve the same result.
Here's a handy website on which you can check what CSS you can and can't use for certain e-mail clients.
<https://www.campaignmonitor.com/css/>
|
Just to provide you an option, look into MJML.
It can be used programmatically with Node.
It can create responsive and emails with all the common email clients via what is essentially a combination of HTML and CSS with baked in fixes for displaying through the various email clients.
<https://mjml.io/>
"MJML is a markup language designed to reduce the pain of coding a responsive email. Its semantic syntax makes it easy and straightforward and its rich standard components library speeds up your development time and lightens your email codebase. MJML’s open-source engine generates high quality responsive HTML compliant with best practices."
Example:
[](https://i.stack.imgur.com/FFZql.png)
|
19,601,797
|
i will answer any questions i can
Basically I have a list of 70 words that I am looking for in over 500 files, and I need to replace them with new words and numbers.
ie... find "hello" and replace with "hello 233.4" but 70 words/numbers and 500+ files.
I found an informative post here, but I have been reading about sys.argv, re's, searches, replaces, etc.. etc.. etc.. I can not understand this bit of code. I have been "calling" (i think) it from "cmd" window on windows 7 with scriptname.py "-i " and "-o"...
if someone could put example input search list path "c:/input/file/path/searchlist.txt" and the example path for the file to be searched "c:/search/this/file/searchme.txt" in their correct positions please! (I will try and get it to repeat through every file in a folder on my own and highlight or bold the replacements on my own.)
I have tried many combinations... I could go over every modification ive made, and could type for days/pages/days/pages... each day/page getting dumber and dumber every time!
Thanks... OR IF YOU KNOW OF A DIFFERENT WAY, PLEASE SUGGEST ADVISE.
here is the link to the original post:
[Use Python to search one .txt file for a list of words or phrases (and show the context)](https://stackoverflow.com/questions/3007889/use-python-to-search-one-txt-file-for-a-list-of-words-or-phrases-and-show-the)
here is the code from the original post:
```
import re
import sys
def main():
if len(sys.argv) != 3:
print("Usage: %s fileofstufftofind filetofinditin" % sys.argv[0])
sys.exit(1)
with open(sys.argv[1]) as f:
patterns = [r'\b%s\b' % re.escape(s.strip()) for s in f]
there = re.compile('|'.join(patterns))
with open(sys.argv[2]) as f:
for i, s in enumerate(f):
if there.search(s):
print("Line %s: %r" % (i, s))
main()
```
|
2013/10/26
|
[
"https://Stackoverflow.com/questions/19601797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2779846/"
] |
The code that you posted above is probably to complex for what you need for your assignment. Perhaps something more simple like the following is easier to understand:
```
# example variables
word_mapping = [['horse', 'donkey'], ['left', 'right']]
filename = 'C:/search/this/file/searchme.txt'
# load the text from the file with 'r' for "reading"
file = open(filename, 'r')
text = file.read()
file.close()
# replace words in the text
for find_word, replacement in word_mapping:
text = text.replace(find_word, replacement)
# save the modified text to the file, 'w' for "writing"
file = open(filename, 'w')
file.write(text)
file.close()
```
---
For loading your list of words to replace, you could simply do something like:
```
words_path = 'C:/input/file/path/searchlist.txt'
with open(words_path) as f:
word_mapping = [line.split() for line in f]
```
`str.split()` splits a string on whitespace (spaces, tabs) by default, but you can split on other characters or even "words". If you have for example a comma separated file you use `line.split(',')` and it splits on comma's.
---
As an explanation to that code you posted above.. There are a couple of separate things happening, so lets break it down in a couple of pieces.
```
if len(sys.argv) != 3:
print("Usage: %s fileofstufftofind filetofinditin" % sys.argv[0])
sys.exit(1)
```
This particular script receives the paths to the wordslist and the target file as command line arguments, so you can run this script as `python script_name.py wordslist_file target_file`. In other words you don't hardcode the file paths in the script, but let the user provide them at run time.
This first part of the code checks how many command line parameters have been passed to the script, by checking the length of `sys.argv`, which is a list containing command line parameters as strings. When the number of command line parameter is not equal to 3, an error message is printed. The first (or zeroth) argument is the filename of the script, so that's why `sys.argv[0]` is printed as part of the error message.
```
with open(sys.argv[1]) as f:
patterns = [r'\b%s\b' % re.escape(s.strip()) for s in f]
there = re.compile('|'.join(patterns))
```
This opens a file with words (with filename equal to `sys.argv[1]`) and compiles regular expression objects for them. Regular expressions give you more control over what words are matched, but it has its own "mini-language" which can be quite confusing if you don't have experience with it. Note that this script only finds words and doesn't replace them, so the file with words it uses contains only one "word" per line.
```
with open(sys.argv[2]) as f:
for i, s in enumerate(f):
if there.search(s):
print("Line %s: %r" % (i, s))
```
This opens the target file (filename in the second command line parameter `sys.argv[2]` and loops over the lines in that file. If a line contains a word from the wordslist the whole line is printed.
|
Maybe can try this...
[Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-with-python)
Put all 500 files in the same directory and process from there.
|
48,600,481
|
I'm working with the following string:
```
'"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"'
```
and I have to use `re.sub()` in python to replace only the double quotes (`"`) that are enclosing the numbers, in order to parse it later in JSON. I've tried with some regular expressions, but without success. Here is my best attempt:
```
exp = re.compile(r': (")\D+\.*\D*(")', re.MULTILINE)
response = re.sub(exp, "", string)
```
I've searched a lot for a similar problem, but have not found another similar question.
### EDIT:
Finally I've used (thanks to [S. Kablar](https://stackoverflow.com/users/6101071/s-kablar)):
```
fomatted = re.sub(r'"(-*\d+(?:\.\d+)?)"', r"\1", string)
parsed = json.loads(formatted)
```
The problem is that [this endpoint](https://api.coinmarketcap.com/v1/ticker/) returns a bad formatted string as JSON.
Other users [answered](https://stackoverflow.com/a/48600555/9167585) "Parse the string first with json, and later convert numbers to float" with a for loop and, I think, is a very inneficient way to do it, also, you will be forced to select between int or float type for your response. To get out of doubt, I've wrote [this gist](https://gist.github.com/mondeja/a8215d34ee1c0c850d7b3f64ab6b2260) where I show you the comparations between the different approachs with benchmarking, and for now I'm going to trust in regex in this case.
Thanks everyone for your help
|
2018/02/03
|
[
"https://Stackoverflow.com/questions/48600481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9167585/"
] |
**Regex**: [`"(-?\d+(?:[\.,]\d+)?)"`](https://regex101.com/r/ySz6v5/3) **Substitution**: `\1`
Details:
* `()` Capturing group
* `(?:)` Non capturing group
* `\d` Matches a digit (equal to `[0-9]`)
* `+` Matches between one and unlimited times
* `?` Matches between zero and one times
* `\1` Group 1.
**Python code**:
```
def remove_quotes(text):
return re.sub(r"\"(-?\d+(?:[\.,]\d+)?)\"", r'\1', text)
remove_quotes('"percent_change_7d": "-23.43"') >> "percent_change_7d": -23.43
```
|
Parse the string first with json, and later convert numbers to floats:
```
string = '{"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"}'
data = json.loads(string)
response = {}
for key, value in data.items():
try:
value = int(value) if value.strip().isdigit() else float(value)
except ValueError:
pass
response[key] = value
```
|
48,600,481
|
I'm working with the following string:
```
'"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"'
```
and I have to use `re.sub()` in python to replace only the double quotes (`"`) that are enclosing the numbers, in order to parse it later in JSON. I've tried with some regular expressions, but without success. Here is my best attempt:
```
exp = re.compile(r': (")\D+\.*\D*(")', re.MULTILINE)
response = re.sub(exp, "", string)
```
I've searched a lot for a similar problem, but have not found another similar question.
### EDIT:
Finally I've used (thanks to [S. Kablar](https://stackoverflow.com/users/6101071/s-kablar)):
```
fomatted = re.sub(r'"(-*\d+(?:\.\d+)?)"', r"\1", string)
parsed = json.loads(formatted)
```
The problem is that [this endpoint](https://api.coinmarketcap.com/v1/ticker/) returns a bad formatted string as JSON.
Other users [answered](https://stackoverflow.com/a/48600555/9167585) "Parse the string first with json, and later convert numbers to float" with a for loop and, I think, is a very inneficient way to do it, also, you will be forced to select between int or float type for your response. To get out of doubt, I've wrote [this gist](https://gist.github.com/mondeja/a8215d34ee1c0c850d7b3f64ab6b2260) where I show you the comparations between the different approachs with benchmarking, and for now I'm going to trust in regex in this case.
Thanks everyone for your help
|
2018/02/03
|
[
"https://Stackoverflow.com/questions/48600481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9167585/"
] |
Parse the string first with json, and later convert numbers to floats:
```
string = '{"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"}'
data = json.loads(string)
response = {}
for key, value in data.items():
try:
value = int(value) if value.strip().isdigit() else float(value)
except ValueError:
pass
response[key] = value
```
|
You came close. You want to **save** the numbers, and the colon, so you need to put them in parentheses, not the rest. Also, numbers are `\d`, not `\D` (that would be *not*-numbers).
So:
```
exp = re.compile(r'(: *)"(\d+\.?\d*)"', re.MULTILINE)
response = re.sub(exp, "\\1\\2", string)
\d+\.?\d* means "a number (or more), a point (or not), any numbers"
```
Border cases
============
The above doesn't cover ".125", which is **no** numbers, **one** point.
And if you changed to "\d\*.?\d\*", that would match ".", since it is \*\*any numbers", one point, any numbers".
I think the only practicable way is
```
(\d+\.?\d*|\.\d+)
```
with | meaning "or": so, either a number optionally followed by one point and any digits (this matches "17."), **or** a point followed by at least one digit. Unfortunately, "\d+.?\d+" does not match "5".
Or you specify all three cases:
```
(\d+|\d+\.?\d+|\.\d+)
```
First integers (\d+), then floating points with or without decimals, then decimal parts alone without leading zeroes.
|
48,600,481
|
I'm working with the following string:
```
'"name": "Gnosis", \n "symbol": "GNO", \n "rank": "99", \n "price_usd": "175.029", \n "price_btc": "0.0186887", \n "24h_volume_usd": "753877.0"'
```
and I have to use `re.sub()` in python to replace only the double quotes (`"`) that are enclosing the numbers, in order to parse it later in JSON. I've tried with some regular expressions, but without success. Here is my best attempt:
```
exp = re.compile(r': (")\D+\.*\D*(")', re.MULTILINE)
response = re.sub(exp, "", string)
```
I've searched a lot for a similar problem, but have not found another similar question.
### EDIT:
Finally I've used (thanks to [S. Kablar](https://stackoverflow.com/users/6101071/s-kablar)):
```
fomatted = re.sub(r'"(-*\d+(?:\.\d+)?)"', r"\1", string)
parsed = json.loads(formatted)
```
The problem is that [this endpoint](https://api.coinmarketcap.com/v1/ticker/) returns a bad formatted string as JSON.
Other users [answered](https://stackoverflow.com/a/48600555/9167585) "Parse the string first with json, and later convert numbers to float" with a for loop and, I think, is a very inneficient way to do it, also, you will be forced to select between int or float type for your response. To get out of doubt, I've wrote [this gist](https://gist.github.com/mondeja/a8215d34ee1c0c850d7b3f64ab6b2260) where I show you the comparations between the different approachs with benchmarking, and for now I'm going to trust in regex in this case.
Thanks everyone for your help
|
2018/02/03
|
[
"https://Stackoverflow.com/questions/48600481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9167585/"
] |
**Regex**: [`"(-?\d+(?:[\.,]\d+)?)"`](https://regex101.com/r/ySz6v5/3) **Substitution**: `\1`
Details:
* `()` Capturing group
* `(?:)` Non capturing group
* `\d` Matches a digit (equal to `[0-9]`)
* `+` Matches between one and unlimited times
* `?` Matches between zero and one times
* `\1` Group 1.
**Python code**:
```
def remove_quotes(text):
return re.sub(r"\"(-?\d+(?:[\.,]\d+)?)\"", r'\1', text)
remove_quotes('"percent_change_7d": "-23.43"') >> "percent_change_7d": -23.43
```
|
You came close. You want to **save** the numbers, and the colon, so you need to put them in parentheses, not the rest. Also, numbers are `\d`, not `\D` (that would be *not*-numbers).
So:
```
exp = re.compile(r'(: *)"(\d+\.?\d*)"', re.MULTILINE)
response = re.sub(exp, "\\1\\2", string)
\d+\.?\d* means "a number (or more), a point (or not), any numbers"
```
Border cases
============
The above doesn't cover ".125", which is **no** numbers, **one** point.
And if you changed to "\d\*.?\d\*", that would match ".", since it is \*\*any numbers", one point, any numbers".
I think the only practicable way is
```
(\d+\.?\d*|\.\d+)
```
with | meaning "or": so, either a number optionally followed by one point and any digits (this matches "17."), **or** a point followed by at least one digit. Unfortunately, "\d+.?\d+" does not match "5".
Or you specify all three cases:
```
(\d+|\d+\.?\d+|\.\d+)
```
First integers (\d+), then floating points with or without decimals, then decimal parts alone without leading zeroes.
|
36,839,650
|
I want to execute one python script in Jupyter, but I don't want to use the web browser (IPython Interactive terminal), I want to run a single command in the Linux terminal to load & run the python script, so that I can get the output from Jupyter.
I tried to run `jupyter notebook %run <my_script.py>`, but it seems jupyter can't recognize `%run` variable.
Is it possible to do that?
|
2016/04/25
|
[
"https://Stackoverflow.com/questions/36839650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6204018/"
] |
You can use the `jupyter console -i` command to run an interactive jupyter session in your terminal. From there you can run `import <my_script.py>`. Do note that this is not the intended use case of either jupyter or the notebook environment. You should run scripts using your normal python interpreter instead.
|
You can run this command to run an interactive jupyter session in your terminal.
>
> jupyter notebook
>
>
>
|
36,839,650
|
I want to execute one python script in Jupyter, but I don't want to use the web browser (IPython Interactive terminal), I want to run a single command in the Linux terminal to load & run the python script, so that I can get the output from Jupyter.
I tried to run `jupyter notebook %run <my_script.py>`, but it seems jupyter can't recognize `%run` variable.
Is it possible to do that?
|
2016/04/25
|
[
"https://Stackoverflow.com/questions/36839650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6204018/"
] |
You can use the `jupyter console -i` command to run an interactive jupyter session in your terminal. From there you can run `import <my_script.py>`. Do note that this is not the intended use case of either jupyter or the notebook environment. You should run scripts using your normal python interpreter instead.
|
The `jupyter_client` package has a `jupyter run` command since [v5.0](https://github.com/jupyter/jupyter_client/blob/7cfd766b067a2972f9e33ee1d687fa2bc72bb518/setup.py#L93), so you can just do:
```
jupyter run my_script.py
```
|
36,839,650
|
I want to execute one python script in Jupyter, but I don't want to use the web browser (IPython Interactive terminal), I want to run a single command in the Linux terminal to load & run the python script, so that I can get the output from Jupyter.
I tried to run `jupyter notebook %run <my_script.py>`, but it seems jupyter can't recognize `%run` variable.
Is it possible to do that?
|
2016/04/25
|
[
"https://Stackoverflow.com/questions/36839650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6204018/"
] |
The `jupyter_client` package has a `jupyter run` command since [v5.0](https://github.com/jupyter/jupyter_client/blob/7cfd766b067a2972f9e33ee1d687fa2bc72bb518/setup.py#L93), so you can just do:
```
jupyter run my_script.py
```
|
You can run this command to run an interactive jupyter session in your terminal.
>
> jupyter notebook
>
>
>
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
1- Stop other applications that are using port 80.
2- run application with port 80 :
```
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
```
|
You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on `uWSGI`.
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
So it's throwing up that error message because you have `apache2` running on port 80.
If this is for development, I would just leave it as it is on port 5000.
If it's for production either:
**Not Recommended**
* Stop `apache2` first;
Not recommended as it states in the documentation:
>
> You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)
>
>
>
**Recommended**
* Proxy `HTTP` traffic through `apache2` to Flask.
This way, `apache2` can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.
[Here's a link](http://flask.pocoo.org/docs/deploying/mod_wsgi/#configuring-apache) to the official documentation about setting up Flask with Apache + mod\_wsgi.
**Edit 1 - Clarification for @Djack**
>
> Proxy HTTP traffic to Flask through apache2
>
>
>
When a request comes to the server on port 80 (`HTTP`) or port 443 (`HTTPS`) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.
>
> reverse proxy for dynamic content
>
>
>
There are a few advantages to configuring your web server like the above;
* SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
* Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
* Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
* +more. This is bordering on scope for this question. If you want more info do some research into this area.
|
you can easily disable any process running on port 80 and then run this command
```
flask run --host 0.0.0.0 --port 80
```
or if u prefer running it within the .py file
```
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
```
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
If you use the following to change the port or host:
```
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
```
use the following code to start the server (my main entrance for flask is app.py):
```
python app.py
```
instead of using:
```
flask run
```
|
On my scenario the following steps worked like a charm:
* Installing the package:
```
pip install --upgrade pip
pip install python-dotenv
```
* Creating a hidden file in my app directory "flaskr/.flaskenv"
* Adding the following content:
```
FLASK_APP=flaskr
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=8000
```
* Finally, run the flask command one more time:
```
flask run
```
* The version which I am working on is:
```
pip freeze |grep -i flask
Flask==1.1.1
```
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
So it's throwing up that error message because you have `apache2` running on port 80.
If this is for development, I would just leave it as it is on port 5000.
If it's for production either:
**Not Recommended**
* Stop `apache2` first;
Not recommended as it states in the documentation:
>
> You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)
>
>
>
**Recommended**
* Proxy `HTTP` traffic through `apache2` to Flask.
This way, `apache2` can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.
[Here's a link](http://flask.pocoo.org/docs/deploying/mod_wsgi/#configuring-apache) to the official documentation about setting up Flask with Apache + mod\_wsgi.
**Edit 1 - Clarification for @Djack**
>
> Proxy HTTP traffic to Flask through apache2
>
>
>
When a request comes to the server on port 80 (`HTTP`) or port 443 (`HTTPS`) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.
>
> reverse proxy for dynamic content
>
>
>
There are a few advantages to configuring your web server like the above;
* SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
* Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
* Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
* +more. This is bordering on scope for this question. If you want more info do some research into this area.
|
I solved 2 times and solved it with 2 solution
The first solution, follow these steps:
1 open cmd
2 run `ipconfig` at cmd
3 copy IPv4 Address from cmd
4 Use your IPv4 as the local host in the next:
```
app.run(debug=True, port=5000, host='localhost')
```
at replace 'localhost' with your IPv4 Address
5 for your front end, do the same of step 4 like:
at 'http://localhost:5000/auth' replace 'localhost' with your IPv4 Address
>
> Note: use the same port for {the frontend, and the backend}
>
>
>
6 run your both projects together(the backend and the frontend)
---
The second time, the last solution didn't work, and I solved it with this:
* at the mobile side I used that URL: "http://10.0.2.2:8000" and at the Flask side used
`app.run(debug=True, port=8000, host='localhost')`
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
For externally visible server, where you don't use apache or other web server you just type
```
flask run --host=0.0.0.0 --port=80
```
|
I had to set `FLASK_RUN_PORT` in my environment to the specified port number. Next time you start your app, Flask will load that environment variable with the port number you selected.
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
So it's throwing up that error message because you have `apache2` running on port 80.
If this is for development, I would just leave it as it is on port 5000.
If it's for production either:
**Not Recommended**
* Stop `apache2` first;
Not recommended as it states in the documentation:
>
> You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)
>
>
>
**Recommended**
* Proxy `HTTP` traffic through `apache2` to Flask.
This way, `apache2` can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.
[Here's a link](http://flask.pocoo.org/docs/deploying/mod_wsgi/#configuring-apache) to the official documentation about setting up Flask with Apache + mod\_wsgi.
**Edit 1 - Clarification for @Djack**
>
> Proxy HTTP traffic to Flask through apache2
>
>
>
When a request comes to the server on port 80 (`HTTP`) or port 443 (`HTTPS`) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.
>
> reverse proxy for dynamic content
>
>
>
There are a few advantages to configuring your web server like the above;
* SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
* Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
* Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
* +more. This is bordering on scope for this question. If you want more info do some research into this area.
|
Your issue is, that you have an apache webserver already running that is already using port 80. So, you can either:
1. Kill apache: You should probably do this via `/etc/init.d/apache2 stop`, rather than simply killing them.
2. Deploy your flask app in your apache process, as [flask in apache](http://flask.pocoo.org/docs/deploying/mod_wsgi/#configuring-apache) describes.
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
A convinient way is using the package `python-dotenv`:
It reads out a `.flaskenv` file where you can store environment variables for flask.
* `pip install python-dotenv`
* create a file `.flaskenv` in the root directory of your app
Inside the file you specify:
```
FLASK_APP=application.py
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=80
```
After that you just have to run your app with `flask run` and can access your app at that port.
Please note that `FLASK_RUN_HOST` defaults to `127.0.0.1` and `FLASK_RUN_PORT` defaults to `5000`.
|
I had to set `FLASK_RUN_PORT` in my environment to the specified port number. Next time you start your app, Flask will load that environment variable with the port number you selected.
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
I had to set `FLASK_RUN_PORT` in my environment to the specified port number. Next time you start your app, Flask will load that environment variable with the port number you selected.
|
On my scenario the following steps worked like a charm:
* Installing the package:
```
pip install --upgrade pip
pip install python-dotenv
```
* Creating a hidden file in my app directory "flaskr/.flaskenv"
* Adding the following content:
```
FLASK_APP=flaskr
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=8000
```
* Finally, run the flask command one more time:
```
flask run
```
* The version which I am working on is:
```
pip freeze |grep -i flask
Flask==1.1.1
```
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
set the port with `app.run(port=80,debug=True)`
you should set debug to true when on dev
|
I solved 2 times and solved it with 2 solution
The first solution, follow these steps:
1 open cmd
2 run `ipconfig` at cmd
3 copy IPv4 Address from cmd
4 Use your IPv4 as the local host in the next:
```
app.run(debug=True, port=5000, host='localhost')
```
at replace 'localhost' with your IPv4 Address
5 for your front end, do the same of step 4 like:
at 'http://localhost:5000/auth' replace 'localhost' with your IPv4 Address
>
> Note: use the same port for {the frontend, and the backend}
>
>
>
6 run your both projects together(the backend and the frontend)
---
The second time, the last solution didn't work, and I solved it with this:
* at the mobile side I used that URL: "http://10.0.2.2:8000" and at the Flask side used
`app.run(debug=True, port=8000, host='localhost')`
|
20,212,894
|
I have a Flask server running through port 5000, and it's fine. I can access it at <http://example.com:5000>
But is it possible to simply access it at <http://example.com>? I'm assuming that means I have to change the port from 5000 to 80. But when I try that on Flask, I get this error message when I run it.
```
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
```
Running `lsof -i :80` returns
```
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
```
Do I need to kill these processes first? Is that safe? Or is there another way to keep Flask running on port 5000 but have the main website domain redirect somehow?
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20212894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3024025/"
] |
This is the only solution that worked for me on Ubuntu-18.
Inside the file `app.py` , use:
```
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
```
The code above will give the same permission error unless `sudo` is used to run it:
```
sudo python3 app.py
```
|
You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on `uWSGI`.
|
70,241,576
|
This is a very weried situation, in vscode, I edited my code in the root directory and saved it as test\_distribution.py. After I run this file in vscode terminal. Everytime I edit and save this file, it gets run automatically.
So I moved this file to the subfolder of this project, but I found out it still get run when I edit and save this file. So I changed the file name to distribution\_test.py and add logging and save this file again. It turns out it will still run when I edit and save this file.
How should I figure out why this is happening? What kind of info should I log out in order to figure out this issue?
As you can see the 1300000\_bake.xlsx is generated by this python file, I even moved this python file to a different folder and changed the name of it as I stated above, I am very curious how to find out which program is running this
Pics as follow:
```
for store_id in store_ids:
df = pd.DataFrame(columns=columns)
for query_date in date_range:
logging.info(f"提高计算速度, 使用常规kind_code_cate1类型")
kind_cate1s = normal_cate1
for kind_cate1 in kind_cate1s:
for setting in [dev_setting, prod_setting]:
eng = conn(setting)
delivery_cycle = pd.read_sql(
f"select delivery_cycle from dim_mty_goods where kind_code_cate1={kind_cate1} and can_be_ordered=1",
eng,
)
delivery_cycle = np.unique(delivery_cycle["delivery_cycle"].values)
delivery_cycle = min(delivery_cycle) # 只有冷藏存在多个值, 1, 2, 3 取1, 其他均为单一值
start_time = time.time()
logging.info(
f"开始计算, store_id: {store_id}, date: {query_date}, kind_cate1: {kind_cate1}, dev 环境: {setting == dev_setting}"
)
logging.info(
f"bash command: {create_bash(query_date, kind_cate1, store_id, setting == dev_setting)}"
)
status = os.system(
create_bash(
query_date=query_date,
kind_cate1=kind_cate1,
store_id=store_id,
dev_setting=(setting == dev_setting),
)
)
elapsed = time.time() - start_time
if status != 0:
logging.info(
f'计算出现问题, store_id: {store_id}, date: {query_date}, kind code cate1: {kind_cate1}, 环境: {setting["db"]}'
)
break
logging.info(f"返回耗时: {elapsed}")
if elapsed < 60:
calculate_time = elapsed
elif setting == dev_setting:
calculate_time = pd.DataFrame()
while calculate_time.empty:
calculate_time = pd.read_sql(
f'select cal_time from calculate_time where dt = "{str(query_date)}" and store_id={store_id} and kind_code_cate1={kind_cate1}',
eng,
)
# 等待写库
time.sleep(0.1)
logging.warning(
f"未查询到计算时间, store_id: {store_id}, date: {query_date}, kind_code_cate1: {kind_cate1}"
)
calculate_time = min(calculate_time["cal_time"].values)
else:
calculate_time = elapsed
logging.info(f"计算时间, {calculate_time}")
arrival_sale_day = [
"sale_predict_qtty_t1",
"sale_predict_qtty_t2",
"sale_predict_qtty_t3",
][delivery_cycle]
dev_prod = int(setting["db"] == "marsboard_dev")
df_temp = pd.DataFrame()
while df_temp.empty:
df_temp = pd.read_sql(
f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
eng,
)
logging.warning(f"未查询到order list 里的信息")
if pd.read_sql(
f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
prod_eng,
).empty:
logging.info(f"生产环境本品类亦无数据, {kind_cate1}")
break
time.sleep(0.1)
df_temp["dev_prod"] = dev_prod
df_temp["calculate_time"] = float(calculate_time)
df_temp.columns = columns
df = pd.concat([df_temp, df], axis=0, ignore_index=True)
print(df)
df.to_excel(f"{store_id}_bake.xlsx", index=False)
```
[](https://i.stack.imgur.com/K6vDs.png)
[](https://i.stack.imgur.com/0lHOt.png)
[](https://i.stack.imgur.com/xa4oJ.png)
|
2021/12/06
|
[
"https://Stackoverflow.com/questions/70241576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14232877/"
] |
I avoid this issue by adding
```
if __name__ == '__main':
fun()
```
I guess this file will be import or load or something else, then it gets run. Anyway, this is not important.
|
Perhaps , You have mistakenly installed an extension 'Run on Save' . I think that's causing the Problem.
|
70,241,576
|
This is a very weried situation, in vscode, I edited my code in the root directory and saved it as test\_distribution.py. After I run this file in vscode terminal. Everytime I edit and save this file, it gets run automatically.
So I moved this file to the subfolder of this project, but I found out it still get run when I edit and save this file. So I changed the file name to distribution\_test.py and add logging and save this file again. It turns out it will still run when I edit and save this file.
How should I figure out why this is happening? What kind of info should I log out in order to figure out this issue?
As you can see the 1300000\_bake.xlsx is generated by this python file, I even moved this python file to a different folder and changed the name of it as I stated above, I am very curious how to find out which program is running this
Pics as follow:
```
for store_id in store_ids:
df = pd.DataFrame(columns=columns)
for query_date in date_range:
logging.info(f"提高计算速度, 使用常规kind_code_cate1类型")
kind_cate1s = normal_cate1
for kind_cate1 in kind_cate1s:
for setting in [dev_setting, prod_setting]:
eng = conn(setting)
delivery_cycle = pd.read_sql(
f"select delivery_cycle from dim_mty_goods where kind_code_cate1={kind_cate1} and can_be_ordered=1",
eng,
)
delivery_cycle = np.unique(delivery_cycle["delivery_cycle"].values)
delivery_cycle = min(delivery_cycle) # 只有冷藏存在多个值, 1, 2, 3 取1, 其他均为单一值
start_time = time.time()
logging.info(
f"开始计算, store_id: {store_id}, date: {query_date}, kind_cate1: {kind_cate1}, dev 环境: {setting == dev_setting}"
)
logging.info(
f"bash command: {create_bash(query_date, kind_cate1, store_id, setting == dev_setting)}"
)
status = os.system(
create_bash(
query_date=query_date,
kind_cate1=kind_cate1,
store_id=store_id,
dev_setting=(setting == dev_setting),
)
)
elapsed = time.time() - start_time
if status != 0:
logging.info(
f'计算出现问题, store_id: {store_id}, date: {query_date}, kind code cate1: {kind_cate1}, 环境: {setting["db"]}'
)
break
logging.info(f"返回耗时: {elapsed}")
if elapsed < 60:
calculate_time = elapsed
elif setting == dev_setting:
calculate_time = pd.DataFrame()
while calculate_time.empty:
calculate_time = pd.read_sql(
f'select cal_time from calculate_time where dt = "{str(query_date)}" and store_id={store_id} and kind_code_cate1={kind_cate1}',
eng,
)
# 等待写库
time.sleep(0.1)
logging.warning(
f"未查询到计算时间, store_id: {store_id}, date: {query_date}, kind_code_cate1: {kind_cate1}"
)
calculate_time = min(calculate_time["cal_time"].values)
else:
calculate_time = elapsed
logging.info(f"计算时间, {calculate_time}")
arrival_sale_day = [
"sale_predict_qtty_t1",
"sale_predict_qtty_t2",
"sale_predict_qtty_t3",
][delivery_cycle]
dev_prod = int(setting["db"] == "marsboard_dev")
df_temp = pd.DataFrame()
while df_temp.empty:
df_temp = pd.read_sql(
f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
eng,
)
logging.warning(f"未查询到order list 里的信息")
if pd.read_sql(
f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
prod_eng,
).empty:
logging.info(f"生产环境本品类亦无数据, {kind_cate1}")
break
time.sleep(0.1)
df_temp["dev_prod"] = dev_prod
df_temp["calculate_time"] = float(calculate_time)
df_temp.columns = columns
df = pd.concat([df_temp, df], axis=0, ignore_index=True)
print(df)
df.to_excel(f"{store_id}_bake.xlsx", index=False)
```
[](https://i.stack.imgur.com/K6vDs.png)
[](https://i.stack.imgur.com/0lHOt.png)
[](https://i.stack.imgur.com/xa4oJ.png)
|
2021/12/06
|
[
"https://Stackoverflow.com/questions/70241576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14232877/"
] |
I have the same issue.
It's now fixed. To do my test I used [pytest](https://docs.pytest.org/en/7.1.x/) and it was able to read my file when it started with `test_`. Because I'm stupid I named it a random filename `test_func.py` and in this one, I wrote "from main.py import \*".
So when I saved, and used pytest to run my test, my main file was run too.
To fix this I just renamed my file in `teste-func.py` and it works.
Sorry my English is terrible. I hope my comment is helpful.
|
Perhaps , You have mistakenly installed an extension 'Run on Save' . I think that's causing the Problem.
|
70,241,576
|
This is a very weried situation, in vscode, I edited my code in the root directory and saved it as test\_distribution.py. After I run this file in vscode terminal. Everytime I edit and save this file, it gets run automatically.
So I moved this file to the subfolder of this project, but I found out it still get run when I edit and save this file. So I changed the file name to distribution\_test.py and add logging and save this file again. It turns out it will still run when I edit and save this file.
How should I figure out why this is happening? What kind of info should I log out in order to figure out this issue?
As you can see the 1300000\_bake.xlsx is generated by this python file, I even moved this python file to a different folder and changed the name of it as I stated above, I am very curious how to find out which program is running this
Pics as follow:
```
for store_id in store_ids:
df = pd.DataFrame(columns=columns)
for query_date in date_range:
logging.info(f"提高计算速度, 使用常规kind_code_cate1类型")
kind_cate1s = normal_cate1
for kind_cate1 in kind_cate1s:
for setting in [dev_setting, prod_setting]:
eng = conn(setting)
delivery_cycle = pd.read_sql(
f"select delivery_cycle from dim_mty_goods where kind_code_cate1={kind_cate1} and can_be_ordered=1",
eng,
)
delivery_cycle = np.unique(delivery_cycle["delivery_cycle"].values)
delivery_cycle = min(delivery_cycle) # 只有冷藏存在多个值, 1, 2, 3 取1, 其他均为单一值
start_time = time.time()
logging.info(
f"开始计算, store_id: {store_id}, date: {query_date}, kind_cate1: {kind_cate1}, dev 环境: {setting == dev_setting}"
)
logging.info(
f"bash command: {create_bash(query_date, kind_cate1, store_id, setting == dev_setting)}"
)
status = os.system(
create_bash(
query_date=query_date,
kind_cate1=kind_cate1,
store_id=store_id,
dev_setting=(setting == dev_setting),
)
)
elapsed = time.time() - start_time
if status != 0:
logging.info(
f'计算出现问题, store_id: {store_id}, date: {query_date}, kind code cate1: {kind_cate1}, 环境: {setting["db"]}'
)
break
logging.info(f"返回耗时: {elapsed}")
if elapsed < 60:
calculate_time = elapsed
elif setting == dev_setting:
calculate_time = pd.DataFrame()
while calculate_time.empty:
calculate_time = pd.read_sql(
f'select cal_time from calculate_time where dt = "{str(query_date)}" and store_id={store_id} and kind_code_cate1={kind_cate1}',
eng,
)
# 等待写库
time.sleep(0.1)
logging.warning(
f"未查询到计算时间, store_id: {store_id}, date: {query_date}, kind_code_cate1: {kind_cate1}"
)
calculate_time = min(calculate_time["cal_time"].values)
else:
calculate_time = elapsed
logging.info(f"计算时间, {calculate_time}")
arrival_sale_day = [
"sale_predict_qtty_t1",
"sale_predict_qtty_t2",
"sale_predict_qtty_t3",
][delivery_cycle]
dev_prod = int(setting["db"] == "marsboard_dev")
df_temp = pd.DataFrame()
while df_temp.empty:
df_temp = pd.read_sql(
f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
eng,
)
logging.warning(f"未查询到order list 里的信息")
if pd.read_sql(
f'select store_id, dt, kind_code_cate1, {arrival_sale_day}, perdict_stock_qtty, predict_num, goods_id, goods_name from order_list where store_id={store_id} and kind_code_cate1={kind_cate1} and dt="{str(query_date)}"',
prod_eng,
).empty:
logging.info(f"生产环境本品类亦无数据, {kind_cate1}")
break
time.sleep(0.1)
df_temp["dev_prod"] = dev_prod
df_temp["calculate_time"] = float(calculate_time)
df_temp.columns = columns
df = pd.concat([df_temp, df], axis=0, ignore_index=True)
print(df)
df.to_excel(f"{store_id}_bake.xlsx", index=False)
```
[](https://i.stack.imgur.com/K6vDs.png)
[](https://i.stack.imgur.com/0lHOt.png)
[](https://i.stack.imgur.com/xa4oJ.png)
|
2021/12/06
|
[
"https://Stackoverflow.com/questions/70241576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14232877/"
] |
I avoid this issue by adding
```
if __name__ == '__main':
fun()
```
I guess this file will be import or load or something else, then it gets run. Anyway, this is not important.
|
I have the same issue.
It's now fixed. To do my test I used [pytest](https://docs.pytest.org/en/7.1.x/) and it was able to read my file when it started with `test_`. Because I'm stupid I named it a random filename `test_func.py` and in this one, I wrote "from main.py import \*".
So when I saved, and used pytest to run my test, my main file was run too.
To fix this I just renamed my file in `teste-func.py` and it works.
Sorry my English is terrible. I hope my comment is helpful.
|
4,170,532
|
I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
```
@app.route('/home')
def userhome():
data=go get user details from the database
return render_template("home.html",userdata=data)
```
Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template.
However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript).
The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks.
I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here.
Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.
|
2010/11/13
|
[
"https://Stackoverflow.com/questions/4170532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459514/"
] |
I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.
In the `home.html` template, I'd do something like
```
<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>
```
And keep the actual markup in `_user_details.html`. This way, for an AJAX request you just render the `_user_details.html` partial only.
|
You have two options: template on the server, or template in the browser.
To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.
To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are [lots of jQuery templating solutions](https://stackoverflow.com/questions/170168/jquery-templating-engines), for example.
|
33,262,919
|
When writing doc strings in python, I am wondering if the docstring should contain the exceptions that are implicitly raised or if it should also contain the exceptions I explicitly raise.
Consider the function
```
def inv(a):
if a == 0:
raise ZeroDivisionError
else:
return 1/a
```
So in a docstring under the "Raises" keyword I would definetly put ZeroDivisionError. However, depending on the input I would also expect a TypeError. So would you put that also in the docstring?
Due to the EAFP principle (if i understand it correctly) I don't want to check for types here, correct?
Any hint (also on the code sample) is welcome.
|
2015/10/21
|
[
"https://Stackoverflow.com/questions/33262919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5152563/"
] |
It depends what (or whom) you're writing the docstring for. For automatic conversion to API documentation, I like [Google-style docstrings](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/example_google.html), which would look like:
```
def inv(a):
"""Return the inverse of the argument.
Arguments:
a (int): The number to invert.
Returns:
float: The inverse of the argument.
Raises:
TypeError: If 1 cannot be divided by the argument.
ZeroDivisionError: If the argument is zero.
"""
return 1 / a
```
Here I've included *all of the exceptions that the function is likely to raise*. Note that there's no need to explicitly `raise ZeroDivisionError` - that will happen automatically if you try to divide by zero.
---
However, if you aren't creating documentation from the docstring, I would probably just include the description line for such a simple function:
```
def inv(a):
"""Return the inverse of the argument."""
return 1 / a
```
Anyone using it is likely to know that you can't invert e.g. strings.
---
>
> I don't want to check for types here, correct?
>
>
>
I wouldn't - if the user, after reading your documentation, decides to pass e.g. a string into the function they should *expect* to get the `TypeError`, and there's no point testing the argument type to then raise the same exception yourself that the code would have raised anyway (again, see also the `ZeroDivisionError`!) That is, unless e.g. `float` or `complex` numbers should be invalid input, in which case you will need to handle them manually.
|
No. The docstring should describe the input expected. If this were my function, I would include something like this in the docstring:
```
"""Return the inverse of an integer. ZeroDivisionError is raised if zero is
passed to this function."""
```
Therefore it is specified that the input should be an integer. Specifying that the function can raise a `TypeError` just overly complicates the docstring.
|
21,234,884
|
How can I set a suitable fps number in pygame for any kind of monitor running my game? I know I can set fps using `pygame.time.Clock().tick(fps)` but how can I set suitable fps?
Please post example python code along with answer.
|
2014/01/20
|
[
"https://Stackoverflow.com/questions/21234884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2837388/"
] |
I'm not entirely sure that I understand the question being asked, but I think you will just have to experiment with different numbers and find out what works for you. I find that around 50-100 is a good range.
If what you are trying to do is make game events only update a certain number of times per second while rendering happens as fast as the computer is able to handle it, this is a very complex process and probably not very easily done in pygame.
|
The trick I've figured out is not limiting the frame rate, but calculating based on time. The pygame.time.Clock.tick() returns time in milliseconds, which you can then pass to other parts of the program to calculate events or animation updates.
For example, I currently use a pair of variable in my Player object to store the center point of the player's character multiplied by 1000 to be able to update it as an int from `tick()`. I think update it each loop, after solving which direction the player is moving, with the following code:
```
self.x += self.speed * time * xmove
self.y += self.speed * time * ymove
self.rect.centerx = self.x / 1000
self.rect.centery = self.y / 1000
```
Additionally, I use that same `time` variable as part of the Spawner class to determine when new enemies should be spawned to the map, and for the movement of the enemies and bullets in the game.
This method has the bonus of keeping game play more or less the same across multiple frame rates.
|
58,449,314
|
When I activate my ipykernel\_py3 environment and try to launch Jupyter Lab in terminal, I get the repeated error messages as follows:
```
Macintosh-8:~ yuenfannie$ source activate ipykernel_py3
(ipykernel_py3) Macintosh-8:~ yuenfannie$ jupyter lab
[I 12:38:19.969 LabApp] JupyterLab alpha preview extension loaded from /Users/yuenfannie/anaconda2/lib/python2.7/site-packages/jupyterlab
JupyterLab v0.27.0
Known labextensions:
[I 12:38:19.971 LabApp] Running the core application with no additional extensions or settings
[I 12:38:19.979 LabApp] Serving notebooks from local directory: /Users/yuenfannie
[I 12:38:19.980 LabApp] 0 active kernels
[I 12:38:19.980 LabApp] The Jupyter Notebook is running at: http://localhost:8888/?token=81a366305f2a328dfbbc9cfcf757a30e4977d3abab54cb0f
[I 12:38:19.980 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 12:38:19.981 LabApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=81a366305f2a328dfbbc9cfcf757a30e4977d3abab54cb0f
[I 12:38:20.229 LabApp] Accepting one-time-token-authenticated connection from ::1
[I 12:38:22.881 LabApp] Kernel started: cf6886dd-5475-4e1e-972c-8e4614451f0e
[I 12:38:24.074 LabApp] Adapting to protocol v5.0 for kernel cf6886dd-5475-4e1e-972c-8e4614451f0e
[E 12:38:24.078 LabApp] Uncaught exception GET /api/kernels/cf6886dd-5475-4e1e-972c-8e4614451f0e/channels?session_id=5c81adbda104d35cec3acd907d6decc4&token=81a366305f2a328dfbbc9cfcf757a30e4977d3abab54cb0f (::1)
HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/api/kernels/cf6886dd-5475-4e1e-972c-8e4614451f0e/channels?session_id=5c81adbda104d35cec3acd907d6decc4&token=81a366305f2a328dfbbc9cfcf757a30e4977d3abab54cb0f', version='HTTP/1.1', remote_ip='::1')
Traceback (most recent call last):
File "/Users/yuenfannie/anaconda2/lib/python2.7/site-packages/tornado/websocket.py", line 546, in _run_callback
result = callback(*args, **kwargs)
File "/Users/yuenfannie/anaconda2/lib/python2.7/site-packages/notebook/services/kernels/handlers.py", line 262, in open
super(ZMQChannelsHandler, self).open()
File "/Users/yuenfannie/anaconda2/lib/python2.7/site-packages/notebook/base/zmqhandlers.py", line 176, in open
self.send_ping, self.ping_interval, io_loop=loop,
TypeError: __init__() got an unexpected keyword argument 'io_loop'
```
The opened JupyterLab Alpha Preview does not work at all. Unfortunately I have no clues why this happens. Any suggestions are welcome!
|
2019/10/18
|
[
"https://Stackoverflow.com/questions/58449314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4632960/"
] |
This is the wrong way round and can never be true, because you're asking for `tt` to be less than 2 and at least 12 at the same time:
```
if 2 >= tt >= 12:
```
You probably meant:
```
if 2 <= tt <= 12:
```
And instead of `elif` with a condition, you can just use `else`.
|
That is.
```
tt = int(input("What times tables would you like: "))
if 2 <= tt <= 12:
for x in range(1, 13):
aw = tt * x
print(tt, "x", x, " = ", aw)
else:
print("Please enter number between 2 and 12")
```
|
27,948,420
|
I am getting confused trying to find a way to **send the left-click in a web browser window in a specific point**. I am using Selenium `selenium-2.44.0` and Python 2.7. My ultimate goal is to be able to click in certain areas in the window, but for now I just want to make sure I am able to click at all. I thought that clicking on an area where a link is located is a good idea because then I will be able to verify the click did occur (i.e., I will be taken to another html page).
All the prerequisites are met, I am able to start the browser and access and manipulate various web elements. From what I've found in the Help, one is supposed to use [move\_by\_offset](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.common.action_chains.ActionChains.move_by_offset) method to move the mouse cursor into a certain direction. However, **when I run the code, the click doesn't occur (or it occurs, but the url link is not clicked and no new page opens)**. I cannot even verify whether the click occurred. When clicking the Logout link, for instance, in a normal browser session, the logout operation occurs.
```
...
homeLink = driver.find_element_by_link_text("Home")
homeLink.click() #clicking on the Home button and mouse cursor should? stay here
print homeLink.size, homeLink.location
helpLink = driver.find_element_by_link_text("Help")
print helpLink.size, helpLink.location
action = webdriver.common.action_chains.ActionChains(driver)
action.move_by_offset(150,0) #move 150 pixels to the right to access Help link
action.click()
action.perform()
```
Here is the screenshot of the area in the web page I am working with.

The size and location of the elements are printed as below:
```
{'width': 39, 'height': 16} {'y': 47, 'x': 341}
{'width': 30, 'height': 16} {'y': 47, 'x': 457}
```
The html code behind the page is below, if it's worth looking at.
```
<a href="/web/">Home</a>
|
<a href="/web/Account/LogOff">Logout</a>
|
<a href="#" onclick="HelpFile.open();">Help</a>
```
I know that I can access the link by finding an element in many ways, but I am trying to perform a click in a certain location and am using the link element just to verify the click really occurred.
**How do perform the click?**
|
2015/01/14
|
[
"https://Stackoverflow.com/questions/27948420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3346915/"
] |
Assuming there is nothing else going on on your page that would interfere with the click, this should do it:
```
homeLink = driver.find_element_by_link_text("Home")
homeLink.click() #clicking on the Home button and mouse cursor should? stay here
print homeLink.size, homeLink.location
helpLink = driver.find_element_by_link_text("Help")
print helpLink.size, helpLink.location
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(homeLink, 150, 0) #move 150 pixels to the right to access Help link
action.click()
action.perform()
```
You should use [`move_to_element_with_offset`](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.common.action_chains.ActionChains.move_to_element_with_offset) if you want the mouse position to be relative to an element. Otherwise, [`move_by_offset`](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.common.action_chains.ActionChains.move_by_offset) moves the mouse relative to the previous mouse position. When you using `click` or `move_to_element`, the mouse is placed in the center of the element. (The [Java documentation](https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html#click%28org.openqa.selenium.WebElement%29) about these is explicit.)
|
Hard to say for you exact situation but I know a workaround to the question in the summary and bold
>
> send the left-click in a web browser window in a specific point
>
>
>
You just use execute\_script and do the clicking using javascript.
```
self.driver.execute_script('el = document.elementFromPoint(47, 457); el.click();')
```
It's convenient in a pinch because you can debug find the coordinates of an element in a browser by opening console and using querySelector (works the same as Webdriver's By.CSS\_SELECTOR):
```
el = document.querySelector('div > h1');
var boundaries = el.getBoundingClientRect();
console.log(boundaries.top, boundaries.right, boundaries.bottom, boundaries.left);
```
That being said, it's a really bad idea to write your tests to click a specific point. But I have found that sometimes even when el.click() or an [action chain](https://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.action_chains.html) aren't working, execute script will still work using a querySelector which is about as good as what you would be doing in Selenium.
```
self.driver.execute_script('el = document.querySelector("div > h1"); el.click();')
```
|
18,701,464
|
I wanted to write a program to scrape a website from python. Since there is no built-in possibility to do so, I decided to give the BeautifulSoup module a try.
Unfortunately I encountered some problems using pip and ez\_install, since I use Windows 7 64 bit and Python 3.3.
Is there a way to get the BeautifulSoup module on my Python 3.3 installation with Windows 7 64x without ez\_install or easy\_install, since I have too much trouble with this, or is there an alternative module which can be easily installed?
|
2013/09/09
|
[
"https://Stackoverflow.com/questions/18701464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2733724/"
] |
Just download [here](http://www.crummy.com/software/BeautifulSoup/bs3/download//) and then add the `BeautifulSoup.py (uncompress the download tarball file use uncompress soft such as 7z)` to your python sys.path use `sys.path.append("/path/to/BeautifulSoup.py")`, of cource you can just put it under your current src dir as a normal python module or put it in the pathon's sys path.
BTW the tarball install(or build) way is:
```
cd BeautifulSoup
python setup.py install(or build)
```
if you are using **python3**, you can dowload the `bs4(look at the commetn under this answer)`, just let the `bs4`(in the tarball source dir) under your python's sys path and then
```
from bs4 import BeautifulSoup
```
good luck~
|
I haven't tried it, but check out [pip](https://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) to install python packages. It's supposed to be better.
[Why use pip over easy\_install](https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install)
I have personally used BeautifulSoup and like it. I have heard [pyquery](https://pypi.python.org/pypi/pyquery) is good too with a jquery like interface.
|
18,701,464
|
I wanted to write a program to scrape a website from python. Since there is no built-in possibility to do so, I decided to give the BeautifulSoup module a try.
Unfortunately I encountered some problems using pip and ez\_install, since I use Windows 7 64 bit and Python 3.3.
Is there a way to get the BeautifulSoup module on my Python 3.3 installation with Windows 7 64x without ez\_install or easy\_install, since I have too much trouble with this, or is there an alternative module which can be easily installed?
|
2013/09/09
|
[
"https://Stackoverflow.com/questions/18701464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2733724/"
] |
You just need to add to download it and add it to your python search path directly. (Which is in sys.path, if you need to check it.)
From the documentation:
Beautiful Soup is licensed under the MIT license, so you can also download the tarball, drop the bs4/ directory into almost any Python application (or into your library path) and start using it immediately. (If you want to do this under Python 3, you will need to manually convert the code using 2to3.)
|
I haven't tried it, but check out [pip](https://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) to install python packages. It's supposed to be better.
[Why use pip over easy\_install](https://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install)
I have personally used BeautifulSoup and like it. I have heard [pyquery](https://pypi.python.org/pypi/pyquery) is good too with a jquery like interface.
|
41,525,223
|
I'm just trying to run the simple hello world app on their tutorials page. I used to use Google App Engine frequently, but now I can't seem to get it going at all. I'm on win 10 x64. Downloaded latest google cloud sdk, and python version 2.7.13
```
> ERROR 2017-01-07 15:25:21,219 wsgi.py:263] Traceback (most recent
> call last): File "C:\Program Files (x86)\Google\Cloud
> SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py",
> line 240, in Handle
> handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "C:\Program Files (x86)\Google\Cloud
> SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py",
> line 299, in _LoadHandler
> handler, path, err = LoadObject(self._handler) File "C:\Program Files (x86)\Google\Cloud
> SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py",
> line 85, in LoadObject
> obj = __import__(path[0]) File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\main.py",
> line 18, in <module>
> from flask import Flask File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\flask\__init__.py",
> line 21, in <module>
> from .app import Flask, Request, Response File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\flask\app.py",
> line 27, in <module>
> from . import json, cli File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\flask\cli.py",
> line 17, in <module>
> import click File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\click\__init__.py",
> line 18, in <module> INFO 2017-01-07 10:25:21,229 module.py:806]
> default: "GET / HTTP/1.1" 500 -
> from .core import Context, BaseCommand, Command, MultiCommand, Group, \ File
> "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\click\core.py", line 8, in <module>
> from .types import convert_type, IntRange, BOOL File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\click\types.py",
> line 4, in <module>
> from ._compat import open_stream, text_type, filename_to_ui, \ File
> "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\click\_compat.py",
> line 536, in <module>
> from ._winconsole import _get_windows_console_stream File "C:\....\python-docs-samples\appengine\standard\flask\hello_world\lib\click\_winconsole.py",
> line 16, in <module>
> import ctypes File "C:\Python27\lib\ctypes\__init__.py", line 7, in <module>
> from _ctypes import Union, Structure, Array File "C:\Program Files (x86)\Google\Cloud
> SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\sandbox.py",
> line 964, in load_module
> raise ImportError('No module named %s' % fullname)
ImportError: No module named _ctypes
```
|
2017/01/07
|
[
"https://Stackoverflow.com/questions/41525223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4769616/"
] |
Google's sample Flask "Hello World" application requires `Flask 0.11.1`.
This library is not vendored by Google, so developers are required to install it via `pip`
>
> This sample shows how to use Flask with Google App Engine Standard.
>
>
> Before running or deploying this application, install the dependencies
> using pip:
>
>
> `pip install -t lib -r requirements.txt`
>
>
>
Flask's `setup.py` [instructs](https://github.com/pallets/flask/blob/0.11.1/setup.py) `pip` to install the [click](https://github.com/pallets/click/) library, at a release later than or equal to version 2.0.
```
install_requires=[
'Werkzeug>=0.7',
'Jinja2>=2.4',
'itsdangerous>=0.21',
'click>=2.0',
],
```
In November 2015 [a change was committed](https://github.com/pallets/click/commit/bcf8feceb41b3f75f3cd07eb851734fa96cd1991) to `click` to improve support for unicode in the windows console. This change added the import of the `ctypes` library which Appengine is choking on, because the Appengine sandbox does not allow importing `ctypes`.
The workaround for this is to overwrite the installed `click` with an earlier version (5.1 [looks like the most recent candidate](https://github.com/pallets/click/blob/master/CHANGES)):
`pip install --target lib --upgrade click==5.1`
|
For me, the workaround mentioned here [Google's issue tracker](https://issuetracker.google.com/issues/38290292) worked
* goto [sdk\_home]\google\appengine\tools\devappserver2\python\sandbox.py
* find the definition of \_WHITE\_LIST\_C\_MODULES = [xxx]
add following two lines to the list:
'\_winreg',
'\_ctypes',
* try your app again.
The issue was marked fixed on 7/7/2017.
|
52,960,057
|
I have an assignment where we need to create functions to display text onto the screen in python/pygame. This part I understand. What I don't is that you're supposed to create a function which creates a drop shadow. I know how to make the shadow I just don't know how to make another function to do it and have the option to call from a pre existing text one. This is what I have so far
```
import pygame
import sys
pygame.init()
screenSizeX = 1080
screenSizeY = 720
screenSize = (screenSizeX,screenSizeY)
screen = pygame.display.set_mode(screenSize,0)
pygame.display.set_caption("Test Functions")
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,255,0)
BLACK = (0,0,0)
MAGENTA = (139,0,139)
def horCenter(font, size, text, colour, y, shadow, pos):
if shadow == True:
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textWidth = textTitle.get_width()
screen.blit(textTitle, (screenSizeX/2 - textWidth/2, y))
def verCenter(font, size, text, colour, x):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
screen.blit(textTitle, (x, screenSizeY/2 - textHeight/2))
def cenCenter(font, size, text, colour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
textWidth = textTitle.get_width()
screen.blit(textTitle, (screenSizeX/2 - textWidth/2, screenSizeY/2 - textHeight/2))
pygame.display.update()
go = True
while go:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
go = False
screen.fill(WHITE)
horCenter("Comic Sans MS", 40, "Text1", MAGENTA, 100)
verCenter("Georgia", 10, "Tex2", GREEN, 500)
cenCenter("Impact", 50, "Text3", RED)
verCenter("Verdana", 60, "89274", BLACK, 50)
pygame.display.update()
pygame.quit()
sys.exit()
```
|
2018/10/24
|
[
"https://Stackoverflow.com/questions/52960057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10391389/"
] |
A dropshadow can be rendered by drawing the text twice. The first is a grey version of the text at an offset, then the actual text at the original position.
```
def dropShadowText(screen, text, size, x, y, colour=(255,255,255), drop_colour=(128,128,128), font=None):
# how much 'shadow distance' is best?
dropshadow_offset = 1 + (size // 15)
text_font = pygame.font.Font(font, size)
# make the drop-shadow
text_bitmap = text_font.render(text, True, drop_colour)
screen.blit(text_bitmap, (x+dropshadow_offset, y+dropshadow_offset) )
# make the overlay text
text_bitmap = text_font.render(text, True, colour)
screen.blit(text_bitmap, (x, y) )
```
So you can call it like:
```
dropShadowText(screen, "Hello World", 36, 50, 50)
```
|
I figured it out with help from Kingsley's response. Now you can choose to add a shadow or not, where its positioned and what colour it is. Maybe there is an easier way but this worked for me.
```
import pygame
import sys
pygame.init()
screenSizeX = 1080
screenSizeY = 720
screenSize = (screenSizeX,screenSizeY)
screen = pygame.display.set_mode(screenSize,0)
pygame.display.set_caption("Test Functions")
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,255,0)
BLACK = (0,0,0)
MAGENTA = (139,0,139)
def horCenter(font, size, text, colour, yPos, shadow, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textWidth = textTitle.get_width()
xPos = screenSizeX/2 - textWidth/2
if shadow == "True":
dropShadow(font,size,text,colour, xPos,yPos, shadowPlace, shadowColour)
else:
screen.blit(textTitle, (xPos, yPos))
def verCenter(font, size, text, colour, xPos, shadow, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
yPos = screenSizeY/2 - textHeight/2
if shadow == "True":
dropShadow(font,size,text,colour, xPos,yPos, shadowPlace, shadowColour)
else:
screen.blit(textTitle, (xPos, yPos))
def cenCenter(font, size, text, colour, shadow, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
textWidth = textTitle.get_width()
xPos = screenSizeX/2 - textWidth/2
yPos = screenSizeY/2 - textHeight/2
if shadow == "True":
dropShadow(font,size,text,colour, xPos,yPos, shadowPlace, shadowColour)
else:
screen.blit(textTitle, (xPos, yPos))
def dropShadow(font, size, text, colour, xPos,yPos, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
shadowTitle = fontTitle.render(text, True, shadowColour)
if shadowPlace == "bottomRight":
newXPos = xPos +2
newYPos = yPos + 2
screen.blit(shadowTitle, (newXPos,newYPos))
screen.blit(textTitle, (xPos,yPos))
elif shadowPlace == "bottomLeft":
newXPos = xPos - 2
newYPos = yPos + 2
screen.blit(shadowTitle, (newXPos, newYPos))
screen.blit(textTitle, (xPos, yPos))
elif shadowPlace == "topRight":
newXPos = xPos - 2
newYPos = yPos - 2
screen.blit(shadowTitle, (newXPos, newYPos))
screen.blit(textTitle, (xPos, yPos))
elif shadowPlace == "topLeft":
newXPos = xPos + 2
newYPos = yPos - 2
screen.blit(shadowTitle, (newXPos, newYPos))
screen.blit(textTitle, (xPos, yPos))
pygame.display.update()
go = True
while go:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
go = False
screen.fill(WHITE)
horCenter("Comic Sans MS", 40, "Thanos", MAGENTA, 100, "True", "topLeft", YELLOW)
verCenter("Georgia", 10, "HULK SMASH", GREEN, 800, "True", "bottomRight", BLACK)
cenCenter("Impact", 50, "MARVEL", RED, "True", "bottomRight", BLACK)
verCenter("Verdana", 60, "Black Widow", BLACK, 50, "True", "topRight", RED)
pygame.display.update()
pygame.quit()
sys.exit()
```
|
52,960,057
|
I have an assignment where we need to create functions to display text onto the screen in python/pygame. This part I understand. What I don't is that you're supposed to create a function which creates a drop shadow. I know how to make the shadow I just don't know how to make another function to do it and have the option to call from a pre existing text one. This is what I have so far
```
import pygame
import sys
pygame.init()
screenSizeX = 1080
screenSizeY = 720
screenSize = (screenSizeX,screenSizeY)
screen = pygame.display.set_mode(screenSize,0)
pygame.display.set_caption("Test Functions")
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,255,0)
BLACK = (0,0,0)
MAGENTA = (139,0,139)
def horCenter(font, size, text, colour, y, shadow, pos):
if shadow == True:
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textWidth = textTitle.get_width()
screen.blit(textTitle, (screenSizeX/2 - textWidth/2, y))
def verCenter(font, size, text, colour, x):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
screen.blit(textTitle, (x, screenSizeY/2 - textHeight/2))
def cenCenter(font, size, text, colour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
textWidth = textTitle.get_width()
screen.blit(textTitle, (screenSizeX/2 - textWidth/2, screenSizeY/2 - textHeight/2))
pygame.display.update()
go = True
while go:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
go = False
screen.fill(WHITE)
horCenter("Comic Sans MS", 40, "Text1", MAGENTA, 100)
verCenter("Georgia", 10, "Tex2", GREEN, 500)
cenCenter("Impact", 50, "Text3", RED)
verCenter("Verdana", 60, "89274", BLACK, 50)
pygame.display.update()
pygame.quit()
sys.exit()
```
|
2018/10/24
|
[
"https://Stackoverflow.com/questions/52960057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10391389/"
] |
A dropshadow can be rendered by drawing the text twice. The first is a grey version of the text at an offset, then the actual text at the original position.
```
def dropShadowText(screen, text, size, x, y, colour=(255,255,255), drop_colour=(128,128,128), font=None):
# how much 'shadow distance' is best?
dropshadow_offset = 1 + (size // 15)
text_font = pygame.font.Font(font, size)
# make the drop-shadow
text_bitmap = text_font.render(text, True, drop_colour)
screen.blit(text_bitmap, (x+dropshadow_offset, y+dropshadow_offset) )
# make the overlay text
text_bitmap = text_font.render(text, True, colour)
screen.blit(text_bitmap, (x, y) )
```
So you can call it like:
```
dropShadowText(screen, "Hello World", 36, 50, 50)
```
|
If you want a transparent drop shadow, you have to:
* Create a transparent [`pygame.Surface`](https://www.pygame.org/docs/ref/surface.html) large enough for the text and the shadow. The size of a text to be rendered can be determined with [`Font.size()`](https://www.pygame.org/docs/ref/font.html#pygame.font.Font.size). A transparent *Surface* can be created with the `pygame.SRCALPHA` flag (see [How to make a surface with a transparent background in pygame](https://stackoverflow.com/questions/328061/how-to-make-a-surface-with-a-transparent-background-in-pygame/64512639#64512639)).
* Render the text with the shadow color and set the transparency of the shadow with [`pygame.Surface.set_alpha`](https://www.pygame.org/docs/ref/surface.html#pygame.Surface.set_alpha) (see [How to render transparent text with alpha channel in PyGame?](https://stackoverflow.com/questions/20620109/how-to-render-transparent-text-with-alpha-channel-in-pygame/64552616#64552616)).
* render the text with the text color.
* `blit` the transparent drop shadow text on the render *Surface*
* `blit` the text on the render *Surface*.
* `blit` the render surface on the screen.
```py
def renderTextDropShadow(font, text, color, dx, dy, shadowColor, shadowAlpha):
textSize = font.size(text)
surf = pygame.Surface((textSize[0] + abs(dx), textSize[1] + abs(dy)), pygame.SRCALPHA)
shadowSurf = font.render(text, True, shadowColor)
shadowSurf.set_alpha(shadowAlpha)
textSurf = font.render(text, True, color)
surf.blit(shadowSurf, (max(0, dx), max(0, dy)))
surf.blit(textSurf, (max(0, -dx), max(0, -dy)))
return surf
```
---
Minimal example:
[](https://i.stack.imgur.com/8D4mY.png)
```py
import pygame
def renderTextDropShadow(font, text, color, dx, dy, shadowColor=(127, 127, 127), shadowAlpha = 127):
textSize = font.size(text)
surf = pygame.Surface((textSize[0] + abs(dx), textSize[1] + abs(dy)), pygame.SRCALPHA)
shadowSurf = font.render(text, True, shadowColor)
shadowSurf.set_alpha(shadowAlpha)
textSurf = font.render(text, True, color)
surf.blit(shadowSurf, (max(0, dx), max(0, dy)))
surf.blit(textSurf, (max(0, -dx), max(0, -dy)))
return surf
pygame.init()
window = pygame.display.set_mode((700, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 150)
textSurf = renderTextDropShadow(font, 'Hello World!', (0, 0, 0), -15, 10)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (255, 255, 255), (255, 164, 196)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(textSurf, textSurf.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
```
|
52,960,057
|
I have an assignment where we need to create functions to display text onto the screen in python/pygame. This part I understand. What I don't is that you're supposed to create a function which creates a drop shadow. I know how to make the shadow I just don't know how to make another function to do it and have the option to call from a pre existing text one. This is what I have so far
```
import pygame
import sys
pygame.init()
screenSizeX = 1080
screenSizeY = 720
screenSize = (screenSizeX,screenSizeY)
screen = pygame.display.set_mode(screenSize,0)
pygame.display.set_caption("Test Functions")
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,255,0)
BLACK = (0,0,0)
MAGENTA = (139,0,139)
def horCenter(font, size, text, colour, y, shadow, pos):
if shadow == True:
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textWidth = textTitle.get_width()
screen.blit(textTitle, (screenSizeX/2 - textWidth/2, y))
def verCenter(font, size, text, colour, x):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
screen.blit(textTitle, (x, screenSizeY/2 - textHeight/2))
def cenCenter(font, size, text, colour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
textWidth = textTitle.get_width()
screen.blit(textTitle, (screenSizeX/2 - textWidth/2, screenSizeY/2 - textHeight/2))
pygame.display.update()
go = True
while go:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
go = False
screen.fill(WHITE)
horCenter("Comic Sans MS", 40, "Text1", MAGENTA, 100)
verCenter("Georgia", 10, "Tex2", GREEN, 500)
cenCenter("Impact", 50, "Text3", RED)
verCenter("Verdana", 60, "89274", BLACK, 50)
pygame.display.update()
pygame.quit()
sys.exit()
```
|
2018/10/24
|
[
"https://Stackoverflow.com/questions/52960057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10391389/"
] |
I figured it out with help from Kingsley's response. Now you can choose to add a shadow or not, where its positioned and what colour it is. Maybe there is an easier way but this worked for me.
```
import pygame
import sys
pygame.init()
screenSizeX = 1080
screenSizeY = 720
screenSize = (screenSizeX,screenSizeY)
screen = pygame.display.set_mode(screenSize,0)
pygame.display.set_caption("Test Functions")
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,255,0)
BLACK = (0,0,0)
MAGENTA = (139,0,139)
def horCenter(font, size, text, colour, yPos, shadow, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textWidth = textTitle.get_width()
xPos = screenSizeX/2 - textWidth/2
if shadow == "True":
dropShadow(font,size,text,colour, xPos,yPos, shadowPlace, shadowColour)
else:
screen.blit(textTitle, (xPos, yPos))
def verCenter(font, size, text, colour, xPos, shadow, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
yPos = screenSizeY/2 - textHeight/2
if shadow == "True":
dropShadow(font,size,text,colour, xPos,yPos, shadowPlace, shadowColour)
else:
screen.blit(textTitle, (xPos, yPos))
def cenCenter(font, size, text, colour, shadow, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
textHeight = textTitle.get_height()
textWidth = textTitle.get_width()
xPos = screenSizeX/2 - textWidth/2
yPos = screenSizeY/2 - textHeight/2
if shadow == "True":
dropShadow(font,size,text,colour, xPos,yPos, shadowPlace, shadowColour)
else:
screen.blit(textTitle, (xPos, yPos))
def dropShadow(font, size, text, colour, xPos,yPos, shadowPlace, shadowColour):
fontTitle = pygame.font.SysFont(font, size)
textTitle = fontTitle.render(text, True, colour)
shadowTitle = fontTitle.render(text, True, shadowColour)
if shadowPlace == "bottomRight":
newXPos = xPos +2
newYPos = yPos + 2
screen.blit(shadowTitle, (newXPos,newYPos))
screen.blit(textTitle, (xPos,yPos))
elif shadowPlace == "bottomLeft":
newXPos = xPos - 2
newYPos = yPos + 2
screen.blit(shadowTitle, (newXPos, newYPos))
screen.blit(textTitle, (xPos, yPos))
elif shadowPlace == "topRight":
newXPos = xPos - 2
newYPos = yPos - 2
screen.blit(shadowTitle, (newXPos, newYPos))
screen.blit(textTitle, (xPos, yPos))
elif shadowPlace == "topLeft":
newXPos = xPos + 2
newYPos = yPos - 2
screen.blit(shadowTitle, (newXPos, newYPos))
screen.blit(textTitle, (xPos, yPos))
pygame.display.update()
go = True
while go:
for event in pygame.event.get():
if event.type ==pygame.QUIT:
go = False
screen.fill(WHITE)
horCenter("Comic Sans MS", 40, "Thanos", MAGENTA, 100, "True", "topLeft", YELLOW)
verCenter("Georgia", 10, "HULK SMASH", GREEN, 800, "True", "bottomRight", BLACK)
cenCenter("Impact", 50, "MARVEL", RED, "True", "bottomRight", BLACK)
verCenter("Verdana", 60, "Black Widow", BLACK, 50, "True", "topRight", RED)
pygame.display.update()
pygame.quit()
sys.exit()
```
|
If you want a transparent drop shadow, you have to:
* Create a transparent [`pygame.Surface`](https://www.pygame.org/docs/ref/surface.html) large enough for the text and the shadow. The size of a text to be rendered can be determined with [`Font.size()`](https://www.pygame.org/docs/ref/font.html#pygame.font.Font.size). A transparent *Surface* can be created with the `pygame.SRCALPHA` flag (see [How to make a surface with a transparent background in pygame](https://stackoverflow.com/questions/328061/how-to-make-a-surface-with-a-transparent-background-in-pygame/64512639#64512639)).
* Render the text with the shadow color and set the transparency of the shadow with [`pygame.Surface.set_alpha`](https://www.pygame.org/docs/ref/surface.html#pygame.Surface.set_alpha) (see [How to render transparent text with alpha channel in PyGame?](https://stackoverflow.com/questions/20620109/how-to-render-transparent-text-with-alpha-channel-in-pygame/64552616#64552616)).
* render the text with the text color.
* `blit` the transparent drop shadow text on the render *Surface*
* `blit` the text on the render *Surface*.
* `blit` the render surface on the screen.
```py
def renderTextDropShadow(font, text, color, dx, dy, shadowColor, shadowAlpha):
textSize = font.size(text)
surf = pygame.Surface((textSize[0] + abs(dx), textSize[1] + abs(dy)), pygame.SRCALPHA)
shadowSurf = font.render(text, True, shadowColor)
shadowSurf.set_alpha(shadowAlpha)
textSurf = font.render(text, True, color)
surf.blit(shadowSurf, (max(0, dx), max(0, dy)))
surf.blit(textSurf, (max(0, -dx), max(0, -dy)))
return surf
```
---
Minimal example:
[](https://i.stack.imgur.com/8D4mY.png)
```py
import pygame
def renderTextDropShadow(font, text, color, dx, dy, shadowColor=(127, 127, 127), shadowAlpha = 127):
textSize = font.size(text)
surf = pygame.Surface((textSize[0] + abs(dx), textSize[1] + abs(dy)), pygame.SRCALPHA)
shadowSurf = font.render(text, True, shadowColor)
shadowSurf.set_alpha(shadowAlpha)
textSurf = font.render(text, True, color)
surf.blit(shadowSurf, (max(0, dx), max(0, dy)))
surf.blit(textSurf, (max(0, -dx), max(0, -dy)))
return surf
pygame.init()
window = pygame.display.set_mode((700, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 150)
textSurf = renderTextDropShadow(font, 'Hello World!', (0, 0, 0), -15, 10)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (255, 255, 255), (255, 164, 196)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
window.blit(textSurf, textSurf.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
```
|
18,718,715
|
I've been looking into scraping, and I cant manage to scrape twitter searches that date long way back by using python code, i can do it however with an addon for chrome but it falls short since it will only let me obtain a very limited amount of tweets. can anybody point me in the right direction¿
|
2013/09/10
|
[
"https://Stackoverflow.com/questions/18718715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2761466/"
] |
I found a related answer here:
<https://stackoverflow.com/a/6082633/1449045>
you can get up to 1500 tweets for a search; 3200 for a particular user's timeline
source: <https://dev.twitter.com/docs/things-every-developer-should-know>
see "There are pagination limits"
Here you can find a list of libraries to simplify the use of the APIs,
in different languages, including python
<https://dev.twitter.com/docs/twitter-libraries>
|
You can use [snscrape](https://github.com/JustAnotherArchivist/snscrape). It doesn't require a Twitter Developer Account it can go back many years.
|
26,928,817
|
I will start by saying that I have never created an app that required installation and I have no idea how it works. But now I have to, and I am wondering how to proceed, use some kind os installation tools (installshield, wix) or create a python script and turn into an .exe.
What my install needs to do is:
* create a folder and add it to the system path
* check a repo via http for the latest version of a file and download it into that folder
How can I approach this?
Also, if I use any installation tools, can that setup file be used for updating?
|
2014/11/14
|
[
"https://Stackoverflow.com/questions/26928817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2367912/"
] |
I put this logic in my view's `form_valid` like so:
```
def form_valid(self, form):
self.object, created = Car.objects.get_or_create(
**form.cleaned_data
)
return super(CarCreateView, self).form_valid(form)
```
To put that in context, I have a complaints case management system that registers new complaints in stages. When someone wants to complain their details are stored in a `Complainant` model that creates a new complainant for someone's first complaint but doesn't for subsequent ones. They are then redirected to a `Case` model form along with their `id` value, which is automatically added as the `Case` object's foreign key to the `Complainant` object. That model form looks like this:
```
class ComplainantCreateView(PermissionRequiredMixin, CreateView):
model = Complainant
form_class = ComplainantForm
login_url = "/login/"
permission_required = "complaints.add_complainant"
def form_valid(self, form):
self.object, created = Complainant.objects.get_or_create(
**form.cleaned_data
)
return HttpResponseRedirect(
reverse(
'select_case',
args=[self.object.pk],
)
)
```
|
Do it in form's `clean` method:
```
from django.forms import ModelForm
from myapp.models import Car
class CarForm(ModelForm):
class Meta:
model = Car
def clean(self):
if self._meta.model.objects.filter(**self.cleaned_data).count() > 0:
raise forms.ValidationError('Car already exists')
return self.cleaned_data
```
|
52,138,300
|
I'm trying to write simple things in a Tkinter module using python 3.6 in Anaconda. This is my code
```
from tkinter import *
root = Tk()
thelabel = label(root, text="this is our tk window")
thelabel.pack()
root.mainloop()
```
but I get the error:
```
TclError: can't invoke "label" command: application has been destroyed
ERROR: execution aborted
```
and I keep getting a blank Tkinter window whenever I run my code and I don't understand what is the problem, thanks:)
|
2018/09/02
|
[
"https://Stackoverflow.com/questions/52138300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9784945/"
] |
One of the recommended ways to have multiple python installations with differing libraries installed is to use [Virtualenv](https://virtualenv.pypa.io/en/stable/). This gives you the possibility to have a specific python environment with it's own set of dependencies for each project you work on. This works not only for the dependencies, but also for different versions of python.
On top of that you can use [Pipenv](https://github.com/pypa/pipenv) to manage the different virtualenvs. In a `Pipfile` you can describe your required python and it's dependencies which is used by `Pipenv` to manage a python env specific for your project.
|
I found this to work after searching for a while. Here are the steps I followed to install an older python version alongside my standard one:
* Download the Python3.6 tgz file from the official website (eg. Python-3.6.6.tgz)
* Unpack it with `tar -xvzf Python-3.6.6.tgz`
* `cd Python-3.6.6`
* run `./configure`
* run `make altinstall` to install it (`install` vs `altinstall` explanation here [Difference in details between "make install" and "make altinstall"](https://stackoverflow.com/questions/16018463/difference-in-details-between-make-install-and-make-altinstall))
You'll normally find your new python install under `/usr/local/bin`. Now you can create a new virtualenv specifying the python version to use with:
* `virtualenv --python=python3.6 env3.6`
* Get into the virtualenv running the command `source env3.6/bin/activate`.
* Install tensorflow with the classic `pip3 install tensorflow`
* Profit
|
27,751,072
|
I have an ordinary Python list that contains (multidimensional) numPy arrays, all of the same shape and with the same number of values. Some of the arrays in the list are duplicates of earlier ones.
I have the problem that I want to remove all the duplicates, but the fact that the data type is numPy arrays complicates this a bit...
• I can't use set() as numPy arrays are not hashable.
• I can't check for duplicates during insertion, as the arrays are generated in batches by a function and added to the list with .extend().
• numPy arrays aren't directly comparable without resorting to one of numPy's own functions, so I can't just go something that uses "if x in list"...
• The contents of the list need to remain numPy arrays at the end of the process; I could compare copies of the arrays converted to nested lists, but I can't convert the arrays to straight python lists permanently.
Any suggestions on how I can remove duplicates efficiently here?
|
2015/01/03
|
[
"https://Stackoverflow.com/questions/27751072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541913/"
] |
Using the solutions here: [Most efficient property to hash for numpy array](https://stackoverflow.com/questions/16589791/most-efficient-property-to-hash-for-numpy-array) we see that hashing works best with a.tostring() if a is an numpy array. So:
```
import numpy as np
arraylist = [np.array([1,2,3,4]), np.array([1,2,3,4]), np.array([1,3,2,4])]
L = {array.tostring(): array for array in arraylist}
L.values() # [array([1, 3, 2, 4]), array([1, 2, 3, 4])]
```
|
Here is one way using `tuple`:
```
>>> import numpy as np
>>> t = [np.asarray([1, 2, 3, 4]),
np.asarray([1, 2, 3, 4]),
np.asarray([1, 1, 3, 4])]
>>> map(np.asarray, set(map(tuple, t)))
[array([1, 1, 3, 4]), array([1, 2, 3, 4])]
```
If your arrays are multidimensional, then first flatten them to a 1-by-whatever array, then use the same idea, and reshape them at the end:
```
def to_tuple(arr):
return tuple(arr.reshape((arr.size,)))
def from_tuple(tup, original_shape):
np.asarray(tup).reshape(original_shape)
```
Example:
```
In [64]: t = np.asarray([[[1,2,3],[4,5,6]],
[[1,1,3],[4,5,6]],
[[1,2,3],[4,5,6]]])
In [65]: map(lambda x: from_tuple(x, t[0].shape), set(map(to_tuple, t)))
Out[65]:
[array([[1, 2, 3],
[4, 5, 6]]),
array([[1, 1, 3],
[4, 5, 6]])]
```
Another option is to create a `pandas.DataFrame` out of your `ndarrays` (treating them as rows by reshaping if needed) and using the pandas built-ins for uniquifying the rows.
```
In [34]: t
Out[34]: [array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 1, 3, 4])]
In [35]: pandas.DataFrame(t).drop_duplicates().values
Out[35]:
array([[1, 2, 3, 4],
[1, 1, 3, 4]])
```
Overall, I think it's a bad idea to try to use `tostring()` as a quasi hash function, because you'll need more boiler plate code than in my approach just to protect against the possibility that some of the contents are mutated after they've been assigned their "hash" key in some `dict`.
If the reshaping and converting to `tuple` is too slow given the size of the data, my feeling is that this reveals a more fundamental problem: the application isn't designed well around the needs (like de-duping) and trying to cram them into some Python process running in memory is probably not the right way. At that point, I would stop to consider whether something like Cassandra, which can easily build database indices on top of large columns (or multidimensional arrays) of floating point (or other) data isn't the more sane approach.
|
27,751,072
|
I have an ordinary Python list that contains (multidimensional) numPy arrays, all of the same shape and with the same number of values. Some of the arrays in the list are duplicates of earlier ones.
I have the problem that I want to remove all the duplicates, but the fact that the data type is numPy arrays complicates this a bit...
• I can't use set() as numPy arrays are not hashable.
• I can't check for duplicates during insertion, as the arrays are generated in batches by a function and added to the list with .extend().
• numPy arrays aren't directly comparable without resorting to one of numPy's own functions, so I can't just go something that uses "if x in list"...
• The contents of the list need to remain numPy arrays at the end of the process; I could compare copies of the arrays converted to nested lists, but I can't convert the arrays to straight python lists permanently.
Any suggestions on how I can remove duplicates efficiently here?
|
2015/01/03
|
[
"https://Stackoverflow.com/questions/27751072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541913/"
] |
Using the solutions here: [Most efficient property to hash for numpy array](https://stackoverflow.com/questions/16589791/most-efficient-property-to-hash-for-numpy-array) we see that hashing works best with a.tostring() if a is an numpy array. So:
```
import numpy as np
arraylist = [np.array([1,2,3,4]), np.array([1,2,3,4]), np.array([1,3,2,4])]
L = {array.tostring(): array for array in arraylist}
L.values() # [array([1, 3, 2, 4]), array([1, 2, 3, 4])]
```
|
Depending on the structure of your data, it may be quicker to directly compare all the arrays rather than finding some way to hash the arrays. The algorithm is O(n^2), but each individual comparison wil be much quicker than creating strings or python lists of your arrays. So it depends how many arrays you have to check.
eg.
```
uniques = []
for arr in possible_duplicates:
if not any(numpy.array_equal(arr, unique_arr) for unique_arr in uniques):
uniques.append(arr)
```
|
27,751,072
|
I have an ordinary Python list that contains (multidimensional) numPy arrays, all of the same shape and with the same number of values. Some of the arrays in the list are duplicates of earlier ones.
I have the problem that I want to remove all the duplicates, but the fact that the data type is numPy arrays complicates this a bit...
• I can't use set() as numPy arrays are not hashable.
• I can't check for duplicates during insertion, as the arrays are generated in batches by a function and added to the list with .extend().
• numPy arrays aren't directly comparable without resorting to one of numPy's own functions, so I can't just go something that uses "if x in list"...
• The contents of the list need to remain numPy arrays at the end of the process; I could compare copies of the arrays converted to nested lists, but I can't convert the arrays to straight python lists permanently.
Any suggestions on how I can remove duplicates efficiently here?
|
2015/01/03
|
[
"https://Stackoverflow.com/questions/27751072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541913/"
] |
Depending on the structure of your data, it may be quicker to directly compare all the arrays rather than finding some way to hash the arrays. The algorithm is O(n^2), but each individual comparison wil be much quicker than creating strings or python lists of your arrays. So it depends how many arrays you have to check.
eg.
```
uniques = []
for arr in possible_duplicates:
if not any(numpy.array_equal(arr, unique_arr) for unique_arr in uniques):
uniques.append(arr)
```
|
Here is one way using `tuple`:
```
>>> import numpy as np
>>> t = [np.asarray([1, 2, 3, 4]),
np.asarray([1, 2, 3, 4]),
np.asarray([1, 1, 3, 4])]
>>> map(np.asarray, set(map(tuple, t)))
[array([1, 1, 3, 4]), array([1, 2, 3, 4])]
```
If your arrays are multidimensional, then first flatten them to a 1-by-whatever array, then use the same idea, and reshape them at the end:
```
def to_tuple(arr):
return tuple(arr.reshape((arr.size,)))
def from_tuple(tup, original_shape):
np.asarray(tup).reshape(original_shape)
```
Example:
```
In [64]: t = np.asarray([[[1,2,3],[4,5,6]],
[[1,1,3],[4,5,6]],
[[1,2,3],[4,5,6]]])
In [65]: map(lambda x: from_tuple(x, t[0].shape), set(map(to_tuple, t)))
Out[65]:
[array([[1, 2, 3],
[4, 5, 6]]),
array([[1, 1, 3],
[4, 5, 6]])]
```
Another option is to create a `pandas.DataFrame` out of your `ndarrays` (treating them as rows by reshaping if needed) and using the pandas built-ins for uniquifying the rows.
```
In [34]: t
Out[34]: [array([1, 2, 3, 4]), array([1, 2, 3, 4]), array([1, 1, 3, 4])]
In [35]: pandas.DataFrame(t).drop_duplicates().values
Out[35]:
array([[1, 2, 3, 4],
[1, 1, 3, 4]])
```
Overall, I think it's a bad idea to try to use `tostring()` as a quasi hash function, because you'll need more boiler plate code than in my approach just to protect against the possibility that some of the contents are mutated after they've been assigned their "hash" key in some `dict`.
If the reshaping and converting to `tuple` is too slow given the size of the data, my feeling is that this reveals a more fundamental problem: the application isn't designed well around the needs (like de-duping) and trying to cram them into some Python process running in memory is probably not the right way. At that point, I would stop to consider whether something like Cassandra, which can easily build database indices on top of large columns (or multidimensional arrays) of floating point (or other) data isn't the more sane approach.
|
36,278,220
|
I have a big third-party python2.7 application, a bunch of python scripts, which is added into `PATH` and it requires python2.7 instead of python 3.5 which I have by default.
```
$ python
Python 3.5.1 (default, Mar 3 2016, 09:29:07)
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python2
Python 2.7.11 (default, Mar 3 2016, 11:00:04)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I run that application as `$ some_app arg1 arg2`. How can make it use python2 as a temporary solution, preferably only in that single terminal window?
I don't substitute a call of that application with "python". I call it like `$ some_app arg1 arg2`. I don't want to change the version of python permanently or modify the source code of the application.
|
2016/03/29
|
[
"https://Stackoverflow.com/questions/36278220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708058/"
] |
My favorite way: use virtualenv or pyenv
========================================
The most used tool for keeping multiple Python environments is [virtualenv](https://virtualenv.pypa.io/en/latest/). I like to use a sugary wrapper around it called [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/).
Usually I install it using:
```
sudo pip install virtualenvwrapper
```
Then I add a line like the following one to my shell profile:
```
source /usr/local/bin/virtualenvwrapper.sh
```
Now you can make a virtual environment for each version of Python. Gosh, you can make one for each Python project!
```
mkvirtualenv py3
mkvirtualenv py2 --python=python2
```
Then you can switch temporarily to python2 by typing:
```
workon py2
```
There is another tool called [pyenv](https://github.com/yyuu/pyenv) that lets you easily switch between multiple versions of Python. Quoting the project readme, "It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well. This project was forked from rbenv and ruby-build, and modified for Python". Looks like it is getting popular.
Both are elegant, easy to use and a perfect fit for this use case (switch to a particular python version in a terminal window temporarily).
The Unix way: set `$PATH`
=========================
It is a best practice to write the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) for Python scripts like:
```
#!/usr/bin/env python
```
If the 3rd-party app you are running follows this convention, you can change the PATH. For example, suppose the default python interpreter is not the one you want:
```
$ env python --version
Python 3.5.1
```
Make a local copy of the python you want to make the default temporarily (you just have to do this one time):
```
$ mkdir ~/local
$ mkdir ~/local/python2
$ ln -s `which python2` ~/local/python2/python
```
Then every time you want to make python2 the default, do:
```
$ export PATH=~/local/python2/:$PATH
```
Now the default is the version you want:
```
$ env python --version
Python 2.7.10
```
The positive karma way: if the 3rd-party app has a hardcoded path in the shebang
================================================================================
Perhaps the app author did not follow the best practices and hardcoded the Python path in the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)). For example, suppose the first line of the program is:
```
#!/usr/bin/python
```
In this case, none of the previous tricks would work. Personally, I would change it to the canonical form and send a pull request to the author of the 3rd-party app.
The bossy way: change the default Python version system-wide
============================================================
While this does not really answer your question - because it affects every window and avery other user in the system - I'm mentioning it for the sake of completeness.
For example, if you are using Ubuntu you can change the default python interpreter using:
```
$ update-alternatives --config python
```
Other Linux distributions probably have something like this.
Quick and dirty
===============
The [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) just tells the shell to call the script using the given interpreter. You can override the shebang when calling the app as `interpreter app`:
```
$ python2 `which app_name`
```
Or:
```
$ python2 /path/to/app_name
```
You can also just edit the program and change the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)):
```
#!/usr/bin/python2
```
Note that this would change permanently the Python interpreter for that program, it is not temporary nor restricted to a particular terminal. Worst, if the program is in the global PATH, all the other users of the system will be affected. If you want to restore the old behavior, you must undo your changes.
That said, sometimes you just don't care about doing it right, you just want to make it work.
|
You can make use of terminal alias. **The alias will not be temporary** but it will not affect your system, so you can have a short alias like:
**alias pyt "/usr/bin/python2.7"**
in your .bashrc file inside home directory
|
36,278,220
|
I have a big third-party python2.7 application, a bunch of python scripts, which is added into `PATH` and it requires python2.7 instead of python 3.5 which I have by default.
```
$ python
Python 3.5.1 (default, Mar 3 2016, 09:29:07)
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python2
Python 2.7.11 (default, Mar 3 2016, 11:00:04)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I run that application as `$ some_app arg1 arg2`. How can make it use python2 as a temporary solution, preferably only in that single terminal window?
I don't substitute a call of that application with "python". I call it like `$ some_app arg1 arg2`. I don't want to change the version of python permanently or modify the source code of the application.
|
2016/03/29
|
[
"https://Stackoverflow.com/questions/36278220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708058/"
] |
My favorite way: use virtualenv or pyenv
========================================
The most used tool for keeping multiple Python environments is [virtualenv](https://virtualenv.pypa.io/en/latest/). I like to use a sugary wrapper around it called [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/).
Usually I install it using:
```
sudo pip install virtualenvwrapper
```
Then I add a line like the following one to my shell profile:
```
source /usr/local/bin/virtualenvwrapper.sh
```
Now you can make a virtual environment for each version of Python. Gosh, you can make one for each Python project!
```
mkvirtualenv py3
mkvirtualenv py2 --python=python2
```
Then you can switch temporarily to python2 by typing:
```
workon py2
```
There is another tool called [pyenv](https://github.com/yyuu/pyenv) that lets you easily switch between multiple versions of Python. Quoting the project readme, "It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well. This project was forked from rbenv and ruby-build, and modified for Python". Looks like it is getting popular.
Both are elegant, easy to use and a perfect fit for this use case (switch to a particular python version in a terminal window temporarily).
The Unix way: set `$PATH`
=========================
It is a best practice to write the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) for Python scripts like:
```
#!/usr/bin/env python
```
If the 3rd-party app you are running follows this convention, you can change the PATH. For example, suppose the default python interpreter is not the one you want:
```
$ env python --version
Python 3.5.1
```
Make a local copy of the python you want to make the default temporarily (you just have to do this one time):
```
$ mkdir ~/local
$ mkdir ~/local/python2
$ ln -s `which python2` ~/local/python2/python
```
Then every time you want to make python2 the default, do:
```
$ export PATH=~/local/python2/:$PATH
```
Now the default is the version you want:
```
$ env python --version
Python 2.7.10
```
The positive karma way: if the 3rd-party app has a hardcoded path in the shebang
================================================================================
Perhaps the app author did not follow the best practices and hardcoded the Python path in the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)). For example, suppose the first line of the program is:
```
#!/usr/bin/python
```
In this case, none of the previous tricks would work. Personally, I would change it to the canonical form and send a pull request to the author of the 3rd-party app.
The bossy way: change the default Python version system-wide
============================================================
While this does not really answer your question - because it affects every window and avery other user in the system - I'm mentioning it for the sake of completeness.
For example, if you are using Ubuntu you can change the default python interpreter using:
```
$ update-alternatives --config python
```
Other Linux distributions probably have something like this.
Quick and dirty
===============
The [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) just tells the shell to call the script using the given interpreter. You can override the shebang when calling the app as `interpreter app`:
```
$ python2 `which app_name`
```
Or:
```
$ python2 /path/to/app_name
```
You can also just edit the program and change the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)):
```
#!/usr/bin/python2
```
Note that this would change permanently the Python interpreter for that program, it is not temporary nor restricted to a particular terminal. Worst, if the program is in the global PATH, all the other users of the system will be affected. If you want to restore the old behavior, you must undo your changes.
That said, sometimes you just don't care about doing it right, you just want to make it work.
|
As the question is tagged with Linux, I assume your scripts starts with that line
```
#! /usr/bin/env python
```
This is great to allow the system to choose the current Python installation, but here your requirement is to specifically use version 2.7
So IMHO you just have to change the hashbang line to select the required version:
```
#! /path/to/python-2.7
```
|
36,278,220
|
I have a big third-party python2.7 application, a bunch of python scripts, which is added into `PATH` and it requires python2.7 instead of python 3.5 which I have by default.
```
$ python
Python 3.5.1 (default, Mar 3 2016, 09:29:07)
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ python2
Python 2.7.11 (default, Mar 3 2016, 11:00:04)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
I run that application as `$ some_app arg1 arg2`. How can make it use python2 as a temporary solution, preferably only in that single terminal window?
I don't substitute a call of that application with "python". I call it like `$ some_app arg1 arg2`. I don't want to change the version of python permanently or modify the source code of the application.
|
2016/03/29
|
[
"https://Stackoverflow.com/questions/36278220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1708058/"
] |
My favorite way: use virtualenv or pyenv
========================================
The most used tool for keeping multiple Python environments is [virtualenv](https://virtualenv.pypa.io/en/latest/). I like to use a sugary wrapper around it called [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/).
Usually I install it using:
```
sudo pip install virtualenvwrapper
```
Then I add a line like the following one to my shell profile:
```
source /usr/local/bin/virtualenvwrapper.sh
```
Now you can make a virtual environment for each version of Python. Gosh, you can make one for each Python project!
```
mkvirtualenv py3
mkvirtualenv py2 --python=python2
```
Then you can switch temporarily to python2 by typing:
```
workon py2
```
There is another tool called [pyenv](https://github.com/yyuu/pyenv) that lets you easily switch between multiple versions of Python. Quoting the project readme, "It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well. This project was forked from rbenv and ruby-build, and modified for Python". Looks like it is getting popular.
Both are elegant, easy to use and a perfect fit for this use case (switch to a particular python version in a terminal window temporarily).
The Unix way: set `$PATH`
=========================
It is a best practice to write the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) for Python scripts like:
```
#!/usr/bin/env python
```
If the 3rd-party app you are running follows this convention, you can change the PATH. For example, suppose the default python interpreter is not the one you want:
```
$ env python --version
Python 3.5.1
```
Make a local copy of the python you want to make the default temporarily (you just have to do this one time):
```
$ mkdir ~/local
$ mkdir ~/local/python2
$ ln -s `which python2` ~/local/python2/python
```
Then every time you want to make python2 the default, do:
```
$ export PATH=~/local/python2/:$PATH
```
Now the default is the version you want:
```
$ env python --version
Python 2.7.10
```
The positive karma way: if the 3rd-party app has a hardcoded path in the shebang
================================================================================
Perhaps the app author did not follow the best practices and hardcoded the Python path in the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)). For example, suppose the first line of the program is:
```
#!/usr/bin/python
```
In this case, none of the previous tricks would work. Personally, I would change it to the canonical form and send a pull request to the author of the 3rd-party app.
The bossy way: change the default Python version system-wide
============================================================
While this does not really answer your question - because it affects every window and avery other user in the system - I'm mentioning it for the sake of completeness.
For example, if you are using Ubuntu you can change the default python interpreter using:
```
$ update-alternatives --config python
```
Other Linux distributions probably have something like this.
Quick and dirty
===============
The [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) just tells the shell to call the script using the given interpreter. You can override the shebang when calling the app as `interpreter app`:
```
$ python2 `which app_name`
```
Or:
```
$ python2 /path/to/app_name
```
You can also just edit the program and change the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)):
```
#!/usr/bin/python2
```
Note that this would change permanently the Python interpreter for that program, it is not temporary nor restricted to a particular terminal. Worst, if the program is in the global PATH, all the other users of the system will be affected. If you want to restore the old behavior, you must undo your changes.
That said, sometimes you just don't care about doing it right, you just want to make it work.
|
If you are using Anaconda as your Python distribution, it has virtual enviroments built in. If not, use `virtualenv` and `virtualenvwrapper` as Paul recommended.
In addition I recommend `autoenv`. With that you can automatically change your venv depending on the folder you're in. There is one for bash and one for zsh.
|
42,128,830
|
I am trying a simple demo code of tensorflow from [github link](https://github.com/llSourcell/tensorflow_demo).
I'm currently using python version 3.5.2
```
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py Python
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32<br> Type "help", "copyright", "credits" or "license" for more information.
```
I ran into this error when I tried board.py in command-line. I have installed all the dependencies that are required for this to run.
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
def extract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
(magic, filename))
num_images = _read32(bytestream)
rows = _read32(bytestream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py board.py
Extracting Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
Traceback (most recent call last):
File "board.py", line 3, in <module>
mnist = input_data.read_data_sets(r'Z:/downloads/MNIST dataset', one_hot=True)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 150, in read_data_sets
train_images = extract_images(local_file)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 40, in extract_images
buf = bytestream.read(rows * cols * num_images)
File "C:\Users\surak\AppData\Local\Programs\Python\Python35\lib\gzip.py", line 274, in read
return self._buffer.read(size)
TypeError: only integer scalar arrays can be converted to a scalar index
```
|
2017/02/09
|
[
"https://Stackoverflow.com/questions/42128830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6833276/"
] |
The code link you have provided uses a separate file named `input_data.py` to download data from MNIST using the following two lines in `board.py`
```
import input_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=True)
```
Since MNIST data is so frequently used for demonstration purposes, Tensorflow provides a way to automatically download it.
Replace the above two lines in `board.py` with the following two lines and the error will disappear.
```
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
```
|
This file is likely corrupt:
```
Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
```
Let's analyze the error you posted.
This, indicates that code is currently working with the file in question:
```
Extracting Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
```
`Traceback` indicates that a stack trace follows:
```
Traceback (most recent call last):
```
This, indicates that you read your data sets from `'Z:/downloads/MNIST dataset'`:
```
File "board.py", line 3, in <module>
mnist = input_data.read_data_sets(r'Z:/downloads/MNIST dataset', one_hot=True)
```
This, indicates that the code is extracting images:
```
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 150, in read_data_sets
train_images = extract_images(local_file)
```
This, indicates that the code is expected to read `rows * cols * num_images` bytes:
```
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 40, in extract_images
buf = bytestream.read(rows * cols * num_images)
```
This is the line that errors:
```
File "C:\Users\surak\AppData\Local\Programs\Python\Python35\lib\gzip.py", line 274, in read
return self._buffer.read(size)
TypeError: only integer scalar arrays can be converted to a scalar index
```
I expect `size` is the problematic value and was calculated on the previous line of the stacktrace.
I can see at least two ways to proceed.
1. Delete the offending file and see if the problem goes away. This would allow you to verify that the file is somehow corrupt.
2. Use a debugger to step into the code and then inspect the values used to calculate the offending variable. Use the knowledge gained to proceed from there.
|
42,128,830
|
I am trying a simple demo code of tensorflow from [github link](https://github.com/llSourcell/tensorflow_demo).
I'm currently using python version 3.5.2
```
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py Python
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32<br> Type "help", "copyright", "credits" or "license" for more information.
```
I ran into this error when I tried board.py in command-line. I have installed all the dependencies that are required for this to run.
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
def extract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
(magic, filename))
num_images = _read32(bytestream)
rows = _read32(bytestream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py board.py
Extracting Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
Traceback (most recent call last):
File "board.py", line 3, in <module>
mnist = input_data.read_data_sets(r'Z:/downloads/MNIST dataset', one_hot=True)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 150, in read_data_sets
train_images = extract_images(local_file)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 40, in extract_images
buf = bytestream.read(rows * cols * num_images)
File "C:\Users\surak\AppData\Local\Programs\Python\Python35\lib\gzip.py", line 274, in read
return self._buffer.read(size)
TypeError: only integer scalar arrays can be converted to a scalar index
```
|
2017/02/09
|
[
"https://Stackoverflow.com/questions/42128830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6833276/"
] |
you can modify the function:
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
```
new version:
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
```
add `[0]` in the end.
This appears to be an issue with the latest version of Numpy. A recent change made it an error to treat a single-element array as a scalar for the purposes of indexing.
|
This file is likely corrupt:
```
Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
```
Let's analyze the error you posted.
This, indicates that code is currently working with the file in question:
```
Extracting Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
```
`Traceback` indicates that a stack trace follows:
```
Traceback (most recent call last):
```
This, indicates that you read your data sets from `'Z:/downloads/MNIST dataset'`:
```
File "board.py", line 3, in <module>
mnist = input_data.read_data_sets(r'Z:/downloads/MNIST dataset', one_hot=True)
```
This, indicates that the code is extracting images:
```
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 150, in read_data_sets
train_images = extract_images(local_file)
```
This, indicates that the code is expected to read `rows * cols * num_images` bytes:
```
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 40, in extract_images
buf = bytestream.read(rows * cols * num_images)
```
This is the line that errors:
```
File "C:\Users\surak\AppData\Local\Programs\Python\Python35\lib\gzip.py", line 274, in read
return self._buffer.read(size)
TypeError: only integer scalar arrays can be converted to a scalar index
```
I expect `size` is the problematic value and was calculated on the previous line of the stacktrace.
I can see at least two ways to proceed.
1. Delete the offending file and see if the problem goes away. This would allow you to verify that the file is somehow corrupt.
2. Use a debugger to step into the code and then inspect the values used to calculate the offending variable. Use the knowledge gained to proceed from there.
|
42,128,830
|
I am trying a simple demo code of tensorflow from [github link](https://github.com/llSourcell/tensorflow_demo).
I'm currently using python version 3.5.2
```
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py Python
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32<br> Type "help", "copyright", "credits" or "license" for more information.
```
I ran into this error when I tried board.py in command-line. I have installed all the dependencies that are required for this to run.
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
def extract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
(magic, filename))
num_images = _read32(bytestream)
rows = _read32(bytestream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
Z:\downloads\tensorflow_demo-master\tensorflow_demo-master>py board.py
Extracting Z:/downloads/MNIST dataset\train-images-idx3-ubyte.gz
Traceback (most recent call last):
File "board.py", line 3, in <module>
mnist = input_data.read_data_sets(r'Z:/downloads/MNIST dataset', one_hot=True)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 150, in read_data_sets
train_images = extract_images(local_file)
File "Z:\downloads\tensorflow_demo-master\tensorflow_demo-master\input_data.py", line 40, in extract_images
buf = bytestream.read(rows * cols * num_images)
File "C:\Users\surak\AppData\Local\Programs\Python\Python35\lib\gzip.py", line 274, in read
return self._buffer.read(size)
TypeError: only integer scalar arrays can be converted to a scalar index
```
|
2017/02/09
|
[
"https://Stackoverflow.com/questions/42128830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6833276/"
] |
you can modify the function:
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
```
new version:
```
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
```
add `[0]` in the end.
This appears to be an issue with the latest version of Numpy. A recent change made it an error to treat a single-element array as a scalar for the purposes of indexing.
|
The code link you have provided uses a separate file named `input_data.py` to download data from MNIST using the following two lines in `board.py`
```
import input_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=True)
```
Since MNIST data is so frequently used for demonstration purposes, Tensorflow provides a way to automatically download it.
Replace the above two lines in `board.py` with the following two lines and the error will disappear.
```
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
```
|
64,785,224
|
How can I remove keys from python dictionary of dictionaries based on some conditions?
Example dictionary:
```
a = {
'k': 'abc',
'r': 20,
'c': {
'd': 'pppq',
'e': 22,
'g': 75
},
'f': ''}
```
I want to remove all entries whose values are type of string. It can contain dictionary for any key. Nested key value pairs should also be handled.
|
2020/11/11
|
[
"https://Stackoverflow.com/questions/64785224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3056288/"
] |
You could do:
```
a = {
'k': 'abc',
'r': 20,
'c': {
'd': 'pppq',
'e': 22,
'g': 75
},
'f': ''}
def remove_string_values(d):
result = {}
for k, v in d.items():
if not isinstance(v, str):
result[k] = remove_string_values(v) if isinstance(v, dict) else v
return result
res = remove_string_values(a)
print(res)
```
**Output**
```
{'r': 20, 'c': {'e': 22, 'g': 75}}
```
|
Something like this should work:
```
def remove_strings(a):
no_strings = {}
for k,v in a.items():
if type(x) is str:
continue
elif type(x) is dict:
no_strings[k] = remove_strings(v)
else:
no_strings[k] = v
```
This function is recursive - it calls itself to process nested dictionaries.
It should be possible to remove the keys in-place (without copying the dictionary), but the code would be a bit less readable that way.
|
12,006,267
|
So I can create Django model like this:
```
from django.db import models
class Something(models.Model):
title = models.TextField(max_length=200)
```
and I can work with it like this:
```
thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title
```
All works as it should but I'd like to understand HOW it works.
```
title = models.TextField(max_length=200)
```
in non-Django Python code above line defines class variable title of type models.TextField and I could access it also like this: `thing.__class__.title`([link](http://getpython3.com/diveintopython3/iterators.html#a-plural-rule-iterator))
But in Django when I create instance of Something I suddenly have a title attribute where I can get/set text. And cannot access it with `thing.__class__.title` So clearly when doing thing.title I'm not accessing class variable "title" but some generated attribute/property, or?
I know that fields ended up in thing.\_meta.fields but how? **What's going on and how?**
1, Does Django create property "title" behind the scenes?
2, What happened to class variable "title"?
|
2012/08/17
|
[
"https://Stackoverflow.com/questions/12006267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3272/"
] |
I think its hard to beat what Django documentation has to [say on this](https://code.djangoproject.com/wiki/DevModelCreation).
>
> The Model class (see base.py) has a **metaclass** attribute that defines ModelBase (also in base.py) as the class to use for creating new classes. So ModelBase.**new** is called to create this new Example class. It is important to realise that we are creating the class object here, not an instance of it. In other words, Python is creating the thing that will eventually be bound to the Example name in our current namespace.
>
>
>
Basically a [metaclass](http://en.wikipedia.org/wiki/Metaclass#Python_example) defines how a class itself will be created. During creation, additional attributes/methods/anything can be bound to that class. The example this [stackoverflow answer](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) gives, capitalizes all the attributes of a class
```
# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
# __new__ is the method called before __init__
# it's the method that creates the object and returns it
# while __init__ just initializes the object passed as parameter
# you rarely use __new__, except when you want to control how the object
# is created.
# here the created object is the class, and we want to customize it
# so we override __new__
# you can do some stuff in __init__ too if you wish
# some advanced use involves overriding __call__ as well, but we won't
# see this
def __new__(upperattr_metaclass, future_class_name,
future_class_parents, future_class_attr):
attrs = ((name, value) for name, value in future_class_attr.items() if not name.startswith('__'))
uppercase_attr = dict((name.upper(), value) for name, value in attrs)
return type(future_class_name, future_class_parents, uppercase_attr)
```
In a similar way, Django's metaclass for Models can digest the attributes you've applied to the class and add various useful attributes for validation/etc, including even methods and what-not.
|
python is extremely powerfull and permit the developer to use intrespection.
django use a lot of metaclass. and it seem that models.Model use it too. see in
django\db\models\base.py
```
class Model(object):
__metaclass__ = ModelBase
```
i think the metaclass just take the classes attributes such a the Field and for all new instance for these Model subclass,create the apropriate variable.
1) yes, django create the instance variable of property "title" automaticaly
2) in the same way, the metaclass move the fields into the meta class...
|
64,694,569
|
aws cdk returns jsii error on empty stack. Steps to reproduce are at the hello world level which makes me think that I have a version mismatch somewhere. I have re-installed aws cli, cdk and nodejs. Any suggestions on what to look for?
Steps to reproduce:
```
mkdir myfolder
cdk init --language python
.env\Scripts\activate.ps1
python -m pip install -r requirements.txt
cdk synth
```
Returns error AND an empty stack:
```
(.env) p$[myfolder]> cdk synth d:\myfolder\.env\lib\site-packages\jsii\_embedded\jsii\jsii-runtime.js:13295
throw e;
^
Error: EOF: end of file, read
at Object.readSync (fs.js:592:3)
at SyncStdio.readLine (d:\myfolder\.env\lib\site-packages\jsii\_embedded\jsii\jsii-runtime.js:13278:33)
at InputOutput.read (d:\myfolder\.env\lib\site-packages\jsii\_embedded\jsii\jsii-runtime.js:13203:34)
at KernelHost.run (d:\myfolder\.env\lib\site-packages\jsii\_embedded\jsii\jsii-runtime.js:13021:32)
at Immediate.<anonymous> (d:\myfolder\.env\lib\site-packages\jsii\_embedded\jsii\jsii-runtime.js:13029:37)
at processImmediate (internal/timers.js:461:21) {
errno: -4095,
syscall: 'read',
code: 'EOF'
}
Resources:
CDKMetadata:
Type: AWS::CDK::Metadata
Properties:
Modules: aws-cdk=1.69.0,@aws-cdk/cloud-assembly-schema=1.69.0,@aws-cdk/core=1.69.0,@aws-cdk/cx-api=1.69.0,@aws-cdk/region-info=1.69.0,jsii-runtime=Python/3.7.4
Metadata:
aws:cdk:path: myfolder/CDKMetadata/Default
Condition: CDKMetadataAvailable
```
Environment
```
- **CLI Version :aws-cli/2.0.61 Python/3.7.7 Windows/10 exe/AMD64
- **cdk Version:1.69.0 (build 2b474b9)
- **Node.js Version:v14.15.0
- **OS :Windows 10
- **Language (Version):python 3.7.4
```
Saw this error when I first started on cdk. But, 'cdk synth' showed a stack, so I pressed on. I was even able to 'cdk deploy' simple stacks. Eventually, as the code became only slightly more complex, jsii errors prevent stack creation. Code created by me throws errors on my machine but does NOT error on other machines. Working cdk code from other devs will not synth or deploy stacks on my machine.
So far, I have re-installed aws cli, node.js and cdk. Any ideas where the jsii error originate or how to fix them?
|
2020/11/05
|
[
"https://Stackoverflow.com/questions/64694569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14582438/"
] |
For AWS-CDK on Windows, there is at least one bug in jsii documented by AWS CDK group. Deep inside the jsiiruntime (line 13278 to be exact), aws cdk group has a comment with a link to a nodejs bug report. I reported my problem to aws-cdk which seemed to be related. They reproduced the bug and created a bug report at nodejs. This bug report has links to the other bug reports. <https://github.com/aws/aws-cdk/issues/11314>
But I still needed a workaround. After much trial and error, the following 2 workarounds should work for AWS-CDK on Windows.
**Workaround 1:** replace jsii 1.14.x distro in site-packages with 1.12 or 1.13 distro. After swapping out 1.14 for 1.12 or 1.13, errors stop. Getting a distro is a trick. You will have to get one from someone who has not upgraded or run pip -- which what I did.
**Workaround 2:** move dev environment off Windows and onto linux or mac
|
TL;DR. Expanded work arounds. (A question was asked in the AWS-CDK bug report noted above).
**Workaround 1: replace jsii 1.14.x distro**
***Distro folders:*** jsii is contained in 2 folders
jsii and jsii-1.14.1.dist-info
REPLACE both of these folders with folders from an older install -- 1.12 or 1.13.
The distro folders can be found in one or both of the following locations:
***Distro location virtual environment:*** jsii distro will be found in the **site-packages** directory. Example:
.env\lib\python3.8\site-packages
where virtual environment name = .env, python version = 3.8
***Distro location non-virtual:*** This should be the location if you have not created a virtual environment. Note that, again, the python version is part of the path.
C:\Program Files\Python37\Lib\site-packages
Note: for some reason, they were not installed here. But, that may change, so keep this in mind.
C:\Users\yourusername\AppData\Roaming\Python\Python37\site-packages
**Workaround 2: move to linux**
In windows, install WSL 2.
Install Ubuntu or your favorite linux variety.
Install python
Use your favorite Windows IDE from Windows! I use Visual Studio Code. Requires installing an extension if I remember correctly.
WARNING: I had problems when trying to run python, cdk, etc where the files were on the Windows system (ex: /mnt/d/project). Just copy the repo to the "pure" linux file system ( ex: ~/project). I have git installed on the linux side and maintain my files as if it were a separate machine.
|
11,661,053
|
I am running Windows 7 currently, and I remember when using Linux at the school computers I was able to type "gedit &" into the terminal for example to open up the gedit text editor. I was wondering whether there is a similar process to open IDLE, and for that matter a Python program/script by typing it into the "terminal-equivalent." I'm a complete newbie, so I may be off-base a bit...anyways, so there is this terminal-like program called python.exe, and it seems like it should be able to open Python-related software (like IDLE), and I was wondering 1) what python.exe is for, 2) whether it can be treated like a Linux terminal, and 3) how to do stuff in it. I've tried various commands and I get a syntax error for virtually everything. Much appreciated!
|
2012/07/26
|
[
"https://Stackoverflow.com/questions/11661053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553212/"
] |
python.exe is the Python interpreter. All of your Python programs are executed with it. If you run it in the console, you will get an interactive prompt:
```
C:\> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
If you give it a Python program, it will run it:
```
C:\> python myprog.py
```
You can also ask it to run an importable module:
```
C:\> python -m modulename
```
You can run IDLE this way:
```
C:\> python -m idlelib.idle
```
|
python.exe **is** Python, the python interpreter specifically.
|
11,661,053
|
I am running Windows 7 currently, and I remember when using Linux at the school computers I was able to type "gedit &" into the terminal for example to open up the gedit text editor. I was wondering whether there is a similar process to open IDLE, and for that matter a Python program/script by typing it into the "terminal-equivalent." I'm a complete newbie, so I may be off-base a bit...anyways, so there is this terminal-like program called python.exe, and it seems like it should be able to open Python-related software (like IDLE), and I was wondering 1) what python.exe is for, 2) whether it can be treated like a Linux terminal, and 3) how to do stuff in it. I've tried various commands and I get a syntax error for virtually everything. Much appreciated!
|
2012/07/26
|
[
"https://Stackoverflow.com/questions/11661053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553212/"
] |
python.exe is the Python interpreter. All of your Python programs are executed with it. If you run it in the console, you will get an interactive prompt:
```
C:\> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
If you give it a Python program, it will run it:
```
C:\> python myprog.py
```
You can also ask it to run an importable module:
```
C:\> python -m modulename
```
You can run IDLE this way:
```
C:\> python -m idlelib.idle
```
|
Yes you can start libraries like Idle, you need to import idlelib:
```
import idlelib.idle
```
Alternatively, to start idle from terminal without getting into python.exe shell first, you can do python.exe -m idlelib.idle assuming that idlelib is in your PYTHONPATH
The python.exe, is just like the shell in IDLE, is mainly used for quick experimentation with algorithms you want to try or testing library calls or language features, when you don't want to open a new file for that purpose. There are similarities with Linux shells like bash, but python's shell are heavily oriented for aiding programming while Linux shell are heavily oriented for starting up other programs. While you can start other programs in python's shell using subprocess.Popen and while bash do have it's own scripting language, they are very different.
|
11,661,053
|
I am running Windows 7 currently, and I remember when using Linux at the school computers I was able to type "gedit &" into the terminal for example to open up the gedit text editor. I was wondering whether there is a similar process to open IDLE, and for that matter a Python program/script by typing it into the "terminal-equivalent." I'm a complete newbie, so I may be off-base a bit...anyways, so there is this terminal-like program called python.exe, and it seems like it should be able to open Python-related software (like IDLE), and I was wondering 1) what python.exe is for, 2) whether it can be treated like a Linux terminal, and 3) how to do stuff in it. I've tried various commands and I get a syntax error for virtually everything. Much appreciated!
|
2012/07/26
|
[
"https://Stackoverflow.com/questions/11661053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553212/"
] |
Yes you can start libraries like Idle, you need to import idlelib:
```
import idlelib.idle
```
Alternatively, to start idle from terminal without getting into python.exe shell first, you can do python.exe -m idlelib.idle assuming that idlelib is in your PYTHONPATH
The python.exe, is just like the shell in IDLE, is mainly used for quick experimentation with algorithms you want to try or testing library calls or language features, when you don't want to open a new file for that purpose. There are similarities with Linux shells like bash, but python's shell are heavily oriented for aiding programming while Linux shell are heavily oriented for starting up other programs. While you can start other programs in python's shell using subprocess.Popen and while bash do have it's own scripting language, they are very different.
|
python.exe **is** Python, the python interpreter specifically.
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
The `b` inside `func_1()` is local to the function and not available outside of the function. You need to *assign* the returned value of the function `func_1()` to a variable name in the main body.
```
b = func_1()
print b
```
|
>
> I am 'expecting' b to be available after the function call, as I have returned it
>
>
>
The fundamental misunderstanding: you aren't returning a variable, you're returning a value. Variables are labels (names) for values. Inside the function, you have a name `b` for a value `"foo"`. You use this name to refer to the value, so that you can return it.
On the outside, to use this value, you must do something with it. The call to the function - `func_1()` - is a stand-in, in whatever expression contains it, for the value that gets returned. So a line of code like `func_1()`, by itself, does nothing visible: you have an expression that evaluates to `"foo"`, but then nothing is done with `"foo"`.
You could, for example, `print(func_1())` to display the string. You can assign the returned value to another variable: `c = func_1()`. Now `c` is a name for the `"foo"` value that was returned. You can use the function call as part of a larger expression: `c = func_1() + "bar"` - now `c` is a name for a string `"foobar"`, created by joining together the string returned from the function with the directly-specified one.
On the other side: to get information **into** the function, you should pass it as a parameter. These are the values that go inside the parentheses: when you write the function, you put argument names (another kind of variable) inside the parentheses, and when you call the function, you put the parameters that you are calling the function with (expressions that provide the values). Now, inside the function, each time it is called, the arguments will refer to the parameter values.
Let us work a simple example. We will make a function that appends "bar" to an input string, and call it a few times.
```
def add_bar(to):
return to + "bar"
```
Notice how we can return any expression. When the function is called, the expression is evaluated, joining the passed-in argument string `to` to the constant `"bar"`, and the resulting value is returned. There is no variable here that represents the entire return value, because again, we are returning a value, not a variable.
Now we may call this. Again, the parameter can be whatever expression - so a constant:
```
add_bar("foo")
```
or a variable that we have previously assigned a value:
```
my_string = "sand"
add_bar(my_string)
```
or something more complex, maybe even involving another call to the function:
```
add_bar(add_bar("bar ") + " ")
```
But again, none of these will actually do anything, except produce the string and then throw it away. So let's fix that:
```
print("I want a " + add_bar("chocolate") + ".")
```
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
I think this is what you want to do:
```
a = "foo"
def func_1():
b = "bar"
print a,b
return b # Took out parenthasis
returned_b = func_1() # Added variable to hold the returned "b"
print returned_b
```
It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular.
A couple of other things.
In the line `a = "foo"`, a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular).
It looks like you are having trouble understanding an aspect of how variables work called 'scope'. When you declared the variable `b` inside of `func_1()`, it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been called `b`.
I'm not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration.
Here is an example of how a "normal" program might be set up:
```
def main(): # Calling main() "runs" the program
a = add(1,2)
print a
def add(first, second): # functions are normally declared outside of other functions,
result = first + second # that way, they can be used anywhere
return result
```
|
>
> I am 'expecting' b to be available after the function call, as I have returned it
>
>
>
The fundamental misunderstanding: you aren't returning a variable, you're returning a value. Variables are labels (names) for values. Inside the function, you have a name `b` for a value `"foo"`. You use this name to refer to the value, so that you can return it.
On the outside, to use this value, you must do something with it. The call to the function - `func_1()` - is a stand-in, in whatever expression contains it, for the value that gets returned. So a line of code like `func_1()`, by itself, does nothing visible: you have an expression that evaluates to `"foo"`, but then nothing is done with `"foo"`.
You could, for example, `print(func_1())` to display the string. You can assign the returned value to another variable: `c = func_1()`. Now `c` is a name for the `"foo"` value that was returned. You can use the function call as part of a larger expression: `c = func_1() + "bar"` - now `c` is a name for a string `"foobar"`, created by joining together the string returned from the function with the directly-specified one.
On the other side: to get information **into** the function, you should pass it as a parameter. These are the values that go inside the parentheses: when you write the function, you put argument names (another kind of variable) inside the parentheses, and when you call the function, you put the parameters that you are calling the function with (expressions that provide the values). Now, inside the function, each time it is called, the arguments will refer to the parameter values.
Let us work a simple example. We will make a function that appends "bar" to an input string, and call it a few times.
```
def add_bar(to):
return to + "bar"
```
Notice how we can return any expression. When the function is called, the expression is evaluated, joining the passed-in argument string `to` to the constant `"bar"`, and the resulting value is returned. There is no variable here that represents the entire return value, because again, we are returning a value, not a variable.
Now we may call this. Again, the parameter can be whatever expression - so a constant:
```
add_bar("foo")
```
or a variable that we have previously assigned a value:
```
my_string = "sand"
add_bar(my_string)
```
or something more complex, maybe even involving another call to the function:
```
add_bar(add_bar("bar ") + " ")
```
But again, none of these will actually do anything, except produce the string and then throw it away. So let's fix that:
```
print("I want a " + add_bar("chocolate") + ".")
```
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
I think this is what you want to do:
```
a = "foo"
def func_1():
b = "bar"
print a,b
return b # Took out parenthasis
returned_b = func_1() # Added variable to hold the returned "b"
print returned_b
```
It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular.
A couple of other things.
In the line `a = "foo"`, a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular).
It looks like you are having trouble understanding an aspect of how variables work called 'scope'. When you declared the variable `b` inside of `func_1()`, it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been called `b`.
I'm not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration.
Here is an example of how a "normal" program might be set up:
```
def main(): # Calling main() "runs" the program
a = add(1,2)
print a
def add(first, second): # functions are normally declared outside of other functions,
result = first + second # that way, they can be used anywhere
return result
```
|
Function calls are expressions. Like any expression they have a value. If you don't assign the value to anything, it is lost.
```
def add(a, b):
result = a + b
return result
four = add(2, 2)
```
Any local variables of the function (like `a`, `b` and `result` in above case) aren't visible outside of the function, i.e. they are local to the function.
The value of a function call is the value that was passed to the `return` statement inside the function. In this case it's the value of the local variable `result`.
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
I think you mean, how do I access values that I return from a function.
Say you have a function:
```
def func_1():
b = 1
return b
```
If you want the return value from that function, set some variable equal to it, like so:
```
someVariable = func_1() #func_1 executes it's code, and returns the value contained in b
```
You pass arguments to functions by placing them in the parentheses in the function declaration line:
```
a = "foo"
def func_1(some_foo): #here some_foo represents a variable you are passing to func_1
b = "bar"
print some_foo, b #now you're referencing the variable you passed
return b
#Now you call the function like this:
func_1(a) #passing a (which equals "foo")
```
To pass multiple arguments, your function declaration would look like this:
```
def func_1(some_foo1, some_foo2,...):
```
It's also important to remember that variables declared/initialized inside of a function are only accessible within that function block. Therefore:
```
def func_1(some_foo1):
print some_foo1
a = some_foo1 #Doesn't work. The variable some_foo1 doesn't exist outside of `func_1`
```
|
>
> I am 'expecting' b to be available after the function call, as I have returned it
>
>
>
The fundamental misunderstanding: you aren't returning a variable, you're returning a value. Variables are labels (names) for values. Inside the function, you have a name `b` for a value `"foo"`. You use this name to refer to the value, so that you can return it.
On the outside, to use this value, you must do something with it. The call to the function - `func_1()` - is a stand-in, in whatever expression contains it, for the value that gets returned. So a line of code like `func_1()`, by itself, does nothing visible: you have an expression that evaluates to `"foo"`, but then nothing is done with `"foo"`.
You could, for example, `print(func_1())` to display the string. You can assign the returned value to another variable: `c = func_1()`. Now `c` is a name for the `"foo"` value that was returned. You can use the function call as part of a larger expression: `c = func_1() + "bar"` - now `c` is a name for a string `"foobar"`, created by joining together the string returned from the function with the directly-specified one.
On the other side: to get information **into** the function, you should pass it as a parameter. These are the values that go inside the parentheses: when you write the function, you put argument names (another kind of variable) inside the parentheses, and when you call the function, you put the parameters that you are calling the function with (expressions that provide the values). Now, inside the function, each time it is called, the arguments will refer to the parameter values.
Let us work a simple example. We will make a function that appends "bar" to an input string, and call it a few times.
```
def add_bar(to):
return to + "bar"
```
Notice how we can return any expression. When the function is called, the expression is evaluated, joining the passed-in argument string `to` to the constant `"bar"`, and the resulting value is returned. There is no variable here that represents the entire return value, because again, we are returning a value, not a variable.
Now we may call this. Again, the parameter can be whatever expression - so a constant:
```
add_bar("foo")
```
or a variable that we have previously assigned a value:
```
my_string = "sand"
add_bar(my_string)
```
or something more complex, maybe even involving another call to the function:
```
add_bar(add_bar("bar ") + " ")
```
But again, none of these will actually do anything, except produce the string and then throw it away. So let's fix that:
```
print("I want a " + add_bar("chocolate") + ".")
```
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
I think this is what you want to do:
```
a = "foo"
def func_1():
b = "bar"
print a,b
return b # Took out parenthasis
returned_b = func_1() # Added variable to hold the returned "b"
print returned_b
```
It looks like you are just learning to code in general. Your issues look to be with understanding how computer code typically works, not so much with Python in particular.
A couple of other things.
In the line `a = "foo"`, a is a global variable. This is often frowned upon in programming because it can create confusion (although I feel like it may be used more in Python in particular).
It looks like you are having trouble understanding an aspect of how variables work called 'scope'. When you declared the variable `b` inside of `func_1()`, it had only function scope. Once the function exited, the variable no longer existed unless you returned the value AND stored it in another variable, that may, coincidentally, also have been called `b`.
I'm not sure you will be able to learn these concepts out of a normal Python book geared towards people who already know how to program. What you probably need is a book that teaches you how to program in general, and also uses Python as the language of choice. As I mentioned in a comment up top, finding the right learning source is key, otherwise you can be in for a world of frustration.
Here is an example of how a "normal" program might be set up:
```
def main(): # Calling main() "runs" the program
a = add(1,2)
print a
def add(first, second): # functions are normally declared outside of other functions,
result = first + second # that way, they can be used anywhere
return result
```
|
Here is your example modified:
```
a = "foo"
def func_1():
b = "bar"
print a,b
return b
b = func_1()
print b
```
`b` inside the function is a local variable, so it's not available outside of the function, but since you return it, you can assign the returned value to a new variable (which I also called `b`, but it's not the same one).
An alternative approach would be to use a global (not local) variable inside the function. To do that you need to declare it as global inside the function:
```
a = "foo"
def func_1():
global b
b = "bar"
print a,b
func_1()
print b
```
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
You've returned it, but not assigned it to anything:
```
def func_1():
b = "bar"
a = 2
return a, b
a, b = func_1()
print b
```
|
>
> I am 'expecting' b to be available after the function call, as I have returned it
>
>
>
The fundamental misunderstanding: you aren't returning a variable, you're returning a value. Variables are labels (names) for values. Inside the function, you have a name `b` for a value `"foo"`. You use this name to refer to the value, so that you can return it.
On the outside, to use this value, you must do something with it. The call to the function - `func_1()` - is a stand-in, in whatever expression contains it, for the value that gets returned. So a line of code like `func_1()`, by itself, does nothing visible: you have an expression that evaluates to `"foo"`, but then nothing is done with `"foo"`.
You could, for example, `print(func_1())` to display the string. You can assign the returned value to another variable: `c = func_1()`. Now `c` is a name for the `"foo"` value that was returned. You can use the function call as part of a larger expression: `c = func_1() + "bar"` - now `c` is a name for a string `"foobar"`, created by joining together the string returned from the function with the directly-specified one.
On the other side: to get information **into** the function, you should pass it as a parameter. These are the values that go inside the parentheses: when you write the function, you put argument names (another kind of variable) inside the parentheses, and when you call the function, you put the parameters that you are calling the function with (expressions that provide the values). Now, inside the function, each time it is called, the arguments will refer to the parameter values.
Let us work a simple example. We will make a function that appends "bar" to an input string, and call it a few times.
```
def add_bar(to):
return to + "bar"
```
Notice how we can return any expression. When the function is called, the expression is evaluated, joining the passed-in argument string `to` to the constant `"bar"`, and the resulting value is returned. There is no variable here that represents the entire return value, because again, we are returning a value, not a variable.
Now we may call this. Again, the parameter can be whatever expression - so a constant:
```
add_bar("foo")
```
or a variable that we have previously assigned a value:
```
my_string = "sand"
add_bar(my_string)
```
or something more complex, maybe even involving another call to the function:
```
add_bar(add_bar("bar ") + " ")
```
But again, none of these will actually do anything, except produce the string and then throw it away. So let's fix that:
```
print("I want a " + add_bar("chocolate") + ".")
```
|
9,353,457
|
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently.
How do you pass variables to and from functions properly.
In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not work.)
```
a = "foo"
def func_1():
b = "bar"
print a,b
return (b)
func_1()
print b
```
I am 'expecting' b to be available after the function call, as I have returned it... I appreciate this me not understanding properly how to implement/manage variables
Thanks.
|
2012/02/19
|
[
"https://Stackoverflow.com/questions/9353457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191626/"
] |
Function calls are expressions. Like any expression they have a value. If you don't assign the value to anything, it is lost.
```
def add(a, b):
result = a + b
return result
four = add(2, 2)
```
Any local variables of the function (like `a`, `b` and `result` in above case) aren't visible outside of the function, i.e. they are local to the function.
The value of a function call is the value that was passed to the `return` statement inside the function. In this case it's the value of the local variable `result`.
|
>
> I am 'expecting' b to be available after the function call, as I have returned it
>
>
>
The fundamental misunderstanding: you aren't returning a variable, you're returning a value. Variables are labels (names) for values. Inside the function, you have a name `b` for a value `"foo"`. You use this name to refer to the value, so that you can return it.
On the outside, to use this value, you must do something with it. The call to the function - `func_1()` - is a stand-in, in whatever expression contains it, for the value that gets returned. So a line of code like `func_1()`, by itself, does nothing visible: you have an expression that evaluates to `"foo"`, but then nothing is done with `"foo"`.
You could, for example, `print(func_1())` to display the string. You can assign the returned value to another variable: `c = func_1()`. Now `c` is a name for the `"foo"` value that was returned. You can use the function call as part of a larger expression: `c = func_1() + "bar"` - now `c` is a name for a string `"foobar"`, created by joining together the string returned from the function with the directly-specified one.
On the other side: to get information **into** the function, you should pass it as a parameter. These are the values that go inside the parentheses: when you write the function, you put argument names (another kind of variable) inside the parentheses, and when you call the function, you put the parameters that you are calling the function with (expressions that provide the values). Now, inside the function, each time it is called, the arguments will refer to the parameter values.
Let us work a simple example. We will make a function that appends "bar" to an input string, and call it a few times.
```
def add_bar(to):
return to + "bar"
```
Notice how we can return any expression. When the function is called, the expression is evaluated, joining the passed-in argument string `to` to the constant `"bar"`, and the resulting value is returned. There is no variable here that represents the entire return value, because again, we are returning a value, not a variable.
Now we may call this. Again, the parameter can be whatever expression - so a constant:
```
add_bar("foo")
```
or a variable that we have previously assigned a value:
```
my_string = "sand"
add_bar(my_string)
```
or something more complex, maybe even involving another call to the function:
```
add_bar(add_bar("bar ") + " ")
```
But again, none of these will actually do anything, except produce the string and then throw it away. So let's fix that:
```
print("I want a " + add_bar("chocolate") + ".")
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.