qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
20,795,230 | I have blob representing webp image I want to be able to create an image from the blob using Wand and then convert it to jpeg. Is that possible with Wand or any other python library. | 2013/12/27 | [
"https://Stackoverflow.com/questions/20795230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2442744/"
] | Wand is a wrapper for imagemagick - in general, the file types that Wand supports are based on how imagemagick is configured on the system in question.
For example, if you're on a mac using homebrew, it would need to be installed with:
```
brew install imagemagick --with-webp
``` | Well I could not do it with Wand. I found another library [Pillow](https://pypi.python.org/pypi/Pillow/).
I have a java script code that capture video frame from canvas and convert the webp imge from based64 to binary image and send it using web socket to a server on the server I construct the image and convert it from webp to jpeg and then use OpenCV to process the jpeg image. Here is a sample
code
```
from PIL import Image
import StringIO
import numpy as np
import cv2
#webpimg is binary webp image received from the websocket
newImg = Image.open(StringIO.StringIO(webpimg)).convert("")
temp = StringIO.StringIO()
newImg.save(temp, "JPEG")
contents = temp.getvalue()
temp.close()
array = np.fromstring(contents, dtype=np.uint8)
jpegimg = cv2.imdecode(array, cv2.CV_LOAD_IMAGE_COLOR)
cv2.imwrite("imgCV.jpeg", img1)
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Another solution in case you already use [GuzzleHttp](http://docs.guzzlephp.org/).
This solution is based on an internal method of `GuzzleHttp\Client`.
```php
use GuzzleHttp\Psr7\UriResolver;
use GuzzleHttp\Psr7\Utils;
function resolve(string $uri, ?string $base_uri): string
{
$uri = Utils::uriFor(trim($uri));
if (isset($base_uri)) {
$uri = UriResolver::resolve(Utils::uriFor(trim($base_uri)), $uri);
}
// optional: set default scheme if missing
$uri = $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
return (string)$uri;
}
```
**EDIT:** the source code was updated as suggested by myriacl | If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php>
```
<?php
$url_parts = parse_url($relative_url);
$absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
```
Ex:
```
<?php
function getAbsoluteURL($source_url, $relative_url)
{
$url_parts = parse_url($relative_url);
return http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
}
echo getAbsoluteURL('http://foo.tw/a/b/c', '../pic.jpg') . "\n";
// http://foo.tw/a/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', '../pic.jpg') . "\n";
// http://foo.tw/a/b/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', 'http://bar.tw/a.js') . "\n";
// http://bar.tw/a.js
echo getAbsoluteURL('http://foo.tw/a/b/c/', '/robots.txt') . "\n";
// http://foo.tw/robots.txt
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php>
```
<?php
$url_parts = parse_url($relative_url);
$absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
```
Ex:
```
<?php
function getAbsoluteURL($source_url, $relative_url)
{
$url_parts = parse_url($relative_url);
return http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
}
echo getAbsoluteURL('http://foo.tw/a/b/c', '../pic.jpg') . "\n";
// http://foo.tw/a/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', '../pic.jpg') . "\n";
// http://foo.tw/a/b/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', 'http://bar.tw/a.js') . "\n";
// http://bar.tw/a.js
echo getAbsoluteURL('http://foo.tw/a/b/c/', '/robots.txt') . "\n";
// http://foo.tw/robots.txt
``` | Here is another function that can handle protocol relative urls
```
<?php
function getAbsoluteURL($to, $from = null) {
$arTarget = parse_url($to);
$arSource = parse_url($from);
$targetPath = isset($arTarget['path']) ? $arTarget['path'] : '';
if (isset($arTarget['host'])) {
if (!isset($arTarget['scheme'])) {
$proto = isset($arSource['scheme']) ? "{$arSource['scheme']}://" : '//';
} else {
$proto = "{$arTarget['scheme']}://";
}
$baseUrl = "{$proto}{$arTarget['host']}" . (isset($arTarget['port']) ? ":{$arTarget['port']}" : '');
} else {
if (isset($arSource['host'])) {
$proto = isset($arSource['scheme']) ? "{$arSource['scheme']}://" : '//';
$baseUrl = "{$proto}{$arSource['host']}" . (isset($arSource['port']) ? ":{$arSource['port']}" : '');
} else {
$baseUrl = '';
}
$arPath = [];
if ((empty($targetPath) || $targetPath[0] !== '/') && !empty($arSource['path'])) {
$arTargetPath = explode('/', $targetPath);
if (empty($arSource['path'])) {
$arPath = [];
} else {
$arPath = explode('/', $arSource['path']);
array_pop($arPath);
}
$len = count($arPath);
foreach ($arTargetPath as $idx => $component) {
if ($component === '..') {
if ($len > 1) {
$len--;
array_pop($arPath);
}
} elseif ($component !== '.') {
$len++;
array_push($arPath, $component);
}
}
$targetPath = implode('/', $arPath);
}
}
return $baseUrl . $targetPath;
}
// SAMPLES
// Absolute path => https://www.google.com/doubleclick/
echo getAbsoluteURL('/doubleclick/', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 1 => https://www.google.com/doubleclick/studio
echo getAbsoluteURL('../studio', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 2 => https://www.google.com/doubleclick/insights/case-studies.html
echo getAbsoluteURL('./case-studies.html', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 3 => https://www.google.com/doubleclick/insights/case-studies.html
echo getAbsoluteURL('case-studies.html', 'https://www.google.com/doubleclick/insights/') . "\n";
// Protocol relative url => https://www.google.com/doubleclick/
echo getAbsoluteURL('//www.google.com/doubleclick/', 'https://www.google.com/doubleclick/insights/') . "\n";
// Empty path => https://www.google.com/doubleclick/insights/
echo getAbsoluteURL('', 'https://www.google.com/doubleclick/insights/') . "\n";
// Different url => http://www.yahoo.com/
echo getAbsoluteURL('http://www.yahoo.com/', 'https://www.google.com') . "\n";
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | other tools that are already linked in page linked in pguardiario's comment: <http://publicmind.in/blog/urltoabsolute/> , <https://github.com/monkeysuffrage/phpuri> .
and i have found other tool from comment in <http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url> :
```
require_once 'Net/URL2.php';
$base = new Net_URL2('http://example.org/foo.html');
$absolute = (string)$base->resolve('relative.html#bar');
``` | I noticed the upvoted answer above uses RegEx, which can be dangerous when dealing with URLs.
This function will resolve relative URLs to a *given* current page url in `$pgurl` **without regex**. It successfully resolves:
`/home.php?example` types,
same-dir `nextpage.php` types,
`../...../.../parentdir` types,
full `http://example.net` urls,
and shorthand `//example.net` urls
```
//Current base URL (you can dynamically retrieve from $_SERVER)
$pgurl = 'http://example.com/scripts/php/absurl.php';
function absurl($url) {
global $pgurl;
if(strpos($url,'://')) return $url; //already absolute
if(substr($url,0,2)=='//') return 'http:'.$url; //shorthand scheme
if($url[0]=='/') return parse_url($pgurl,PHP_URL_SCHEME).'://'.parse_url($pgurl,PHP_URL_HOST).$url; //just add domain
if(strpos($pgurl,'/',9)===false) $pgurl .= '/'; //add slash to domain if needed
return substr($pgurl,0,strrpos($pgurl,'/')+1).$url; //for relative links, gets current directory and appends new filename
}
function nodots($path) { //Resolve dot dot slashes, no regex!
$arr1 = explode('/',$path);
$arr2 = array();
foreach($arr1 as $seg) {
switch($seg) {
case '.':
break;
case '..':
array_pop($arr2);
break;
case '...':
array_pop($arr2); array_pop($arr2);
break;
case '....':
array_pop($arr2); array_pop($arr2); array_pop($arr2);
break;
case '.....':
array_pop($arr2); array_pop($arr2); array_pop($arr2); array_pop($arr2);
break;
default:
$arr2[] = $seg;
}
}
return implode('/',$arr2);
}
```
Usage Example:
```
echo nodots(absurl('../index.html'));
```
`nodots()` must be called *after* the URL is converted to absolute.
The dots function is kind of redundant, but is readable, fast, doesn't use regex's, and will resolve 99% of typical urls (if you want to be 100% sure, just extend the switch block to support 6+ dots, although I've never seen that many dots in a URL).
Hope this helps, |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php>
```
<?php
$url_parts = parse_url($relative_url);
$absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
```
Ex:
```
<?php
function getAbsoluteURL($source_url, $relative_url)
{
$url_parts = parse_url($relative_url);
return http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
}
echo getAbsoluteURL('http://foo.tw/a/b/c', '../pic.jpg') . "\n";
// http://foo.tw/a/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', '../pic.jpg') . "\n";
// http://foo.tw/a/b/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', 'http://bar.tw/a.js') . "\n";
// http://bar.tw/a.js
echo getAbsoluteURL('http://foo.tw/a/b/c/', '/robots.txt') . "\n";
// http://foo.tw/robots.txt
``` | ```
function absoluteUri($Path, $URI)
{ # Requires PHP4 or better.
$URL = parse_url($URI);
$Str = "{$URL['scheme']}://";
if (isset($URL['user']) || isset($URL['pass']))
$Str .= "{$URL['user']}:{$URL['pass']}@";
$Str .= $URL['host'];
if (isset($URL['port']))
$Str .= ":{$URL['port']}";
$Str .= realpath($URL['path'] . $Path); # This part might have an issue on windows boxes.
if (isset($URL['query']))
$Str .= "?{$URL['query']}";
if (isset($URL['fragment']))
$Str .= "#{$URL['fragment']}";
return $Str;
}
absoluteUri("../abc.png", "http://example.com/path/thing?foo=bar");
# Should return "http://example.com/abc.png?foo=bar" on Linux boxes.
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Here is another function that can handle protocol relative urls
```
<?php
function getAbsoluteURL($to, $from = null) {
$arTarget = parse_url($to);
$arSource = parse_url($from);
$targetPath = isset($arTarget['path']) ? $arTarget['path'] : '';
if (isset($arTarget['host'])) {
if (!isset($arTarget['scheme'])) {
$proto = isset($arSource['scheme']) ? "{$arSource['scheme']}://" : '//';
} else {
$proto = "{$arTarget['scheme']}://";
}
$baseUrl = "{$proto}{$arTarget['host']}" . (isset($arTarget['port']) ? ":{$arTarget['port']}" : '');
} else {
if (isset($arSource['host'])) {
$proto = isset($arSource['scheme']) ? "{$arSource['scheme']}://" : '//';
$baseUrl = "{$proto}{$arSource['host']}" . (isset($arSource['port']) ? ":{$arSource['port']}" : '');
} else {
$baseUrl = '';
}
$arPath = [];
if ((empty($targetPath) || $targetPath[0] !== '/') && !empty($arSource['path'])) {
$arTargetPath = explode('/', $targetPath);
if (empty($arSource['path'])) {
$arPath = [];
} else {
$arPath = explode('/', $arSource['path']);
array_pop($arPath);
}
$len = count($arPath);
foreach ($arTargetPath as $idx => $component) {
if ($component === '..') {
if ($len > 1) {
$len--;
array_pop($arPath);
}
} elseif ($component !== '.') {
$len++;
array_push($arPath, $component);
}
}
$targetPath = implode('/', $arPath);
}
}
return $baseUrl . $targetPath;
}
// SAMPLES
// Absolute path => https://www.google.com/doubleclick/
echo getAbsoluteURL('/doubleclick/', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 1 => https://www.google.com/doubleclick/studio
echo getAbsoluteURL('../studio', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 2 => https://www.google.com/doubleclick/insights/case-studies.html
echo getAbsoluteURL('./case-studies.html', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 3 => https://www.google.com/doubleclick/insights/case-studies.html
echo getAbsoluteURL('case-studies.html', 'https://www.google.com/doubleclick/insights/') . "\n";
// Protocol relative url => https://www.google.com/doubleclick/
echo getAbsoluteURL('//www.google.com/doubleclick/', 'https://www.google.com/doubleclick/insights/') . "\n";
// Empty path => https://www.google.com/doubleclick/insights/
echo getAbsoluteURL('', 'https://www.google.com/doubleclick/insights/') . "\n";
// Different url => http://www.yahoo.com/
echo getAbsoluteURL('http://www.yahoo.com/', 'https://www.google.com') . "\n";
``` | ```
function absoluteUri($Path, $URI)
{ # Requires PHP4 or better.
$URL = parse_url($URI);
$Str = "{$URL['scheme']}://";
if (isset($URL['user']) || isset($URL['pass']))
$Str .= "{$URL['user']}:{$URL['pass']}@";
$Str .= $URL['host'];
if (isset($URL['port']))
$Str .= ":{$URL['port']}";
$Str .= realpath($URL['path'] . $Path); # This part might have an issue on windows boxes.
if (isset($URL['query']))
$Str .= "?{$URL['query']}";
if (isset($URL['fragment']))
$Str .= "#{$URL['fragment']}";
return $Str;
}
absoluteUri("../abc.png", "http://example.com/path/thing?foo=bar");
# Should return "http://example.com/abc.png?foo=bar" on Linux boxes.
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php>
```
<?php
$url_parts = parse_url($relative_url);
$absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
```
Ex:
```
<?php
function getAbsoluteURL($source_url, $relative_url)
{
$url_parts = parse_url($relative_url);
return http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
}
echo getAbsoluteURL('http://foo.tw/a/b/c', '../pic.jpg') . "\n";
// http://foo.tw/a/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', '../pic.jpg') . "\n";
// http://foo.tw/a/b/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', 'http://bar.tw/a.js') . "\n";
// http://bar.tw/a.js
echo getAbsoluteURL('http://foo.tw/a/b/c/', '/robots.txt') . "\n";
// http://foo.tw/robots.txt
``` | I noticed the upvoted answer above uses RegEx, which can be dangerous when dealing with URLs.
This function will resolve relative URLs to a *given* current page url in `$pgurl` **without regex**. It successfully resolves:
`/home.php?example` types,
same-dir `nextpage.php` types,
`../...../.../parentdir` types,
full `http://example.net` urls,
and shorthand `//example.net` urls
```
//Current base URL (you can dynamically retrieve from $_SERVER)
$pgurl = 'http://example.com/scripts/php/absurl.php';
function absurl($url) {
global $pgurl;
if(strpos($url,'://')) return $url; //already absolute
if(substr($url,0,2)=='//') return 'http:'.$url; //shorthand scheme
if($url[0]=='/') return parse_url($pgurl,PHP_URL_SCHEME).'://'.parse_url($pgurl,PHP_URL_HOST).$url; //just add domain
if(strpos($pgurl,'/',9)===false) $pgurl .= '/'; //add slash to domain if needed
return substr($pgurl,0,strrpos($pgurl,'/')+1).$url; //for relative links, gets current directory and appends new filename
}
function nodots($path) { //Resolve dot dot slashes, no regex!
$arr1 = explode('/',$path);
$arr2 = array();
foreach($arr1 as $seg) {
switch($seg) {
case '.':
break;
case '..':
array_pop($arr2);
break;
case '...':
array_pop($arr2); array_pop($arr2);
break;
case '....':
array_pop($arr2); array_pop($arr2); array_pop($arr2);
break;
case '.....':
array_pop($arr2); array_pop($arr2); array_pop($arr2); array_pop($arr2);
break;
default:
$arr2[] = $seg;
}
}
return implode('/',$arr2);
}
```
Usage Example:
```
echo nodots(absurl('../index.html'));
```
`nodots()` must be called *after* the URL is converted to absolute.
The dots function is kind of redundant, but is readable, fast, doesn't use regex's, and will resolve 99% of typical urls (if you want to be 100% sure, just extend the switch block to support 6+ dots, although I've never seen that many dots in a URL).
Hope this helps, |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Perhaps this article could help?
http:// nashruddin.com/PHP\_Script\_for\_Converting\_Relative\_to\_Absolute\_URL
Edit: reproduced code below for convenience
```
<?php
function rel2abs($rel, $base)
{
/* return if already absolute URL */
if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;
/* queries and anchors */
if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
/* parse base URL and convert to local variables:
$scheme, $host, $path */
extract(parse_url($base));
/* remove non-directory element from path */
$path = preg_replace('#/[^/]*$#', '', $path);
/* destroy path if relative url points to root */
if ($rel[0] == '/') $path = '';
/* dirty absolute URL */
$abs = "$host$path/$rel";
/* replace '//' or '/./' or '/foo/../' with '/' */
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
/* absolute URL is ready! */
return $scheme.'://'.$abs;
}
?>
``` | Here is another function that can handle protocol relative urls
```
<?php
function getAbsoluteURL($to, $from = null) {
$arTarget = parse_url($to);
$arSource = parse_url($from);
$targetPath = isset($arTarget['path']) ? $arTarget['path'] : '';
if (isset($arTarget['host'])) {
if (!isset($arTarget['scheme'])) {
$proto = isset($arSource['scheme']) ? "{$arSource['scheme']}://" : '//';
} else {
$proto = "{$arTarget['scheme']}://";
}
$baseUrl = "{$proto}{$arTarget['host']}" . (isset($arTarget['port']) ? ":{$arTarget['port']}" : '');
} else {
if (isset($arSource['host'])) {
$proto = isset($arSource['scheme']) ? "{$arSource['scheme']}://" : '//';
$baseUrl = "{$proto}{$arSource['host']}" . (isset($arSource['port']) ? ":{$arSource['port']}" : '');
} else {
$baseUrl = '';
}
$arPath = [];
if ((empty($targetPath) || $targetPath[0] !== '/') && !empty($arSource['path'])) {
$arTargetPath = explode('/', $targetPath);
if (empty($arSource['path'])) {
$arPath = [];
} else {
$arPath = explode('/', $arSource['path']);
array_pop($arPath);
}
$len = count($arPath);
foreach ($arTargetPath as $idx => $component) {
if ($component === '..') {
if ($len > 1) {
$len--;
array_pop($arPath);
}
} elseif ($component !== '.') {
$len++;
array_push($arPath, $component);
}
}
$targetPath = implode('/', $arPath);
}
}
return $baseUrl . $targetPath;
}
// SAMPLES
// Absolute path => https://www.google.com/doubleclick/
echo getAbsoluteURL('/doubleclick/', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 1 => https://www.google.com/doubleclick/studio
echo getAbsoluteURL('../studio', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 2 => https://www.google.com/doubleclick/insights/case-studies.html
echo getAbsoluteURL('./case-studies.html', 'https://www.google.com/doubleclick/insights/') . "\n";
// Relative path 3 => https://www.google.com/doubleclick/insights/case-studies.html
echo getAbsoluteURL('case-studies.html', 'https://www.google.com/doubleclick/insights/') . "\n";
// Protocol relative url => https://www.google.com/doubleclick/
echo getAbsoluteURL('//www.google.com/doubleclick/', 'https://www.google.com/doubleclick/insights/') . "\n";
// Empty path => https://www.google.com/doubleclick/insights/
echo getAbsoluteURL('', 'https://www.google.com/doubleclick/insights/') . "\n";
// Different url => http://www.yahoo.com/
echo getAbsoluteURL('http://www.yahoo.com/', 'https://www.google.com') . "\n";
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Another solution in case you already use [GuzzleHttp](http://docs.guzzlephp.org/).
This solution is based on an internal method of `GuzzleHttp\Client`.
```php
use GuzzleHttp\Psr7\UriResolver;
use GuzzleHttp\Psr7\Utils;
function resolve(string $uri, ?string $base_uri): string
{
$uri = Utils::uriFor(trim($uri));
if (isset($base_uri)) {
$uri = UriResolver::resolve(Utils::uriFor(trim($base_uri)), $uri);
}
// optional: set default scheme if missing
$uri = $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
return (string)$uri;
}
```
**EDIT:** the source code was updated as suggested by myriacl | other tools that are already linked in page linked in pguardiario's comment: <http://publicmind.in/blog/urltoabsolute/> , <https://github.com/monkeysuffrage/phpuri> .
and i have found other tool from comment in <http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url> :
```
require_once 'Net/URL2.php';
$base = new Net_URL2('http://example.org/foo.html');
$absolute = (string)$base->resolve('relative.html#bar');
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Perhaps this article could help?
http:// nashruddin.com/PHP\_Script\_for\_Converting\_Relative\_to\_Absolute\_URL
Edit: reproduced code below for convenience
```
<?php
function rel2abs($rel, $base)
{
/* return if already absolute URL */
if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;
/* queries and anchors */
if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
/* parse base URL and convert to local variables:
$scheme, $host, $path */
extract(parse_url($base));
/* remove non-directory element from path */
$path = preg_replace('#/[^/]*$#', '', $path);
/* destroy path if relative url points to root */
if ($rel[0] == '/') $path = '';
/* dirty absolute URL */
$abs = "$host$path/$rel";
/* replace '//' or '/./' or '/foo/../' with '/' */
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
/* absolute URL is ready! */
return $scheme.'://'.$abs;
}
?>
``` | If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php>
```
<?php
$url_parts = parse_url($relative_url);
$absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
```
Ex:
```
<?php
function getAbsoluteURL($source_url, $relative_url)
{
$url_parts = parse_url($relative_url);
return http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH);
}
echo getAbsoluteURL('http://foo.tw/a/b/c', '../pic.jpg') . "\n";
// http://foo.tw/a/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', '../pic.jpg') . "\n";
// http://foo.tw/a/b/pic.jpg
echo getAbsoluteURL('http://foo.tw/a/b/c/', 'http://bar.tw/a.js') . "\n";
// http://bar.tw/a.js
echo getAbsoluteURL('http://foo.tw/a/b/c/', '/robots.txt') . "\n";
// http://foo.tw/robots.txt
``` |
1,243,418 | I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.
```
resolve("../abc.png", "http://example.com/path/thing?foo=bar")
# returns http://example.com/abc.png
```
Is there a canonical way?
On this site I see great examples for python and c#, lets get a PHP solution. | 2009/08/07 | [
"https://Stackoverflow.com/questions/1243418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Perhaps this article could help?
http:// nashruddin.com/PHP\_Script\_for\_Converting\_Relative\_to\_Absolute\_URL
Edit: reproduced code below for convenience
```
<?php
function rel2abs($rel, $base)
{
/* return if already absolute URL */
if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;
/* queries and anchors */
if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
/* parse base URL and convert to local variables:
$scheme, $host, $path */
extract(parse_url($base));
/* remove non-directory element from path */
$path = preg_replace('#/[^/]*$#', '', $path);
/* destroy path if relative url points to root */
if ($rel[0] == '/') $path = '';
/* dirty absolute URL */
$abs = "$host$path/$rel";
/* replace '//' or '/./' or '/foo/../' with '/' */
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
/* absolute URL is ready! */
return $scheme.'://'.$abs;
}
?>
``` | ```
function absoluteUri($Path, $URI)
{ # Requires PHP4 or better.
$URL = parse_url($URI);
$Str = "{$URL['scheme']}://";
if (isset($URL['user']) || isset($URL['pass']))
$Str .= "{$URL['user']}:{$URL['pass']}@";
$Str .= $URL['host'];
if (isset($URL['port']))
$Str .= ":{$URL['port']}";
$Str .= realpath($URL['path'] . $Path); # This part might have an issue on windows boxes.
if (isset($URL['query']))
$Str .= "?{$URL['query']}";
if (isset($URL['fragment']))
$Str .= "#{$URL['fragment']}";
return $Str;
}
absoluteUri("../abc.png", "http://example.com/path/thing?foo=bar");
# Should return "http://example.com/abc.png?foo=bar" on Linux boxes.
``` |
45,952,387 | I'm trying to follow along the [Audio Recognition Network](https://www.tensorflow.org/versions/master/tutorials/audio_recognition) tutorial.
I've created an Anaconda environment with python 3.6 and followed the install instruction accordingly for installing the GPU whl.
I can run the 'hello world' TF example.
When I go to run 'train.py' in the Audio Recognition Network tutorial/example, I get:
```
Traceback (most recent call last):
File "train.py", line 79, in <module>
import input_data
File "/home/philglau/speech_commands/input_data.py", line 35, in <module>
from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio
ImportError: cannot import name 'audio_ops'
```
The [code](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/speech_commands/input_data.py) in the tutorial that fails is:
```
from tensorflow.contrib.framework.python.ops import audio_ops as contrib_audio
```
I then backed up that chain until I could import some part of it:
```
import tensorflow.contrib.framework as test ==> works
import tensorflow.contrib.framework.python as test --> fail:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow.contrib.framework' has no attribute 'python'
```
Not sure where I'm going wrong on my install.
Details:
```
Ubuntu 16.04
Anaconda env with python 3.6
Followed the 'anaconda' instruction on the TF install page. (GPU version)
```
I also tried using a python 2.7 env for anaconda but got the same results. | 2017/08/30 | [
"https://Stackoverflow.com/questions/45952387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194267/"
] | It looks like they're releasing the audio\_ops modules in version 1.4 (<https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-327879009>).
Until v1.4 is released, an easy way around this is to install the nightly tensorflow build
```
pip install tf-nightly
```
or with the docker image linked in the issue comment. | The short answer:
The framework is missing the "audio\_ops.py" and the example wont work until the file is released. Or you code the wrappers.
More on this:
If you go to the: tensorflow.contrib.framework.python.ops local folder you can find other \*\_ops.py files but not the "audio\_ops.py".
If you get it from the Master at: <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/framework/python/ops>
You will find the file is almost empty and with import labels wrong: "audio\_ops" vs "gen\_audio\_ops".
With almost empty I mean that: decode\_wav, encode\_wav, audio\_spectrogram , mfcc are not implemented/wrapped.
So, no working example and no fun.
We need to check again when "audio\_ops.py" is released.
Here:
<https://github.com/tensorflow/tensorflow/issues/11339>
You can find a Developer saying: "we don't actually want to make them public / supported yet. I'm sorry this decision wasn't better documented" |
55,432,601 | I have a string : `5kg`.
I need to make the numerical and the textual parts apart. So, in this case, it should produce two parts : `5` and `kg`.
For that I wrote a code:
```
grocery_uom = '5kg'
unit_weight, uom = grocery_uom.split('[a-zA-Z]+', 1)
print(unit_weight)
```
Getting this error:
```
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-66-23a4dd3345a6> in <module>()
1 grocery_uom = '5kg'
----> 2 unit_weight, uom = grocery_uom.split('[a-zA-Z]+', 1)
3 #print(unit_weight)
4
5
ValueError: not enough values to unpack (expected 2, got 1)
print(uom)
```
**Edit:**
I wrote this:
```
unit_weight, uom = re.split('[a-zA-Z]+', grocery_uom, 1)
print(unit_weight)
print('-----')
print(uom)
```
Now I am getting this output:
```
5
-----
```
How to store the 2nd part of the string to a var?
**Edit1:**
I wrote this which solved my purpose (Thanks to Peter Wood):
```
unit_weight = re.split('([a-zA-Z]+)', grocery_uom, 1)[0]
uom = re.split('([a-zA-Z]+)', grocery_uom, 1)[1]
``` | 2019/03/30 | [
"https://Stackoverflow.com/questions/55432601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6528055/"
] | You don't want to split on the "kg", because that means it's not part of the actual data. Although looking at the docs, I see you can include them <https://docs.python.org/3/howto/regex.html> But the split pattern is intended to be a separater.
Here's an example of just making a pattern for exactly what you want:
```
import re
pattern = re.compile(r'(?P<weight>[0-9]+)\W*(?P<measure>[a-zA-Z]+)')
text = '5kg'
match = pattern.search(text)
print (match.groups())
weight, measure = match.groups()
print (weight, measure)
print ('the weight is', match.group('weight'))
print ('the unit is', match.group('measure'))
print (match.groupdict())
```
output
>
> ('5', 'kg')
>
> 5 kg
>
> the weight is 5
>
> the unit is kg
>
> {'weight': '5', 'measure': 'kg'}
>
>
>
> | \*updated to allow for bigger numbers, such as "1,000"
Try this.
```
import re
grocery_uom = '5kg'
split_str = re.split(r'([0-9,?]+)([a-zA-Z]+)', grocery_uom, 1)
unit_weight, uom = split_str[1:3]
## Output: 5 kg
``` |
55,432,601 | I have a string : `5kg`.
I need to make the numerical and the textual parts apart. So, in this case, it should produce two parts : `5` and `kg`.
For that I wrote a code:
```
grocery_uom = '5kg'
unit_weight, uom = grocery_uom.split('[a-zA-Z]+', 1)
print(unit_weight)
```
Getting this error:
```
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-66-23a4dd3345a6> in <module>()
1 grocery_uom = '5kg'
----> 2 unit_weight, uom = grocery_uom.split('[a-zA-Z]+', 1)
3 #print(unit_weight)
4
5
ValueError: not enough values to unpack (expected 2, got 1)
print(uom)
```
**Edit:**
I wrote this:
```
unit_weight, uom = re.split('[a-zA-Z]+', grocery_uom, 1)
print(unit_weight)
print('-----')
print(uom)
```
Now I am getting this output:
```
5
-----
```
How to store the 2nd part of the string to a var?
**Edit1:**
I wrote this which solved my purpose (Thanks to Peter Wood):
```
unit_weight = re.split('([a-zA-Z]+)', grocery_uom, 1)[0]
uom = re.split('([a-zA-Z]+)', grocery_uom, 1)[1]
``` | 2019/03/30 | [
"https://Stackoverflow.com/questions/55432601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6528055/"
] | You need to use regex split rather than simple string split and the precise pattern you are looking for splitting is this,
```
(?<=\d)(?=[a-zA-Z]+)
```
Basically the point where is preceded by digit, hence this regex `(?<=\d)` and followed by alphabets, hence this regex `(?=[a-zA-Z]+)` and it can be seen in this demo with pink marker.
**[Check the pink marker from where the split will take place](https://regex101.com/r/PM25Ml/1)**
Also, here is your modified Python code,
```
import re
grocery_uom = '5kg'
unit_weight, uom = re.split(r'(?<=\d)(?=[a-zA-Z]+)', grocery_uom, 1)
print('unit_weight: ', unit_weight, 'uom: ', uom)
```
Prints,
```
unit_weight: 5 uom: kg
```
Also, if there can be optional space between the number and units, you can better use this regex which will optionally consume the space too during split,
```
(?<=\d)\s*(?=[a-zA-Z]+)
```
**[Demo allowing optional space](https://regex101.com/r/PM25Ml/2)** | \*updated to allow for bigger numbers, such as "1,000"
Try this.
```
import re
grocery_uom = '5kg'
split_str = re.split(r'([0-9,?]+)([a-zA-Z]+)', grocery_uom, 1)
unit_weight, uom = split_str[1:3]
## Output: 5 kg
``` |
7,047,133 | I wrote a test program that looked like this:
```
#!/usr/bin/python
def incrementc():
c = c + 1
def main():
c = 5
incrementc()
main()
print c
```
I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get
```
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 8, in main
incrementc()
File "test.py", line 4, in incrementc
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment
```
Why isn't c passing through? And if I want a variable to be referenced by multiple functions, do I have to declare it globally? I read somewhere that global variables are bad.
Thanks! | 2011/08/12 | [
"https://Stackoverflow.com/questions/7047133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892549/"
] | You're thinking of [dynamic scoping](http://en.wikipedia.org/wiki/Dynamic_scoping#Dynamic_scoping). The problem with dynamic scoping is that the behavior of `incrementc` would depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use static scoping: `c` is visible only within `main`.
To accomplish what you want, you'd either use a global variable, or, better, pass `c` as a parameter. Now, because the primitives in Python are immutable, passing an integer can't be changed (it's effectively passed by value), so you'd have to pack it into a container, like a list. Like this:
```
def increment(l):
l[0] = l[0] + 1
def main():
c = [5]
increment(c)
print c[0]
main()
```
Or, even simpler:
```
def increment(l):
return l + 1
def main():
c = 5
print increment(c)
main()
```
Generally, global variables are bad because they make it very easy to write code that's hard to understand. If you only have these two functions, you can go ahead and make `c` global because it's still obvious what the code does. If you have more code, it's better to pass the variables as a parameter instead; this way you can more easily see who depends on the global variable. | Global variables are bad.
Just like friends and enemys. Keep your friends close but keep your enemys even closer.
The function main last a local variable c, assignment the value 5
You then call the function inc..C. The c from main is now out of scope so you are trying to use a value of c that is not in scope - hence the error. |
7,047,133 | I wrote a test program that looked like this:
```
#!/usr/bin/python
def incrementc():
c = c + 1
def main():
c = 5
incrementc()
main()
print c
```
I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get
```
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 8, in main
incrementc()
File "test.py", line 4, in incrementc
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment
```
Why isn't c passing through? And if I want a variable to be referenced by multiple functions, do I have to declare it globally? I read somewhere that global variables are bad.
Thanks! | 2011/08/12 | [
"https://Stackoverflow.com/questions/7047133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892549/"
] | When a variable is assigned to in a scope, Python assumes it's local for the whole scope unless you tell it otherwise.
So, to get this to work as you think it will, you need to use two `global` statements:
```
#!/usr/bin/python
def incrementc():
global c
c = c + 1
def main():
global c
c = 5
incrementc()
main()
print c
```
Otherwise, you're talking about a local variable named `c` in both situations.
The normal way to solve this, however, **does not** involve `global`s.
```
#!/usr/bin/python
def incrementc(c):
c = c + 1
return c
def main():
c = 5
c = incrementc(c)
return c
c = main()
print c
```
Here, in each function and in the global scope, `c` refers to a **different variable**, which you are passing around as an argument and with return values. If you wanted **only one `c`**, use a class:
```
class Foo:
def __init__(self, c):
self.c = c
self.incrementc()
def incrementc(self):
self.c = self.c + 1
foo = Foo(5)
print foo.c
``` | Global variables are bad.
Just like friends and enemys. Keep your friends close but keep your enemys even closer.
The function main last a local variable c, assignment the value 5
You then call the function inc..C. The c from main is now out of scope so you are trying to use a value of c that is not in scope - hence the error. |
7,047,133 | I wrote a test program that looked like this:
```
#!/usr/bin/python
def incrementc():
c = c + 1
def main():
c = 5
incrementc()
main()
print c
```
I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get
```
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 8, in main
incrementc()
File "test.py", line 4, in incrementc
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment
```
Why isn't c passing through? And if I want a variable to be referenced by multiple functions, do I have to declare it globally? I read somewhere that global variables are bad.
Thanks! | 2011/08/12 | [
"https://Stackoverflow.com/questions/7047133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892549/"
] | The variable c isn't passing through because you do not hand any reference to c to the function incrementc.
What you're looking at here are 3 scopes, the global scope and those within the functions main and incrementc. In main you've properly defined a variable c, but increment c has no knowledge of this - so attempting to increment it is going to fail. Even if those two functions succeeded, trying to print c would fail in the global scope because it has no knowledge of the c you've defined in main.
You have a few options. One way to do this:
```
def incrementc(c):
c = c + 1
return c
def main():
c = 5
c = incrementc(c)
return c
c = main()
print c
```
Notice how c is being handed around. Of course, the name doesn't have to be preserved, you very well could write it like this:
```
def increment(z):
z = z + 1
return z
def main():
bar = 5
bar = increment(bar)
return bar
foo = main()
print foo
```
Another option that many would probably dislike (for good reason) is to use globals. In that case:
```
def incrementc():
global c # indicate intention to write to this global, not just read it
c = c + 1
def main():
global c # declares c in global space
c = 5
incrementc()
main()
print c
```
Any function in which you hope to MODIFY the GLOBAL instance of c, you need to inform the function. So you state, 'global c'. You can READ from the global without doing so. This would ensure (to some extent) that you don't make a mistake and overwrite a value in the global space unintentionally with a similar name, should you decide to use one in the local space of a function.
Hopefully that's clear enough, but feel free to ask for clarification on any point (I'm also open to being corrected if I've mistakenly described any part of this). | Global variables are bad.
Just like friends and enemys. Keep your friends close but keep your enemys even closer.
The function main last a local variable c, assignment the value 5
You then call the function inc..C. The c from main is now out of scope so you are trying to use a value of c that is not in scope - hence the error. |
7,047,133 | I wrote a test program that looked like this:
```
#!/usr/bin/python
def incrementc():
c = c + 1
def main():
c = 5
incrementc()
main()
print c
```
I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get
```
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 8, in main
incrementc()
File "test.py", line 4, in incrementc
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment
```
Why isn't c passing through? And if I want a variable to be referenced by multiple functions, do I have to declare it globally? I read somewhere that global variables are bad.
Thanks! | 2011/08/12 | [
"https://Stackoverflow.com/questions/7047133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892549/"
] | You're thinking of [dynamic scoping](http://en.wikipedia.org/wiki/Dynamic_scoping#Dynamic_scoping). The problem with dynamic scoping is that the behavior of `incrementc` would depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use static scoping: `c` is visible only within `main`.
To accomplish what you want, you'd either use a global variable, or, better, pass `c` as a parameter. Now, because the primitives in Python are immutable, passing an integer can't be changed (it's effectively passed by value), so you'd have to pack it into a container, like a list. Like this:
```
def increment(l):
l[0] = l[0] + 1
def main():
c = [5]
increment(c)
print c[0]
main()
```
Or, even simpler:
```
def increment(l):
return l + 1
def main():
c = 5
print increment(c)
main()
```
Generally, global variables are bad because they make it very easy to write code that's hard to understand. If you only have these two functions, you can go ahead and make `c` global because it's still obvious what the code does. If you have more code, it's better to pass the variables as a parameter instead; this way you can more easily see who depends on the global variable. | When a variable is assigned to in a scope, Python assumes it's local for the whole scope unless you tell it otherwise.
So, to get this to work as you think it will, you need to use two `global` statements:
```
#!/usr/bin/python
def incrementc():
global c
c = c + 1
def main():
global c
c = 5
incrementc()
main()
print c
```
Otherwise, you're talking about a local variable named `c` in both situations.
The normal way to solve this, however, **does not** involve `global`s.
```
#!/usr/bin/python
def incrementc(c):
c = c + 1
return c
def main():
c = 5
c = incrementc(c)
return c
c = main()
print c
```
Here, in each function and in the global scope, `c` refers to a **different variable**, which you are passing around as an argument and with return values. If you wanted **only one `c`**, use a class:
```
class Foo:
def __init__(self, c):
self.c = c
self.incrementc()
def incrementc(self):
self.c = self.c + 1
foo = Foo(5)
print foo.c
``` |
7,047,133 | I wrote a test program that looked like this:
```
#!/usr/bin/python
def incrementc():
c = c + 1
def main():
c = 5
incrementc()
main()
print c
```
I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get
```
Traceback (most recent call last):
File "test.py", line 10, in <module>
main()
File "test.py", line 8, in main
incrementc()
File "test.py", line 4, in incrementc
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment
```
Why isn't c passing through? And if I want a variable to be referenced by multiple functions, do I have to declare it globally? I read somewhere that global variables are bad.
Thanks! | 2011/08/12 | [
"https://Stackoverflow.com/questions/7047133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/892549/"
] | You're thinking of [dynamic scoping](http://en.wikipedia.org/wiki/Dynamic_scoping#Dynamic_scoping). The problem with dynamic scoping is that the behavior of `incrementc` would depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use static scoping: `c` is visible only within `main`.
To accomplish what you want, you'd either use a global variable, or, better, pass `c` as a parameter. Now, because the primitives in Python are immutable, passing an integer can't be changed (it's effectively passed by value), so you'd have to pack it into a container, like a list. Like this:
```
def increment(l):
l[0] = l[0] + 1
def main():
c = [5]
increment(c)
print c[0]
main()
```
Or, even simpler:
```
def increment(l):
return l + 1
def main():
c = 5
print increment(c)
main()
```
Generally, global variables are bad because they make it very easy to write code that's hard to understand. If you only have these two functions, you can go ahead and make `c` global because it's still obvious what the code does. If you have more code, it's better to pass the variables as a parameter instead; this way you can more easily see who depends on the global variable. | The variable c isn't passing through because you do not hand any reference to c to the function incrementc.
What you're looking at here are 3 scopes, the global scope and those within the functions main and incrementc. In main you've properly defined a variable c, but increment c has no knowledge of this - so attempting to increment it is going to fail. Even if those two functions succeeded, trying to print c would fail in the global scope because it has no knowledge of the c you've defined in main.
You have a few options. One way to do this:
```
def incrementc(c):
c = c + 1
return c
def main():
c = 5
c = incrementc(c)
return c
c = main()
print c
```
Notice how c is being handed around. Of course, the name doesn't have to be preserved, you very well could write it like this:
```
def increment(z):
z = z + 1
return z
def main():
bar = 5
bar = increment(bar)
return bar
foo = main()
print foo
```
Another option that many would probably dislike (for good reason) is to use globals. In that case:
```
def incrementc():
global c # indicate intention to write to this global, not just read it
c = c + 1
def main():
global c # declares c in global space
c = 5
incrementc()
main()
print c
```
Any function in which you hope to MODIFY the GLOBAL instance of c, you need to inform the function. So you state, 'global c'. You can READ from the global without doing so. This would ensure (to some extent) that you don't make a mistake and overwrite a value in the global space unintentionally with a similar name, should you decide to use one in the local space of a function.
Hopefully that's clear enough, but feel free to ask for clarification on any point (I'm also open to being corrected if I've mistakenly described any part of this). |
14,716,111 | I'd like to rename `%paste` to something like `%pp` so that it takes fewer keystrokes. I worked out a way to do that but it seems complicated. Is there a better way?
```
def foo(self, bar):
get_ipython().magic("paste")
get_ipython().define_magic('pp', foo)
``` | 2013/02/05 | [
"https://Stackoverflow.com/questions/14716111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461389/"
] | From IPython 0.13, there's a new `%alias_magic` magic function, which you would use as:
```
%alias_magic pp paste
``` | use `%alias` magic to do it (if you want it to be permanent use `%store`):
```
In [8]: %alias??
"""Define an alias for a system command.
'%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
...
``` |
52,601,350 | I'm trying to make a minesweeper game using lists in python. I have have this code so far:
```
import random as r
import sys
#dimension of board and number of bombs
width = int(sys.argv[1])
height = int(sys.argv[2])
b = int(sys.argv[3])
#creates the board
board = [[0.0] * width] * height
#places bombs
for i in range(b):
x = r.randint(0, width - 1)
y = r.randint(0, height - 1)
board.insert(x, y, 0.1)
#prints board
for i in range(len(board)):
for j in range(len(board[i]))
print(board[i][j], end=" ")
```
I'm trying to get the bombs to be placed at random places on the board, but `insert()` only accepts 2 args. Is there any other way in which I can do this?
I have an idea to place a random bomb in row 1, then a random bomb in row 2, and so on and once it hits row n it loops back to row 1 until enough bombs have been placed, but I'm not sure if it will work (and I have no way of testing it because I have do idea how to do that either). I feel like this solution is pretty inefficient, so I'm also wondering if there's a more efficient way to do it. | 2018/10/02 | [
"https://Stackoverflow.com/questions/52601350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10173748/"
] | You can just use `board[x][y] = 0.1` to access index `y` in row `x` of your board. Also, you don't want to build a board like that. The way you're doing it will only actually create 1 array with numbers. Here's your code with some modifications.
```
import random as r
# dimension of board and number of bombs
# (I'm using hard coded values as an example)
width = 5
height = 7
b = 10
#creates the board
board = []
for i in range(height): # create a new array for every row
board.append([0.0] * width)
#places bombs
for i in range(b):
x = r.randint(0, height - 1)
y = r.randint(0, width - 1)
board[x][y] = 0.1 # this is how you place a bomb at a random coordinate
#prints board
for row in board:
print(row)
```
The resulting board for me looks like:
```
[0.0, 0.0, 0.1, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0]
[0.1, 0.0, 0.1, 0.0, 0.1]
[0.1, 0.0, 0.0, 0.0, 0.1]
[0.0, 0.1, 0.0, 0.0, 0.1]
[0.0, 0.1, 0.0, 0.0, 0.0]
```
Note that you can end up with less than `b` bombs in case the random x and y values repeat. That's a good problem to solve next. | We are dealing list of list. If we run your board initialization code and modify board value as follows:
```
>>> width = 2; height = 3
>>> board = [[0.0] * width] * height
>>> print board
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
>>> x = 0; y = 1; board[y][x] = 1.1
>>> print board
[[1.1, 0.0], [1.1, 0.0], [1.1, 0.0]]
```
We see our modification appears three places. This is because we have put the same list ([0.0] \* width) *height* times. One way of doing it properly is board = [[0.0] \* width for \_ in range(3)]. Please refer to [Two dimensional array in python](https://stackoverflow.com/questions/8183146/two-dimensional-array-in-python) .
Since we are using list of list, one way of inserting element 0.1 for x and y will be using insert will be board[y].insert(x, 0.1). But I feel like that what you wanted to do is board[y][x]=0.1.
For the placing bombs, what you have described can be implemented like:
```
n = <the number of bombs>
for i in xrange(n):
x = i % width # x will iterate over 0 to width
y = r.randint(0, height - 1)
# insert bomb
```
Cheers, |
52,601,350 | I'm trying to make a minesweeper game using lists in python. I have have this code so far:
```
import random as r
import sys
#dimension of board and number of bombs
width = int(sys.argv[1])
height = int(sys.argv[2])
b = int(sys.argv[3])
#creates the board
board = [[0.0] * width] * height
#places bombs
for i in range(b):
x = r.randint(0, width - 1)
y = r.randint(0, height - 1)
board.insert(x, y, 0.1)
#prints board
for i in range(len(board)):
for j in range(len(board[i]))
print(board[i][j], end=" ")
```
I'm trying to get the bombs to be placed at random places on the board, but `insert()` only accepts 2 args. Is there any other way in which I can do this?
I have an idea to place a random bomb in row 1, then a random bomb in row 2, and so on and once it hits row n it loops back to row 1 until enough bombs have been placed, but I'm not sure if it will work (and I have no way of testing it because I have do idea how to do that either). I feel like this solution is pretty inefficient, so I'm also wondering if there's a more efficient way to do it. | 2018/10/02 | [
"https://Stackoverflow.com/questions/52601350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10173748/"
] | Use assignment instead of insert:
`board[x][y] = 0.1`.
Also, be careful initializing your 2D board. `board = [[0.0] * width] * height` will make one list of size `width` and then will copy pointers to that list for all of the `height` i.e. if you assign 0.1 to the first cell in the first row `board[0][0]` the first item in *every* row will be assigned since they are all the same list. you have to instead use
```
board = [[0.0]*width for _ in range(height)]
``` | We are dealing list of list. If we run your board initialization code and modify board value as follows:
```
>>> width = 2; height = 3
>>> board = [[0.0] * width] * height
>>> print board
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
>>> x = 0; y = 1; board[y][x] = 1.1
>>> print board
[[1.1, 0.0], [1.1, 0.0], [1.1, 0.0]]
```
We see our modification appears three places. This is because we have put the same list ([0.0] \* width) *height* times. One way of doing it properly is board = [[0.0] \* width for \_ in range(3)]. Please refer to [Two dimensional array in python](https://stackoverflow.com/questions/8183146/two-dimensional-array-in-python) .
Since we are using list of list, one way of inserting element 0.1 for x and y will be using insert will be board[y].insert(x, 0.1). But I feel like that what you wanted to do is board[y][x]=0.1.
For the placing bombs, what you have described can be implemented like:
```
n = <the number of bombs>
for i in xrange(n):
x = i % width # x will iterate over 0 to width
y = r.randint(0, height - 1)
# insert bomb
```
Cheers, |
59,661,745 | I have pytest-django == 2.9.1 installed
I started setting up a test environment according to the instructions.
<https://pytest-django.readthedocs.io/en/latest/tutorial.html#step-2-point-pytest-to-your-django-settings>
In the second step, in the root of the project, I created a pytest.ini file and added DJANGO\_SETTINGS\_MODULE there (all according to the instructions)
But when you start the test, an error appears
```
django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
```
But DJANGO\_SETTINGS\_MODULE is defined in the pytest.ini!
I tried putting pytest.ini in different directories, but the result is always the same.
I tried running with a parameter --ds, but the result is still the same.
Can you tell me why this happens?
**UPD**
Hmm... I remove [pytest] from the file header and got an error "no section header defined" The file does not seem to be ignored, but DJANGO\_SETTINGS\_MODULE is still not exported.
I tried adding it to the environment variables separately and received an error on startup
>
> export DJANGO\_SETTINGS\_MODULE=project.settings.test\_settings
>
>
> pytest
>
>
> ImportError: Could not import settings 'project.settings.test\_settings' (Is it on sys.path? Is there an import error in the settings file?): No module named project.settings.test\_settings
>
>
>
But at startup python manage.py runserver --settings=project.settings.test\_settings everything is working fine | 2020/01/09 | [
"https://Stackoverflow.com/questions/59661745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7526559/"
] | had the same issue, there were 2 problems:
1. settings.py had a bug.
2. pytest-django was installed in a different environment.
So ensure you can import settings.py as hoefling recommended, and ensure pytest-django is actually installed in your environment | So the [docs](https://pytest-django.readthedocs.io/en/latest/configuring_django.html#order-of-choosing-settings) say that the order of precedence when choosing setting is
command line
environment variable
pytest.ini file.
Then it goes further to say you can override this precedence using `addopts`.
In my case, I specified my settings like below
```
DJANGO_SETTINGS_MODULE=bm.settings.ttest
addopts = --ds=bm.settings.ttest
```
And it works. |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided.
```
Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error));
```
Other than that you could either use the [mongoose.Types.ObjectId.isValid](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) or a regular expression: `/^[a-fA-F0-9]{24}$/` | ```
let mongoose = require('mongoose');
let ObjectId = mongoose.Types.ObjectId;
let recId1 = "621f1d71aec9313aa2b9074c";
let isValid1 = ObjectId.isValid(recId1); //true
console.log("isValid1 = ", isValid1); //true
let recId2 = "621f1d71aec9313aa2b9074cd";
let isValid2 = ObjectId.isValid(recId2); //false
console.log("isValid2 = ", isValid2); //false
``` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | @mickl's Answer will be failed for the strings with the length of 12.
You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same.
```
import { ObjectId } from 'mongodb'
function isValidId(id) {
return new ObjectId(id).toString() === id;
}
isValidId('5c0a7922c9d89830f4911426')// true
isValidId('lkjyuhgfdres')// false
``` | ```
let mongoose = require('mongoose');
let ObjectId = mongoose.Types.ObjectId;
let recId1 = "621f1d71aec9313aa2b9074c";
let isValid1 = ObjectId.isValid(recId1); //true
console.log("isValid1 = ", isValid1); //true
let recId2 = "621f1d71aec9313aa2b9074cd";
let isValid2 = ObjectId.isValid(recId2); //false
console.log("isValid2 = ", isValid2); //false
``` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose:
```
var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
``` | @mickl's Answer will be failed for the strings with the length of 12.
You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same.
```
import { ObjectId } from 'mongodb'
function isValidId(id) {
return new ObjectId(id).toString() === id;
}
isValidId('5c0a7922c9d89830f4911426')// true
isValidId('lkjyuhgfdres')// false
``` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided.
```
Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error));
```
Other than that you could either use the [mongoose.Types.ObjectId.isValid](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) or a regular expression: `/^[a-fA-F0-9]{24}$/` | If you use **Joi** for validating, you can include validation directly in your **Joi schemas**, using **[joi-objectid](https://github.com/pebble/joi-objectid)**:
Install joi-objectid: `$ npm i joi-objectid`
Define the function to use globally (with Joi already imported):
```
Joi.objectId = require('joi-objectid')(Joi)
```
Use it in your Joi schema:
```js
function validateUser(user) {
const schema = {
userId: Joi.objectId().required(),
name: Joi.string().required()
};
return Joi.validate(user, schema);
}
``` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided.
```
Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error));
```
Other than that you could either use the [mongoose.Types.ObjectId.isValid](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) or a regular expression: `/^[a-fA-F0-9]{24}$/` | @mickl's Answer will be failed for the strings with the length of 12.
You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same.
```
import { ObjectId } from 'mongodb'
function isValidId(id) {
return new ObjectId(id).toString() === id;
}
isValidId('5c0a7922c9d89830f4911426')// true
isValidId('lkjyuhgfdres')// false
``` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose:
```
var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
``` | Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided.
```
Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error));
```
Other than that you could either use the [mongoose.Types.ObjectId.isValid](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) or a regular expression: `/^[a-fA-F0-9]{24}$/` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | @mickl's Answer will be failed for the strings with the length of 12.
You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same.
```
import { ObjectId } from 'mongodb'
function isValidId(id) {
return new ObjectId(id).toString() === id;
}
isValidId('5c0a7922c9d89830f4911426')// true
isValidId('lkjyuhgfdres')// false
``` | If you use **Joi** for validating, you can include validation directly in your **Joi schemas**, using **[joi-objectid](https://github.com/pebble/joi-objectid)**:
Install joi-objectid: `$ npm i joi-objectid`
Define the function to use globally (with Joi already imported):
```
Joi.objectId = require('joi-objectid')(Joi)
```
Use it in your Joi schema:
```js
function validateUser(user) {
const schema = {
userId: Joi.objectId().required(),
name: Joi.string().required()
};
return Joi.validate(user, schema);
}
``` |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose:
```
var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
``` | The API provided ([Mongoose.prototype.isValidObjectId()](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId) and for newer versions and ) returns true for random strings like `Manajemenfs2`.
With mongoose this is how I ended up doing it:
```
import mongoose from 'mongoose';
const isValidMongoId = (id: string) => {
try {
const objectID = new mongoose.Types.ObjectId(id);
const objectIDString = objectID.toString();
return objectIDString === id;
} catch (e){
return false;
}
};
```
The definition of the method clearly shows:
```
Mongoose.prototype.isValidObjectId = function(v) {
if (v == null) {
return true;
}
//Other code
if (v.toString instanceof Function) {
v = v.toString();
}
if (typeof v === 'string' && v.length === 12) {
return true;
}
//Other code
return false;
};
```
that for general primitive strings and even string objects, any string of length 12 passes. |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | @mickl's Answer will be failed for the strings with the length of 12.
You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same.
```
import { ObjectId } from 'mongodb'
function isValidId(id) {
return new ObjectId(id).toString() === id;
}
isValidId('5c0a7922c9d89830f4911426')// true
isValidId('lkjyuhgfdres')// false
``` | The API provided ([Mongoose.prototype.isValidObjectId()](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId) and for newer versions and ) returns true for random strings like `Manajemenfs2`.
With mongoose this is how I ended up doing it:
```
import mongoose from 'mongoose';
const isValidMongoId = (id: string) => {
try {
const objectID = new mongoose.Types.ObjectId(id);
const objectIDString = objectID.toString();
return objectIDString === id;
} catch (e){
return false;
}
};
```
The definition of the method clearly shows:
```
Mongoose.prototype.isValidObjectId = function(v) {
if (v == null) {
return true;
}
//Other code
if (v.toString instanceof Function) {
v = v.toString();
}
if (typeof v === 'string' && v.length === 12) {
return true;
}
//Other code
return false;
};
```
that for general primitive strings and even string objects, any string of length 12 passes. |
53,686,556 | I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit:
```
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu', input_shape = (56,56,3)))
model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(216, activation = "linear"))
from tensorflow.python.keras.losses import categorical_crossentropy
model.compile(loss = categorical_crossentropy,
optimizer = "adam",
metrics = ['accuracy'])
```
This is giving me an error:
```
ValueError: Error when checking target: expected dense_1 to have shape (216,) but got array with shape (72,)
```
I know how to code aclassifier model but not to obtain an array as output, so probably I'm not setting the right shape in last Dense layer. I don't know if it should be 1 or 216.
I read in [this post](https://stackoverflow.com/questions/51617857/keras-dense-layer-shape-error) that the problem could be the loss function, but I'm not sure what other loss function should I use.
Thanks in advance! | 2018/12/08 | [
"https://Stackoverflow.com/questions/53686556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10754618/"
] | You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose:
```
var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
``` | If you use **Joi** for validating, you can include validation directly in your **Joi schemas**, using **[joi-objectid](https://github.com/pebble/joi-objectid)**:
Install joi-objectid: `$ npm i joi-objectid`
Define the function to use globally (with Joi already imported):
```
Joi.objectId = require('joi-objectid')(Joi)
```
Use it in your Joi schema:
```js
function validateUser(user) {
const schema = {
userId: Joi.objectId().required(),
name: Joi.string().required()
};
return Joi.validate(user, schema);
}
``` |
48,836,596 | I stumbled upon the following syntax in [Python decorator to keep signature and user defined attribute](https://stackoverflow.com/questions/48746567/python-decorator-to-keep-signature-and-user-defined-attribute):
```
> def func():
... return "Hello World!"
...
> func?
Signature: func()
Docstring: <no docstring>
File: ~/<ipython-input-8-934f46134434>
Type: function
```
Attempting the same in my Python Shell, whether 2 or 3, simply raises a `SyntaxError`. So what is this exactly, is it specific to some shells? | 2018/02/17 | [
"https://Stackoverflow.com/questions/48836596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5079316/"
] | Check if you have added the below detail in your settings file. If yes, then skip this part.
**settings.py**
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")], # Add this to your settings file
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
myproject/
|-- myproject/
| |-- myapp/
| |-- myproject/
| |-- templates/ <-- here!
| | |-- myapp/
| | | |-- index.html
| | |-- base.html
| | +-- home.html
| +-- manage.py
+-- venv/
```
**views.py:**
```
@login_required
def post_publish(request,pk):
post = get_object_or_404(Post,pk=pk)
return render(request, template_name.html,{'post': post})
```
Try using return render this will work for sure.
In your view you have not show anywhere. what is your template\_name. | From Django Docs:
Additional form template furniture
Don’t forget that a form’s output does not include the surrounding tags, or the form’s submit control. You will have to provide these yourself.
<https://docs.djangoproject.com/en/2.0/topics/forms/>
You are missing the input with type submit:
```
<input type="submit" value="Submit">
```
After handling the submitted data in your views.py you can redirect to the desired url there is no need to use an tag. |
71,215,277 | I have been working on writing a Wordle bot, and wanted to see how it preforms with all 13,000 words. The problem is that I am running this through a for loop and it is very inefficient. After running it for 30 minutes, it only gets to around 5%. I could wait all that time, but it would end up being 10+ hours. There has got to be a more efficient way. I am new to python, so any suggestions would be greatly appreciated.
The code here is the code that is used to limit down the guesses each time. Would there be a way to search for a word that contains "a", "b", and "c"? Instead of running it 3 separate times. Right now the containts, nocontains, and isletter will each run every time I need to search for a new letter. Searching them all together would greatly reduce the time.
```py
#Find the words that only match the criteria
def contains(letter, place):
list.clear()
for x in words:
if x not in removed:
if letter in x:
if letter == x[place]:
removed.append(x)
else:
list.append(x)
else:
removed.append(x)
def nocontains(letter):
list.clear()
for x in words:
if x not in removed:
if letter not in x:
list.append(x)
else:
removed.append(x)
def isletter(letter, place):
list.clear()
for x in words:
if x not in removed:
if letter == x[place]:
list.append(x)
else:
removed.append(x)
``` | 2022/02/22 | [
"https://Stackoverflow.com/questions/71215277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18257273/"
] | The performance problems can be massively reduced by using [sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). Any time that you want to repeatedly test for membership (even only a few times), e.g. `if x not in removed`, you want to try to make a set. Lists require checking every element to find x, which is bad if the list has thousands of elements. In a Python set, `if x not in removed` should take as long to run if `removed` has `100` elements or `100,000`, a small constant amount of time.
Besides this, you're running into problems by trying to use mutable global variables everywhere, like for `list` (which needs to be renamed) and `removed`. There's no benefit to doing that and several downsides, such as making it harder to reason about your code or optimize it. One benefit of Python is that you can pass large containers or objects to functions without any extra time or space cost: calling a function `f(huge_list)` is as fast and uses as much memory as `f(tiny_list)`, as if you were passing by reference in other languages, so don't hesitate to use containers as function parameters or return types.
In summary, here's how your code could be refactored if you take away 'list' and 'removed' and instead store this as a `set` of possible words:
```py
all_words = [] # Huge word list to read in from text file
current_possible_words = set(all_words)
def contains_only_elsewhere(possible_words, letter, place):
"""Given letter and place, remove from possible_words
all words containing letter but not at place"""
to_remove = {word for word in possible_words
if letter not in word or word[place] == letter}
return possible_words - to_remove
def must_not_contain(possible_words, letter):
"""Given a letter, remove from possible_words all words containing letter"""
to_remove = {word for word in possible_words
if letter in word}
return possible_words - to_remove
def exact_letter_match(possible_words, letter, place):
"""Given a letter and place, remove from possible_words
all words not containing letter at place"""
to_remove = {word for word in possible_words
if word[place] != letter}
return possible_words - to_remove
```
The outside code will be different: for example,
```py
current_possible_words = exact_letter_match(current_possible_words, 'a', 2)`
```
Further optimizations are possible (and much easier now): storing only indices to words rather than the strings; precomputing, for each letter, the set of all words containing that letter, etc. | I just wrote a wordle bot that runs in about a second including the web scraping to fetch a list of 5 letter words.
```
import urllib.request
from bs4 import BeautifulSoup
def getwords():
source = "https://www.thefreedictionary.com/5-letter-words.htm"
filehandle = urllib.request.urlopen(source)
soup = BeautifulSoup(filehandle.read(), "html.parser")
wordslis = soup.findAll("li", {"data-f": "15"})
words = []
for k in wordslis:
words.append(k.getText())
return words
words = getwords()
def hasLetterAtPosition(letter,position,word):
return letter==word[position]
def hasLetterNotAtPosition(letter,position,word):
return letter in word[:position]+word[position+1:]
def doesNotHaveLetter(letter,word):
return not letter in word
lettersPositioned = [(0,"y")]
lettersMispositioned = [(0,"h")]
lettersNotHad = ["p"]
idx = 0
while idx<len(words):
eliminated = False
for criteria in lettersPositioned:
if not hasLetterAtPosition(criteria[1],criteria[0],words[idx]):
del words[idx]
eliminated = True
break
if eliminated:
continue
for criteria in lettersMispositioned:
if not hasLetterNotAtPosition(criteria[1],criteria[0],words[idx]):
del words[idx]
eliminated = True
break
if eliminated:
continue
for letter in lettersNotHad:
if not doesNotHaveLetter(letter,words[idx]):
del words[idx]
eliminated = True
break
if eliminated:
continue
idx+=1
print(words) # ["youth"]
```
The reason yours is slow is because you have a lot of calls to check if word in removed in addition to a number of superfluous logical conditions in addition to going through all the words for each of your checks.
Edit: Here's a get words function that gets more words.
```
def getwords():
source = "https://wordfind-com.translate.goog/length/5-letter-words/?_x_tr_sl=es&_x_tr_tl=en&_x_tr_hl=en&_x_tr_pto=wapp"
filehandle = urllib.request.urlopen(source)
soup = BeautifulSoup(filehandle.read(), "html.parser")
wordslis = soup.findAll("a", {"rel": "nofollow"})
words = []
for k in wordslis:
words.append(k.getText())
return words
``` |
27,935,800 | I have been on this for days now. Everytime I attempt to install psycopg2 into a virtual environment on my RHEL VPS it fails with the following error. Anyone with a clue should please help out. Thanks.
```
(pyenv)[root@10 pyenv]# pip install psycopg2==2.5.4
Collecting psycopg2==2.5.4
Using cached psycopg2-2.5.4.tar.gz
/tmp/pip-build-Vn6ET9/psycopg2/setup.py:12: DeprecationWarning: Parameters to load are deprecated. Call .resolve and .require separately.
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
Installing collected packages: psycopg2
Running setup.py install for psycopg2
building 'psycopg2._psycopg' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= 2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSI ON="2.5.4 (dt dec pq3 ext)" -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHA VE_PQFREEMEM=1 -DPG_VERSION_HEX=0x080414 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_B OOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.6 -I. -I/usr/include -I/usr/ include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.6/ psycopg/psycopgmodule.o -Wdeclaration-after-statement
unable to execute gcc: No such file or directory
error: command 'gcc' failed with exit status 1
Complete output from command /root/pyenv/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-Vn6ET9/psycopg2/setup.py';exec(compile(getatt r(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'ex ec'))" install --record /tmp/pip-9d8Iwo-record/install-record.txt --single-vers ion-externally-managed --compile --install-headers /root/pyenv/include/site/pyt hon2.6:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.6
creating build/lib.linux-x86_64-2.6/psycopg2
copying lib/psycopg1.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/extras.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/__init__.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/_json.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/pool.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/errorcodes.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/extensions.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/_range.py -> build/lib.linux-x86_64-2.6/psycopg2
copying lib/tz.py -> build/lib.linux-x86_64-2.6/psycopg2
creating build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_copy.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_notify.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_quote.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/dbapi20.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_lobject.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_bug_gc.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_psycopg2_dbapi20.py -> build/lib.linux-x86_64-2.6/psycop g2/tests
copying tests/testutils.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_cursor.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/__init__.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_bugX000.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_types_basic.py -> build/lib.linux-x86_64-2.6/psycopg2/te sts
copying tests/test_connection.py -> build/lib.linux-x86_64-2.6/psycopg2/tes ts
copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-2.6/psyco pg2/tests
copying tests/test_transaction.py -> build/lib.linux-x86_64-2.6/psycopg2/te sts
copying tests/test_module.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_dates.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/testconfig.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_cancel.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_async.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_with.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_green.py -> build/lib.linux-x86_64-2.6/psycopg2/tests
copying tests/test_types_extras.py -> build/lib.linux-x86_64-2.6/psycopg2/t ests
running build_ext
building 'psycopg2._psycopg' extension
creating build/temp.linux-x86_64-2.6
creating build/temp.linux-x86_64-2.6/psycopg
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE= 2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSI ON="2.5.4 (dt dec pq3 ext)" -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHA VE_PQFREEMEM=1 -DPG_VERSION_HEX=0x080414 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_B OOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.6 -I. -I/usr/include -I/usr/ include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.6/ psycopg/psycopgmodule.o -Wdeclaration-after-statement
unable to execute gcc: No such file or directory
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/root/pyenv/bin/python -c "import setuptools, tokenize;__file__='/ tmp/pip-build-Vn6ET9/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --rec ord /tmp/pip-9d8Iwo-record/install-record.txt --single-version-externally-manag ed --compile --install-headers /root/pyenv/include/site/python2.6" failed with error code 1 in /tmp/pip-build-Vn6ET9/psycopg2
``` | 2015/01/14 | [
"https://Stackoverflow.com/questions/27935800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2669337/"
] | I found my way around it. I noticed it installs successfully globally. So I installed psycopg2 globally and created a new virtual environment with `--system-site-packages` option. Then I installed my other packages using the `-I` option.
Hope this helps someone else.
OK. I later found out that I had no `gcc` installed. So I had to install it first. And after that, I could `pip install psycopg2`. Thank you cel for the direction. | For me, I'm using Redhat 8 enterprise and my issue wasn't solved by installing gcc and gcc-c++.
I was able to solve the issue by installing **python3-devel** and **development tools**.
to install them on Redhat using yum manager, please follow this [link](https://linuxize.com/post/how-to-install-pip-on-centos-8/) |
30,445,136 | I am using z3py. I am trying to check the satisfiability for different problems with different sizes and verify the scalability of the proposed method. However, to do that I need to know the memory consumed by the solver for each problem. Is there a way to access the memory or make the z3py print it in the STATISTICS section. Thank you so much in advance.
**Update-27/5/2015:**
I tried with the paython memory profiler but it seems that the generated memory is very large. I am not sure but the reported memory is similar to the memory consumed by the python application and not only Z3(constructing the z3 model and checking the sat and then generating model). Moreover, I used formal modeling checking tools for many years now. I am expecting Z3 to be more efficient and have better scalability, however, I am getting much less memory than what the paython is generating.
What I am thinking to do is to try to measure the design size or the scalability using factors other than memory. In z3py statistics many details are generated to describe the design size and complexity. However, I am not able to find any explanation of these parameters in the tutorial, webpage, or z3 papers.
For example, can you help me understand the following parameters generated in the statistics for one of the basic models I have. Also is there any parameter/parameters which can replace the memory or be good indication of the Z3 mdoel size/complexity.
* :added-eqs 152
* :assert-lower 2
* :assert-upper 2
* :binary-propagations 59
* :conflicts 6
* :datatype-accessor-ax 12
* :datatype-constructor-ax 14
* :datatype-occurs-check 19
* :datatype-splits 12
* :decisions 35
* :del-clause 2
* :eq-adapter 2
* :final-checks 1
* :mk-clause 9
* :offset-eqs 2
* :propagations 61
Thank again for your time. | 2015/05/25 | [
"https://Stackoverflow.com/questions/30445136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343141/"
] | You should use `getIntent().getIntExtra(name, defaultValue)` instead of `Integer.parseInt(intent.getStringExtra("page"));`
**Update:**
```
int defaultValue = -1;// take any default value of your choice
String name = intent.getStringExtra("name");
int page1 = intent.getIntExtra("page", defaultValue);
``` | Activity A
```
String textname = (String) dataItem.get("name");
Intent m = new Intent(list.this,main.class);
m.putExtra("name",textname);
m.putExtra("page",1);
startActivity(m);
```
Activity B
```
Intent intent = getIntent();
name = intent.getStringExtra("name");
int page = intent.getIntExtra("page", 0);
```
where 0 is the default value. |
30,445,136 | I am using z3py. I am trying to check the satisfiability for different problems with different sizes and verify the scalability of the proposed method. However, to do that I need to know the memory consumed by the solver for each problem. Is there a way to access the memory or make the z3py print it in the STATISTICS section. Thank you so much in advance.
**Update-27/5/2015:**
I tried with the paython memory profiler but it seems that the generated memory is very large. I am not sure but the reported memory is similar to the memory consumed by the python application and not only Z3(constructing the z3 model and checking the sat and then generating model). Moreover, I used formal modeling checking tools for many years now. I am expecting Z3 to be more efficient and have better scalability, however, I am getting much less memory than what the paython is generating.
What I am thinking to do is to try to measure the design size or the scalability using factors other than memory. In z3py statistics many details are generated to describe the design size and complexity. However, I am not able to find any explanation of these parameters in the tutorial, webpage, or z3 papers.
For example, can you help me understand the following parameters generated in the statistics for one of the basic models I have. Also is there any parameter/parameters which can replace the memory or be good indication of the Z3 mdoel size/complexity.
* :added-eqs 152
* :assert-lower 2
* :assert-upper 2
* :binary-propagations 59
* :conflicts 6
* :datatype-accessor-ax 12
* :datatype-constructor-ax 14
* :datatype-occurs-check 19
* :datatype-splits 12
* :decisions 35
* :del-clause 2
* :eq-adapter 2
* :final-checks 1
* :mk-clause 9
* :offset-eqs 2
* :propagations 61
Thank again for your time. | 2015/05/25 | [
"https://Stackoverflow.com/questions/30445136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343141/"
] | You should use `getIntent().getIntExtra(name, defaultValue)` instead of `Integer.parseInt(intent.getStringExtra("page"));`
**Update:**
```
int defaultValue = -1;// take any default value of your choice
String name = intent.getStringExtra("name");
int page1 = intent.getIntExtra("page", defaultValue);
``` | I in other class use the main class and send parameter to it and it work without any problem but just in list class i have problem
in other class i like this send parameter
```
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent(list_sub.this,main.class);
i.putExtra("name", Name[position]);
i.putExtra("page", Ted[position]);
startActivity(i);
}
```
and in refresh class i get ted parameter
```
private void refresh(){
db.open();
int s = db.List_count("text", ID);
Name= new String[s];
Ted=new String[s];
for(int i=0;i<s;i++){
Name[i]=db.List_display_sub("text", ID, i);
Ted[i]=db.page_count("text", Name[i].toString())+"";
}
db.close();
}
``` |
30,445,136 | I am using z3py. I am trying to check the satisfiability for different problems with different sizes and verify the scalability of the proposed method. However, to do that I need to know the memory consumed by the solver for each problem. Is there a way to access the memory or make the z3py print it in the STATISTICS section. Thank you so much in advance.
**Update-27/5/2015:**
I tried with the paython memory profiler but it seems that the generated memory is very large. I am not sure but the reported memory is similar to the memory consumed by the python application and not only Z3(constructing the z3 model and checking the sat and then generating model). Moreover, I used formal modeling checking tools for many years now. I am expecting Z3 to be more efficient and have better scalability, however, I am getting much less memory than what the paython is generating.
What I am thinking to do is to try to measure the design size or the scalability using factors other than memory. In z3py statistics many details are generated to describe the design size and complexity. However, I am not able to find any explanation of these parameters in the tutorial, webpage, or z3 papers.
For example, can you help me understand the following parameters generated in the statistics for one of the basic models I have. Also is there any parameter/parameters which can replace the memory or be good indication of the Z3 mdoel size/complexity.
* :added-eqs 152
* :assert-lower 2
* :assert-upper 2
* :binary-propagations 59
* :conflicts 6
* :datatype-accessor-ax 12
* :datatype-constructor-ax 14
* :datatype-occurs-check 19
* :datatype-splits 12
* :decisions 35
* :del-clause 2
* :eq-adapter 2
* :final-checks 1
* :mk-clause 9
* :offset-eqs 2
* :propagations 61
Thank again for your time. | 2015/05/25 | [
"https://Stackoverflow.com/questions/30445136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343141/"
] | I in other class use the main class and send parameter to it and it work without any problem but just in list class i have problem
in other class i like this send parameter
```
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent(list_sub.this,main.class);
i.putExtra("name", Name[position]);
i.putExtra("page", Ted[position]);
startActivity(i);
}
```
and in refresh class i get ted parameter
```
private void refresh(){
db.open();
int s = db.List_count("text", ID);
Name= new String[s];
Ted=new String[s];
for(int i=0;i<s;i++){
Name[i]=db.List_display_sub("text", ID, i);
Ted[i]=db.page_count("text", Name[i].toString())+"";
}
db.close();
}
``` | Activity A
```
String textname = (String) dataItem.get("name");
Intent m = new Intent(list.this,main.class);
m.putExtra("name",textname);
m.putExtra("page",1);
startActivity(m);
```
Activity B
```
Intent intent = getIntent();
name = intent.getStringExtra("name");
int page = intent.getIntExtra("page", 0);
```
where 0 is the default value. |
66,472,929 | i try to learn better dict in python. I am using an api "chess.com"
```
data = get_player_game_archives(username).json
url = data['archives'][-1]
games = requests.get(url).json()
game = games['games'][-1]
print(games)
```
That's my code and they are no problem and the result is
```
{'games': [{'url': 'https://www.chess.com/live/game/8358870805', 'pgn': '[Event "Live Chess"]\n[Site "Chess.com"]\n
```
But i dont know how to get the "url",
i tried
```
game = games['games']['url'] or
game = games['games'][{url}]
```
obviously i misunderstood something, but i dont know what.
Thanks for your reading | 2021/03/04 | [
"https://Stackoverflow.com/questions/66472929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13934941/"
] | According to the [SQL Server docs](https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql?view=sql-server-ver15), `CHARINDEX` will find the index of the *first* occurrence of the first parameter substring. As for `LIKE` it is highly likely that it is smart enough to stop searching as soon as it finds a match. Therefore, I would expect the performance of both of your queries to be roughly the same. As for which version to use, the `LIKE` expression can handle more complexity than just substring matches, so you might choose that version if you expect the logic could get more complex later on. | I know this has been answered but it's worth noting that you can create a test harness and see for yourself. I created a 1,000,000 row test; first against a shorter string then against a longer one.
```
SELECT TOP(1000000) SomeCol = NEWID()
INTO #t
FROM sys.all_columns, sys.all_columns a;
DECLARE @x INT, @st DATETIME = GETDATE();
SELECT @x = COUNT(*) FROM #t AS t WHERE t.SomeCol LIKE '%-1234%'
PRINT DATEDIFF(MS,@st,GETDATE());
GO 5
DECLARE @x INT, @st DATETIME = GETDATE();
SELECT @x = COUNT(*) FROM #t AS t WHERE CHARINDEX('-1234',t.SomeCol)>0
PRINT DATEDIFF(MS,@st,GETDATE());
GO 5
```
The performance was relatively the same:
```
Beginning execution loop
586
510
530
530
597
Batch execution completed 5 times.
Beginning execution loop
537
606
547
580
607
Batch execution completed 5 times.
```
The execution plans are similar but it would appear that the LIKE query is a smidgen better based on the 49/51% work estimation but this is based on inaccurate cardinality estimations.
[](https://i.stack.imgur.com/XVnUi.png)
Now if I replace the values with longer strings...
```
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t;
SELECT TOP(1000000) SomeCol = CONCAT(REPLICATE('x',100),NEWID(),NEWID(),NEWID())
INTO #t
FROM sys.all_columns, sys.all_columns a;
```
... and run the same test both queries actually speed up:
```
Beginning execution loop
350
363
364
370
363
Batch execution completed 5 times.
Beginning execution loop
370
370
376
380
380
Batch execution completed 5 times.
```
The improvement is due to both queries getting parallel execution plans (multiple CPU's doing the work.)
[](https://i.stack.imgur.com/VE2Fv.png)
It's interesting to note that the plans are slightly different - the optimizer choosing a Stream Aggregate operator whereas the CHARINDEX solution uses a Hash Match aggregate. Thought the performance is the same, this still serves as an interesting example of how to manipulate the optimizer's behavior. |
56,337,696 | I have this abstract class
```
class Kuku(ABC):
def __init__(self):
self.a = 4
@property
@abstractmethod
def kaka(self):
pass
```
`kaka` is an abstract property, So I would expect python to enforce it being a property in inheritors, But it allows me to create:
```
class KukuChild(Kuku):
def kaka(self):
return 3
```
and KukuChild().kaka() returns 3 as if it's not a property. Is this intentional? Pycharm doesn't enforce this either, so why even add the `property` decorator in the abstract class? | 2019/05/28 | [
"https://Stackoverflow.com/questions/56337696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2899096/"
] | I've come across this problem myself, after looking into the options of how to enforce such behaviour I came up with the idea of implementing a class that has that type checking.
```
import abc
import inspect
from typing import Generic, Set, TypeVar, get_type_hints
T = TypeVar('T')
class AbstractClassVar(Generic[T]):
pass
class Abstract(abc.ABC):
"""Inherit this class to:
1. Enforce type checking for abstract properties.
2. Check that abstract class members (aka. `AbstractClassVar`) are implemented.
"""
def __init_subclass__(cls) -> None:
def get_abstract_properties(cls) -> Set[str]:
"""Gets a class's abstract properties"""
abstract_properties = set()
if cls is Abstract:
return abstract_properties
for base_cls in cls.__bases__:
abstract_properties.update(get_abstract_properties(base_cls))
abstract_properties.update(
{abstract_property[0] for abstract_property in
inspect.getmembers(cls, lambda a: getattr(a, "__isabstractmethod__", False) and type(a) == property)})
return abstract_properties
def get_non_property_members(cls) -> Set[str]:
"""Gets a class's non property members"""
return {member[0] for member in inspect.getmembers(cls, lambda a: type(a) != property)}
def get_abstract_members(cls) -> Set[str]:
"""Gets a class's abstract members"""
abstract_members = set()
if cls is Abstract:
return abstract_members
for base_cls in cls.__bases__:
abstract_members.update(get_abstract_members(base_cls))
for (member_name, annotation) in get_type_hints(cls).items():
if getattr(annotation, '__origin__', None) is AbstractClassVar:
abstract_members.add(member_name)
return abstract_members
cls_abstract_properties = get_abstract_properties(cls)
cls_non_property_members = get_non_property_members(cls)
# Type checking for abstract properties
if cls_abstract_properties:
for member in cls_non_property_members:
if member in cls_abstract_properties:
raise TypeError(f"Wrong class implementation {cls.__name__} " +
f"with abstract property {member}")
# Implementation checking for abstract class members
if Abstract not in cls.__bases__:
for cls_member in get_abstract_members(cls):
if not hasattr(cls, cls_member):
raise NotImplementedError(f"Wrong class implementation {cls.__name__} " +
f"with abstract class variable {cls_member}")
return super().__init_subclass__()
```
Usage:
------
```
class Foo(Abstract):
foo_member: AbstractClassVar[str]
@property
@abc.abstractmethod
def a(self):
...
class UpperFoo(Foo):
# Everything should be implemented as intended or else...
...
```
1. Not implementing the abstract property `a` or implementing it as anything but a `property` (type) will result in a TypeError
2. The trick with the class member is quite different and uses a more complex approach with annotations, but the result is almost the same.
Not Implementing the abstract class member `foo_member` will result in a NotImplementedError. | You are overriding the `kaka` property in the child class. You must also use `@property` to decorate the overridden methods in the child:
```
from abc import ABC, abstractmethod
class Kuku(ABC):
def __init__(self):
self.a = 4
@property
@abstractmethod
def kaka(self):
pass
class KukuChild(Kuku):
@property
def kaka(self):
return 3
KukuChild().kaka # <-- use as an attribute, not a method call.
``` |
44,825,529 | I am looking for a piece of software (python preferred, but really anything for which a jupyter kernel exists) to fit a data sample to a mixture of t-distributions.
I searched quite a while already and it seems to be that this is a somehwat obscure endeavor as most search results turn up for mixture of gaussians (what I am not interested here).
TThe most promising candidates so far are the "AdMit" and "MitSEM" R packages. However I do not know R and find the description of these packages rather comlple and it seems their core objective is not the fitting of mixtures of t’s but instead use this as a step to accomplish something else.
This is in a nutshell what I want the software to accomplish:
Fitting a mixture of t-distributions to some data and estimate the "location" "scale" and "degrees of freedom" for each.
I hope someone can point me to a simple package, I can’t believe that this is such an obscure use case. | 2017/06/29 | [
"https://Stackoverflow.com/questions/44825529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1639834/"
] | This seems to work (in R):
Simulate example:
```
set.seed(101)
x <- c(5+ 3*rt(1000,df=5),
10+1*rt(10000,df=20))
```
Fit:
```
library(teigen)
tt <- teigen(x,
Gs=2, # two components
scale=FALSE,dfupdate="numeric",
models=c("univUU") # univariate model, unconstrained scale and df
# (i.e. scale and df can vary between components)
)
```
The parameters are all reasonably close (except for the df for the second component, but this is a very tough thing to estimate ...)
```
tt$parameters[c("df","mean","sigma","pig")]
## $df ## degrees of freedom
## [1] 3.578491 47.059841
## $mean ## ("location")
## [,1]
## [1,] 4.939179
## [2,] 10.002038
## $sigma ## reporting variance rather than sd (I think?)
## , , 1
## [,1]
## [1,] 8.763076
## , , 2
## [,1]
## [1,] 1.041588
## $pig ## mixture probabilities
## [1] 0.09113273 0.90886727
``` | Late to this party but since you prefer something for Python, there appear to be several packages out there on pypi that fit finite Student's t mixtures, including:
<https://pypi.org/project/studenttmixture/>
<https://pypi.org/project/student-mixture/>
<https://pypi.org/project/smm/>
so all of these can be installed with pip.
Scikit-learn and the other usual suspects obviously don't have this functionality at this time. |
8,251,039 | I am currently writing a script where I want to take the data and write it to a spreadsheet. I've found a few modules for writing xls files, however those only seem to work up to python 2.x, and I'm using 3.2 (also on a mac if that's helpful). Anyone have any ideas on how to get a python3.2 script to output to a spreadsheet? | 2011/11/24 | [
"https://Stackoverflow.com/questions/8251039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242191/"
] | Use the **[csv](http://docs.python.org/release/3.0.1/library/csv.html)** module. The intro from the docs:
>
> The csv module implements classes to read and write tabular data in
> CSV format. It allows programmers to say, “write this data in the
> format preferred by Excel,” or “read data from this file which was
> generated by Excel,” without knowing the precise details of the CSV
> format used by Excel. Programmers can also describe the CSV formats
> understood by other applications or define their own special-purpose
> CSV formats.
>
>
> | On Windows, you can use the COM interface: <http://users.rcn.com/python/download/quoter.pyw>
As @sdolan pointed out, CSV can be a good choice if your data is laid out in a tabular format.
Since Excel can save spreadsheets in an XML format, you can use XML tools to access the data. |
19,485,233 | I am complete newb at python :P. How can I return just the third word of a string using string slicing? Am I close with:
```
splitString = myString.split()
print splitString[2]
``` | 2013/10/21 | [
"https://Stackoverflow.com/questions/19485233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2517330/"
] | ```
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
``` | To convert an `int` ASCII value to character you can also use:
```
int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
``` |
19,485,233 | I am complete newb at python :P. How can I return just the third word of a string using string slicing? Am I close with:
```
splitString = myString.split()
print splitString[2]
``` | 2013/10/21 | [
"https://Stackoverflow.com/questions/19485233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2517330/"
] | ```
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
``` | ```
int main()
{
int v1, v2, v3, v4, v5,v6,v7;
cout << "Enter 7 vals ";
cin >> v1 >> v2 >> v3 >> v4 >> v5 >> v6 >> v7;
cout << "The phrase is "
<< char(v1)
<< char(v2) << " "
<< char(v3) << " "
<< char(v4)
<< char(v5)
<< char(v6)
<< char(v7);
system("pause>0");
}
``` |
19,485,233 | I am complete newb at python :P. How can I return just the third word of a string using string slicing? Am I close with:
```
splitString = myString.split()
print splitString[2]
``` | 2013/10/21 | [
"https://Stackoverflow.com/questions/19485233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2517330/"
] | To convert an `int` ASCII value to character you can also use:
```
int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z
``` | ```
int main()
{
int v1, v2, v3, v4, v5,v6,v7;
cout << "Enter 7 vals ";
cin >> v1 >> v2 >> v3 >> v4 >> v5 >> v6 >> v7;
cout << "The phrase is "
<< char(v1)
<< char(v2) << " "
<< char(v3) << " "
<< char(v4)
<< char(v5)
<< char(v6)
<< char(v7);
system("pause>0");
}
``` |
11,296,768 | Ok so I got python to run in command prompt I just can't figure out the syntax to call scripts from it. So my file is in c:\python\script so I've been calling like this;
```
"C:\Python\Script"
```
but it doesn't anything and returns
```
""File<stdin>", line 1"
``` | 2012/07/02 | [
"https://Stackoverflow.com/questions/11296768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469751/"
] | Is it possible that the connections in question are being intercepted by an enterprise proxy like [bluecoat](http://www.bluecoat.com/) or [websense](http://www.websense.com/) that's middling the SSL session? | Altering the certificate would break its signature, and as your validation shows that something alters the certificate, you should look at *what* changes the certificate, not "how" it's done.
The change is simple - as the certificate is self-signed, someone can just create another self-signed certificate with his own keypair and put different Subject or Issuer to the certificate. Not a big deal. The goal is obviously to capture and decode the traffic by installing man-in-the-middle proxy. |
61,335,488 | I'm using a Nodejs server for a WebApp and Mongoose is acting as the ORM.
I've got some hooks that fire when data is inserted into a certain collection.
I want those hooks to fire when a python script inserts into the mongoDB instance. So if I have a pre save hook, it would modify the python scripts insert according to that hook.
Is this possible? If so, How do I do it?
If not, please feel free to explain to me why this is impossible and/or why I'm stupid.
`EDIT:` I came back to this question some months later and cringed just at how green I was when I asked it. All I really needed done was to create an API endpoint/flag on the NodeJS server that is specifically for automated tasks like the python script to send data to, and have mongoose in NodeJS land structure. | 2020/04/21 | [
"https://Stackoverflow.com/questions/61335488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11370450/"
] | It is impossible because python and nodejs are 2 different runtimes - separate isolated processes which don't have access to each other memories.
Mongoose is a nodejs ORM - a library that maps Javascript objects to Mongodb documents and handles queries to the database.
All mongoose hooks belong to javascript space. They are executed on javascript objects before Mongoose sends any request to mongo. 2 outcomes from there: no other process can mess up with these hooks, not even another nodejs, and once the query reaches mongodb it's final, no more hooks, no more modifications.
One said a picture worth 100 words:
[](https://i.stack.imgur.com/aXsp4.png)
Neither python nor mongo are aware about mongoose hooks. All queries to mongo are initiated on the client side - a script sends a request to modify state of the database or to query state of the database.
**The only way to trigger a javascript code execution from an update on mongodb side is to use [change streams](https://mongoosejs.com/docs/models.html#change-streams)**
Change streams are not mongoose hooks but can be used to hook into the updates on mongo side. It's a bit more advanced use of the database. It comes with additional requirements for mongo set up, size of the oplog, availability of the changestream clients, error handling etc.
You can learn more about change streams here <https://docs.mongodb.com/manual/changeStreams/> I would strongly recommend to seek professional advice to architect such set up to avoid frustration and unexpected behaviour. | Mongo itself does not support hooks as a feature, `mongoose` gives you out of the box hooks you can use as you've mentioned. So what can you do to make it work in python?
1. Use an existing framework like python's [eve](https://docs.python-eve.org/en/stable/features.html#insert-events), eve gives you database hooks, much like `mongoose` does. Now eve is a REST api framework which from your description doesn't sound like what you're looking for. Unfortunately I do not know of any package that's a perfect fit to your needs (if you do find one it would be great if you share a link in your question).
2. Build your own custom wrapper like [this](https://github.com/airflow-plugins/mongo_plugin/blob/master/hooks/mongo_hook.py) one. You can just built a custom wrapper class real quick and implement your own logic very easily. |
57,396,394 | I have two dataframes, one bigger, with names and family names, defined as a multi-index (Family and name) dataframe:
```
Age Weight
Family Name
Marge
SIMPSON Bart
Lisa
Homer
Harry
POTTER Lilian
Lisa
James
```
And the another df is smaller, containing just some of the names of the first df:
```
Family Name
SIMPSON Lisa
SIMPSON Bart
POTTER Lisa
```
I want to filter the first df to show just the names that exists in the second df.
To a better explain, as a reference, in Excel I would create an extra colum and type (suposing that second df is in Sheet2)
`=COUNTIFS(Sheet2!A:Sheet2!A,A1,Sheet2!B:Sheet2!B,B1)`
Than I would filter rows that are equal to 1 in the created column.
Ps: I am not asking how to replicate exaclty the excel code, because I know that propably there's a simple way to do in python. | 2019/08/07 | [
"https://Stackoverflow.com/questions/57396394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9975452/"
] | Your `df1` have multiple index , so normal filter will not work , we can try `reindex`
```
df1 = df1.reindex(pd.MultiIndex.from_frame(df2))
``` | Let `df1` be the bigger dataframe with `MutiIndex` and `df2` smaller one with names.
Then you could do something like this:
```
names = set(df2.Name.astype(str).values)
df1 = df1.loc[df1.index.get_level_values('Name').isin(names)]
``` |
57,396,394 | I have two dataframes, one bigger, with names and family names, defined as a multi-index (Family and name) dataframe:
```
Age Weight
Family Name
Marge
SIMPSON Bart
Lisa
Homer
Harry
POTTER Lilian
Lisa
James
```
And the another df is smaller, containing just some of the names of the first df:
```
Family Name
SIMPSON Lisa
SIMPSON Bart
POTTER Lisa
```
I want to filter the first df to show just the names that exists in the second df.
To a better explain, as a reference, in Excel I would create an extra colum and type (suposing that second df is in Sheet2)
`=COUNTIFS(Sheet2!A:Sheet2!A,A1,Sheet2!B:Sheet2!B,B1)`
Than I would filter rows that are equal to 1 in the created column.
Ps: I am not asking how to replicate exaclty the excel code, because I know that propably there's a simple way to do in python. | 2019/08/07 | [
"https://Stackoverflow.com/questions/57396394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9975452/"
] | ### `join`
```
df2.join(df1, on=df1.index.names).set_index(df1.index.names)
Age Weight
Family Name
SIMPSON Lisa NaN NaN
Bart NaN NaN
POTTER Lisa NaN NaN
```
---
### `merge`
```
df1.merge(df2, on=df1.index.names).set_index(df1.index.names)
Age Weight
Family Name
SIMPSON Lisa NaN NaN
Bart NaN NaN
POTTER Lisa NaN NaN
``` | Your `df1` have multiple index , so normal filter will not work , we can try `reindex`
```
df1 = df1.reindex(pd.MultiIndex.from_frame(df2))
``` |
57,396,394 | I have two dataframes, one bigger, with names and family names, defined as a multi-index (Family and name) dataframe:
```
Age Weight
Family Name
Marge
SIMPSON Bart
Lisa
Homer
Harry
POTTER Lilian
Lisa
James
```
And the another df is smaller, containing just some of the names of the first df:
```
Family Name
SIMPSON Lisa
SIMPSON Bart
POTTER Lisa
```
I want to filter the first df to show just the names that exists in the second df.
To a better explain, as a reference, in Excel I would create an extra colum and type (suposing that second df is in Sheet2)
`=COUNTIFS(Sheet2!A:Sheet2!A,A1,Sheet2!B:Sheet2!B,B1)`
Than I would filter rows that are equal to 1 in the created column.
Ps: I am not asking how to replicate exaclty the excel code, because I know that propably there's a simple way to do in python. | 2019/08/07 | [
"https://Stackoverflow.com/questions/57396394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9975452/"
] | ### `join`
```
df2.join(df1, on=df1.index.names).set_index(df1.index.names)
Age Weight
Family Name
SIMPSON Lisa NaN NaN
Bart NaN NaN
POTTER Lisa NaN NaN
```
---
### `merge`
```
df1.merge(df2, on=df1.index.names).set_index(df1.index.names)
Age Weight
Family Name
SIMPSON Lisa NaN NaN
Bart NaN NaN
POTTER Lisa NaN NaN
``` | Let `df1` be the bigger dataframe with `MutiIndex` and `df2` smaller one with names.
Then you could do something like this:
```
names = set(df2.Name.astype(str).values)
df1 = df1.loc[df1.index.get_level_values('Name').isin(names)]
``` |
32,667,047 | I want to program the following (I've just start to learn python):
```
f[i]:=f[i-1]-(1/n)*(1-(1-f[i-1])^n)-(1/n)*(f[i-1])^n+(2*f[0]/n);
```
with `F[0]=x`, `x` belongs to `[0,1]` and `n` a constant integer.
My try:
```
import pylab as pl
import numpy as np
N=20
n=100
h=0.01
T=np.arange(0, 1+h, h)
def f(i):
if i == 0:
return T
else:
return f(i-1)-(1./n)*(1-(1-f(i-1))**n)-(1./n)*(f(i-1))**n+2.*T/n
pl.figure(figsize=(10, 6), dpi=80)
pl.plot(T,f(N), color="red",linestyle='--', linewidth=2.5)
pl.show()
```
For `N=10` (number of iterations) it returns the correct plot fast enough, but for `N=20` it keeps running and running (more than 30 minutes already). | 2015/09/19 | [
"https://Stackoverflow.com/questions/32667047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5353182/"
] | You calculate `f(i-1)` three times in a single recursion layer - so after the first run you "know" the answer but still calculate it two more times. A naive approach:
```
fi_1 = f(i-1)
return fi_1-(1./n)*(1-(1-fi_1)**n)-(1./n)*(fi_1)**n+2.*T/n
```
But of course we can still do better and cache **every** evaluation of f:
```
cache = {}
def f_cached(i):
if not i in cache:
cache[i] = f(i)
return(cache[i])
```
Then replace every every occurence of `f` with `f_cached`.
There are also libraries out there that can do that for you automatically (with a decorator).
While recursion often yields nice and easy formulas, python is not that good at evaluating them (see tail recursion). You are probably better off with rewriting it in a iterativ way and calculate that. | First of all you are calculating f[i-1] three times when you can save it's result in some variable and calculate it only once :
```
t = f(i-1)
return t-(1./n)*(1-(1-t)**n)-(1./n)*(t)**n+2.*T/n
```
It will increase the speed of the program, but I would also like to recommend to calculate f without using recursion.
```
fs = T
for i in range(1,N+1):
tmp = fs
fs = (tmp-(1./n)*(1-(1-tmp)**n)-(1./n)*(tmp)**n+2.*T/n)
``` |
32,667,047 | I want to program the following (I've just start to learn python):
```
f[i]:=f[i-1]-(1/n)*(1-(1-f[i-1])^n)-(1/n)*(f[i-1])^n+(2*f[0]/n);
```
with `F[0]=x`, `x` belongs to `[0,1]` and `n` a constant integer.
My try:
```
import pylab as pl
import numpy as np
N=20
n=100
h=0.01
T=np.arange(0, 1+h, h)
def f(i):
if i == 0:
return T
else:
return f(i-1)-(1./n)*(1-(1-f(i-1))**n)-(1./n)*(f(i-1))**n+2.*T/n
pl.figure(figsize=(10, 6), dpi=80)
pl.plot(T,f(N), color="red",linestyle='--', linewidth=2.5)
pl.show()
```
For `N=10` (number of iterations) it returns the correct plot fast enough, but for `N=20` it keeps running and running (more than 30 minutes already). | 2015/09/19 | [
"https://Stackoverflow.com/questions/32667047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5353182/"
] | The reason why your run time is so slow is the fact that, like the simplistic calculation of the nth fibonacci number it runs in **exponential time** (in this case 3^n). To see this, before F[i] can return it's value, it has to call f[i-1] 3 times, but then each of *those* has to call F[i-2] 3 times (3\*3 calls), and then each of *those* has to call F[i-3] 3 times (3\*3\*3 calls), and so on. In this example, as others have shown, this can be calculated simply in linear time. That you see it slow for N = 20 is because your function has to be called 3^20 = 3486784401 times before you get the answer! | First of all you are calculating f[i-1] three times when you can save it's result in some variable and calculate it only once :
```
t = f(i-1)
return t-(1./n)*(1-(1-t)**n)-(1./n)*(t)**n+2.*T/n
```
It will increase the speed of the program, but I would also like to recommend to calculate f without using recursion.
```
fs = T
for i in range(1,N+1):
tmp = fs
fs = (tmp-(1./n)*(1-(1-tmp)**n)-(1./n)*(tmp)**n+2.*T/n)
``` |
52,297,298 | i'm facing some issues while trying to fetch a bulk mail via python wincom32.client.
Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status..
the problem is that i didn't find out any way to resume/close/re-set and i can't ask for sysadmins to do it for me..
Here's my code snippet - i know it's ugly - but i'm using it on a jupiter notebook just to experiment/play around before arranging it down properly.
```
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
def create_message_list(folder):
return [{
"folder": folder.Name,
"sender" : m.Sender,
"recipients" : m.Recipients,
"subject" : m.subject,
"body":m.body
} for m in folder.Items]
for folder in outlook.Folders:
if (folder.Name=="myfolder.name"):
message_list = create_message_list(folder)
```
and here's what i get:
>
> com\_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft
> Outlook', 'Your server administrator has limited the number of items
> you can open simultaneously. Try closing messages you have opened or
> removing attachments and images from unsent messages you are
> composing.', None, 0, -2147220731), None).
>
>
>
Notice that i *had my sketch code working for a while*. i could fetch something like 10k messages before it messed up with that error.
Things i've been trying (with no result)
- try to close the folder / mapi session
- running a for loop on the same items and calling the message.Close(0)
- using the GetFirst() / GetLast() methods on message instead of list comprehension
thanks anyone for ideas/suggestions/whatever. | 2018/09/12 | [
"https://Stackoverflow.com/questions/52297298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8979081/"
] | the problem was due to using dictionary to store message data held somehow a reference to it, without letting the resource to be released, even if an explicit `m.Close(0)` was invoked.
I've replaced them all with a `"dictkey" : str(m.<field>)` call and the error does not show up anymore. | You keep *all* items in a folder open - that is a really bad idea. Store only the entry ids, and reopen the messages on demand using `Namespace.GetItemFromID`. As soon as you are done with the item, release it. |
52,297,298 | i'm facing some issues while trying to fetch a bulk mail via python wincom32.client.
Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status..
the problem is that i didn't find out any way to resume/close/re-set and i can't ask for sysadmins to do it for me..
Here's my code snippet - i know it's ugly - but i'm using it on a jupiter notebook just to experiment/play around before arranging it down properly.
```
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
def create_message_list(folder):
return [{
"folder": folder.Name,
"sender" : m.Sender,
"recipients" : m.Recipients,
"subject" : m.subject,
"body":m.body
} for m in folder.Items]
for folder in outlook.Folders:
if (folder.Name=="myfolder.name"):
message_list = create_message_list(folder)
```
and here's what i get:
>
> com\_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft
> Outlook', 'Your server administrator has limited the number of items
> you can open simultaneously. Try closing messages you have opened or
> removing attachments and images from unsent messages you are
> composing.', None, 0, -2147220731), None).
>
>
>
Notice that i *had my sketch code working for a while*. i could fetch something like 10k messages before it messed up with that error.
Things i've been trying (with no result)
- try to close the folder / mapi session
- running a for loop on the same items and calling the message.Close(0)
- using the GetFirst() / GetLast() methods on message instead of list comprehension
thanks anyone for ideas/suggestions/whatever. | 2018/09/12 | [
"https://Stackoverflow.com/questions/52297298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8979081/"
] | First of all thanks Equinox23 for your answer.
Just wanted to add few more points to it. The same thing happened for me while accessing bundles of outlook emails. Consider `list1` and `list2`, for every iteration I get the output `list1` and finally, append it to `list2` and reset the list1. After 230+ iterations, I got the same error. Here, the `list2` has reference for `list1` as Equinox23 mentioned and doesn't allow us to open multiple items at a time.
So, instead of directly appending `list1` to `list2` (like `list2.append(list1)`), I did the following as Equinox23 mentioned (`list2.append(str(list1))`) [Use the appropriate datatype like `str(list1)/int(list1)` and append it].
You can eliminate the error and can get the desired output. | You keep *all* items in a folder open - that is a really bad idea. Store only the entry ids, and reopen the messages on demand using `Namespace.GetItemFromID`. As soon as you are done with the item, release it. |
52,297,298 | i'm facing some issues while trying to fetch a bulk mail via python wincom32.client.
Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status..
the problem is that i didn't find out any way to resume/close/re-set and i can't ask for sysadmins to do it for me..
Here's my code snippet - i know it's ugly - but i'm using it on a jupiter notebook just to experiment/play around before arranging it down properly.
```
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
def create_message_list(folder):
return [{
"folder": folder.Name,
"sender" : m.Sender,
"recipients" : m.Recipients,
"subject" : m.subject,
"body":m.body
} for m in folder.Items]
for folder in outlook.Folders:
if (folder.Name=="myfolder.name"):
message_list = create_message_list(folder)
```
and here's what i get:
>
> com\_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft
> Outlook', 'Your server administrator has limited the number of items
> you can open simultaneously. Try closing messages you have opened or
> removing attachments and images from unsent messages you are
> composing.', None, 0, -2147220731), None).
>
>
>
Notice that i *had my sketch code working for a while*. i could fetch something like 10k messages before it messed up with that error.
Things i've been trying (with no result)
- try to close the folder / mapi session
- running a for loop on the same items and calling the message.Close(0)
- using the GetFirst() / GetLast() methods on message instead of list comprehension
thanks anyone for ideas/suggestions/whatever. | 2018/09/12 | [
"https://Stackoverflow.com/questions/52297298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8979081/"
] | the problem was due to using dictionary to store message data held somehow a reference to it, without letting the resource to be released, even if an explicit `m.Close(0)` was invoked.
I've replaced them all with a `"dictkey" : str(m.<field>)` call and the error does not show up anymore. | First of all thanks Equinox23 for your answer.
Just wanted to add few more points to it. The same thing happened for me while accessing bundles of outlook emails. Consider `list1` and `list2`, for every iteration I get the output `list1` and finally, append it to `list2` and reset the list1. After 230+ iterations, I got the same error. Here, the `list2` has reference for `list1` as Equinox23 mentioned and doesn't allow us to open multiple items at a time.
So, instead of directly appending `list1` to `list2` (like `list2.append(list1)`), I did the following as Equinox23 mentioned (`list2.append(str(list1))`) [Use the appropriate datatype like `str(list1)/int(list1)` and append it].
You can eliminate the error and can get the desired output. |
11,632,905 | >
> **Possible Duplicate:**
>
> [Inverse dictionary lookup - Python](https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python)
>
> [reverse mapping of dictionary with Python](https://stackoverflow.com/questions/3221475/reverse-mapping-of-dictionary-with-python)
>
>
>
How do i get key of index in dictionary?
For example like:
```
i = {'a': 0, 'b': 1, 'c': 2}
```
so if i want to get key of i[0], it will return 'a' | 2012/07/24 | [
"https://Stackoverflow.com/questions/11632905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1485698/"
] | Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
```
[k for (k, v) in i.iteritems() if v == 0]
```
Note that there can be more than one key per value in a dict; `{'a': 0, 'b': 0}` is perfectly legal.
If you want ordering you either need to use a list or a [OrderedDict instance](http://docs.python.org/library/collections.html#collections.OrderedDict) instead:
```
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
``` | By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. [Python Ordered Dictionary](http://docs.python.org/library/collections.html) |
11,632,905 | >
> **Possible Duplicate:**
>
> [Inverse dictionary lookup - Python](https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python)
>
> [reverse mapping of dictionary with Python](https://stackoverflow.com/questions/3221475/reverse-mapping-of-dictionary-with-python)
>
>
>
How do i get key of index in dictionary?
For example like:
```
i = {'a': 0, 'b': 1, 'c': 2}
```
so if i want to get key of i[0], it will return 'a' | 2012/07/24 | [
"https://Stackoverflow.com/questions/11632905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1485698/"
] | You *could* do something like this:
```
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
```
However, any time you change your dictionary, you'll need to update your keys,values because **dictionaries are not ordered in versions of Python prior to 3.7**. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
**As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.**
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
```
d={'i':1, 'j':1}
```
In that case, it is impossible to know whether you want `i` or `j` and in fact no answer here will be able to tell you which (`'i'` or `'j'`) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right. | By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. [Python Ordered Dictionary](http://docs.python.org/library/collections.html) |
11,632,905 | >
> **Possible Duplicate:**
>
> [Inverse dictionary lookup - Python](https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python)
>
> [reverse mapping of dictionary with Python](https://stackoverflow.com/questions/3221475/reverse-mapping-of-dictionary-with-python)
>
>
>
How do i get key of index in dictionary?
For example like:
```
i = {'a': 0, 'b': 1, 'c': 2}
```
so if i want to get key of i[0], it will return 'a' | 2012/07/24 | [
"https://Stackoverflow.com/questions/11632905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1485698/"
] | You *could* do something like this:
```
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
```
However, any time you change your dictionary, you'll need to update your keys,values because **dictionaries are not ordered in versions of Python prior to 3.7**. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
**As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.**
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
```
d={'i':1, 'j':1}
```
In that case, it is impossible to know whether you want `i` or `j` and in fact no answer here will be able to tell you which (`'i'` or `'j'`) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right. | Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
```
[k for (k, v) in i.iteritems() if v == 0]
```
Note that there can be more than one key per value in a dict; `{'a': 0, 'b': 0}` is perfectly legal.
If you want ordering you either need to use a list or a [OrderedDict instance](http://docs.python.org/library/collections.html#collections.OrderedDict) instead:
```
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
``` |
56,191,147 | Im trying to extract user identities from a smartcard, and I need to match this pattern: `CN=LAST.FIRST.MIDDLE.0000000000`
And have this result returned: `FIRST.LAST`
This would normaly be easy if I were doing this in my own code:
```
# python example
string = 'CN=LAST.FIRST.MIDDLE.000000000'
pattern = 'CN=(\w+)\.(\w+)\.'
match = regex.search(pattern, string)
parsedResult = match.groups()[1] + '.' + match.groups()[0]
```
Unfortunately, I am matching a pattern using [Keycloaks X.509 certmap web form](https://www.keycloak.org/docs/latest/server_admin/index.html#adding-x-509-client-certificate-authentication-to-a-browser-flow).
I am limited to using only one regular expression, and the regular expression can only contain one capturing group. This is an HTML form so there is no actual code used here, just a single regular expression.
It seems as if i need to have sub capturing groups, and return the second matched group first, and then the first matched group, all within the main capturing group. Is it possible for something like this to be done?
Also, I assume we are limited to whatever features are supported by Java because that is what the app runs on. | 2019/05/17 | [
"https://Stackoverflow.com/questions/56191147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5357869/"
] | I don't think this is possible with just one capturing group. If I read the documentation of keycloak correctly, the capturing group is actually the result of the regular expression. So you can either match FIRST or LAST or both in the original order, but not reorder. | Yes, it is possible. This expression might help you to do so:
```
CN=([A-Z]+)\.(([A-Z]+)+)\.([A-Z]+)\.([0-9]+)
```
### [Demo](https://regex101.com/r/iosym4/1)
[](https://i.stack.imgur.com/69QLP.png)
### RegEx
If this wasn't your desired expression, you can modify/change your expressions in [regex101.com](https://regex101.com/r/iosym4/1). For example, you add reduce the boundaries of the expression and much simplify it, if you want. For example, this would also work:
```
CN=(\w+)\.(\w+)(.*)
```
### RegEx Circuit
You can also visualize your expressions in [jex.im](https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24):
[](https://i.stack.imgur.com/D3VU2.png)
### Python Test
```
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"CN=([A-Z]+)\.(([A-Z]+)+)\.([A-Z]+)\.([0-9]+)"
test_str = "CN=LAST.FIRST.MIDDLE.000000000"
subst = "\\2\\.\\1"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
```
### JavaScript Demo
```js
const regex = /CN=([A-Z]+)\.(([A-Z]+)+)\.([A-Z]+)\.([0-9]+)/gm;
const str = `CN=LAST.FIRST.MIDDLE.000000000`;
const subst = `$2\.$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
``` |
54,604,608 | I have about 30 SEM (scanning-electron microscope) images like that:
[](https://i.stack.imgur.com/uFHNf.png)
What you see is photoresist pillars on a glass substrate.
What I would like to do, is to get the mean diameter in x and y-direction as well as the mean period in x- and y-direction.
Now, instead of doing all the measurement manually, I was wondering, if maybe there is a way to **automate it using python and opencv** ?
EDIT:
I tried the following code, it seems to be *working to detect circles*, **but what I actually need are ellipse,** since I need the diameter in x- and y-direction.
... and I don't quite see how to get the scale yet ?
```
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread("01.jpg",0)
output = img.copy()
edged = cv2.Canny(img, 10, 300)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
# detect circles in the image
circles = cv2.HoughCircles(edged, cv2.HOUGH_GRADIENT, 1.2, 100)
# ensure at least some circles were found
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles[0]:
print(x,y,r)
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(output, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# show the output image
plt.imshow(output, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.figure()
plt.show()
```
[](https://i.stack.imgur.com/aaITo.png)
Source of inspiration: <https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/> | 2019/02/09 | [
"https://Stackoverflow.com/questions/54604608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I rarely find Hough useful for realworld applications, thus I'd rather follow the path of denoising, segmentation and ellipse fit.
For the denoising, one selects the non local means (NLM). For the segmentation --- just looking at the image --- I came up with a Gaussian mixture model with three classes: one for background and two for the object (diffuse and specular component). Here, the mixture model essentially models the shape of the graylevel image histogram by three Gaussian functions (as demonstrated in [Wikipedia mixture-histogram gif](https://commons.wikimedia.org/wiki/File:Movie.gif)). Interested reader is redirected to [Wikipedia article](https://en.wikipedia.org/wiki/Mixture_model).
Ellipse fit at the end is just an elementary OpenCV-tool.
In C++, but in analogue to OpenCV-Python
```
#include "opencv2/ml.hpp"
#include "opencv2/photo.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
void gaussianMixture(const cv::Mat &src, cv::Mat &dst, int nClasses )
{
if ( src.type()!=CV_8UC1 )
CV_Error(CV_StsError,"src is not 8-bit grayscale");
// reshape
cv::Mat samples( src.rows * src.cols, 1, CV_32FC1 );
src.convertTo( cv::Mat( src.size(), CV_32FC1, samples.data ), CV_32F );
cv::Mat labels;
cv::Ptr<cv::ml::EM> em = cv::ml::EM::create();
em->setClustersNumber( nClasses );
em->setTermCriteria( cv::TermCriteria(CV_TERMCRIT_ITER, 4, 0.0 ) );
em->trainEM( samples );
if ( dst.type()!=CV_8UC1 || dst.size()!=src.size() )
dst = cv::Mat( src.size(),CV_8UC1 );
for(int y=0;y<src.rows;++y)
{
for(int x=0;x<src.cols;++x)
{
dst.at<unsigned char>(y,x) = em->predict( src.at<unsigned char>(y,x) );
}
}
}
void automate()
{
cv::Mat input = cv::imread( /* input image in color */,cv::IMREAD_COLOR);
cv::Mat inputDenoised;
cv::fastNlMeansDenoising( input, inputDenoised, 8.0, 5, 17 );
cv::Mat gray;
cv::cvtColor(inputDenoised,gray,cv::COLOR_BGR2GRAY );
gaussianMixture(gray,gray,3 );
typedef std::vector< std::vector< cv::Point > > VecOfVec;
VecOfVec contours;
cv::Mat objectPixels = gray>0;
cv::findContours( objectPixels, contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE );
cv::Mat inputcopy; // for drawing of ellipses
input.copyTo( inputcopy );
for ( size_t i=0;i<contours.size();++i )
{
if ( contours[i].size() < 5 )
continue;
cv::drawContours( input, VecOfVec{contours[i]}, -1, cv::Scalar(0,0,255), 2 );
cv::RotatedRect rect = cv::fitEllipse( contours[i] );
cv::ellipse( inputcopy, rect, cv::Scalar(0,0,255), 2 );
}
}
```
I should have cleaned the very small contours (in upper row second) (larger than the minimum 5 points) before drawing ellipses.
**\* edit \***
added Python predictor without the denoising and find-contours part. After learning the model, the time to predict is about 1.1 second
```
img = cv.imread('D:/tmp/8b3Lm.jpg', cv.IMREAD_GRAYSCALE )
class Predictor :
def train( self, img ):
self.em = cv.ml.EM_create()
self.em.setClustersNumber( 3 )
self.em.setTermCriteria( ( cv.TERM_CRITERIA_COUNT,4,0 ) )
samples = np.reshape( img, (img.shape[0]*img.shape[1], -1) ).astype('float')
self.em.trainEM( samples )
def predict( self, img ):
samples = np.reshape( img, (img.shape[0]*img.shape[1], -1) ).astype('float')
labels = np.zeros( samples.shape, 'uint8' )
for i in range ( samples.shape[0] ):
retval, probs = self.em.predict2( samples[i] )
labels[i] = retval[1] * (255/3) # make it [0,255] for imshow
return np.reshape( labels, img.shape )
predictor = Predictor()
predictor.train( img )
t = time.perf_counter()
predictor.train( img )
t = time.perf_counter() - t
print ( "train %s s" %t )
t = time.perf_counter()
labels = predictor.predict( img )
t = time.perf_counter() - t
print ( "predict %s s" %t )
cv.imshow( "prediction", labels )
cv.waitKey( 0 )
```
[](https://i.stack.imgur.com/8b3Lm.jpg)
[](https://i.stack.imgur.com/NFacS.jpg)
[](https://i.stack.imgur.com/cahH8.jpg)
[](https://i.stack.imgur.com/OXn51.png) | I would go with the `HoughCircles` method, from openCV. It will give you all the circles in the image. Then it will be easy to compute the radius and the position of each circles.
Look at : <https://docs.opencv.org/3.4/d4/d70/tutorial_hough_circle.html> |
54,604,608 | I have about 30 SEM (scanning-electron microscope) images like that:
[](https://i.stack.imgur.com/uFHNf.png)
What you see is photoresist pillars on a glass substrate.
What I would like to do, is to get the mean diameter in x and y-direction as well as the mean period in x- and y-direction.
Now, instead of doing all the measurement manually, I was wondering, if maybe there is a way to **automate it using python and opencv** ?
EDIT:
I tried the following code, it seems to be *working to detect circles*, **but what I actually need are ellipse,** since I need the diameter in x- and y-direction.
... and I don't quite see how to get the scale yet ?
```
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread("01.jpg",0)
output = img.copy()
edged = cv2.Canny(img, 10, 300)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
# detect circles in the image
circles = cv2.HoughCircles(edged, cv2.HOUGH_GRADIENT, 1.2, 100)
# ensure at least some circles were found
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles[0]:
print(x,y,r)
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(output, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# show the output image
plt.imshow(output, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.figure()
plt.show()
```
[](https://i.stack.imgur.com/aaITo.png)
Source of inspiration: <https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/> | 2019/02/09 | [
"https://Stackoverflow.com/questions/54604608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I rarely find Hough useful for realworld applications, thus I'd rather follow the path of denoising, segmentation and ellipse fit.
For the denoising, one selects the non local means (NLM). For the segmentation --- just looking at the image --- I came up with a Gaussian mixture model with three classes: one for background and two for the object (diffuse and specular component). Here, the mixture model essentially models the shape of the graylevel image histogram by three Gaussian functions (as demonstrated in [Wikipedia mixture-histogram gif](https://commons.wikimedia.org/wiki/File:Movie.gif)). Interested reader is redirected to [Wikipedia article](https://en.wikipedia.org/wiki/Mixture_model).
Ellipse fit at the end is just an elementary OpenCV-tool.
In C++, but in analogue to OpenCV-Python
```
#include "opencv2/ml.hpp"
#include "opencv2/photo.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
void gaussianMixture(const cv::Mat &src, cv::Mat &dst, int nClasses )
{
if ( src.type()!=CV_8UC1 )
CV_Error(CV_StsError,"src is not 8-bit grayscale");
// reshape
cv::Mat samples( src.rows * src.cols, 1, CV_32FC1 );
src.convertTo( cv::Mat( src.size(), CV_32FC1, samples.data ), CV_32F );
cv::Mat labels;
cv::Ptr<cv::ml::EM> em = cv::ml::EM::create();
em->setClustersNumber( nClasses );
em->setTermCriteria( cv::TermCriteria(CV_TERMCRIT_ITER, 4, 0.0 ) );
em->trainEM( samples );
if ( dst.type()!=CV_8UC1 || dst.size()!=src.size() )
dst = cv::Mat( src.size(),CV_8UC1 );
for(int y=0;y<src.rows;++y)
{
for(int x=0;x<src.cols;++x)
{
dst.at<unsigned char>(y,x) = em->predict( src.at<unsigned char>(y,x) );
}
}
}
void automate()
{
cv::Mat input = cv::imread( /* input image in color */,cv::IMREAD_COLOR);
cv::Mat inputDenoised;
cv::fastNlMeansDenoising( input, inputDenoised, 8.0, 5, 17 );
cv::Mat gray;
cv::cvtColor(inputDenoised,gray,cv::COLOR_BGR2GRAY );
gaussianMixture(gray,gray,3 );
typedef std::vector< std::vector< cv::Point > > VecOfVec;
VecOfVec contours;
cv::Mat objectPixels = gray>0;
cv::findContours( objectPixels, contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE );
cv::Mat inputcopy; // for drawing of ellipses
input.copyTo( inputcopy );
for ( size_t i=0;i<contours.size();++i )
{
if ( contours[i].size() < 5 )
continue;
cv::drawContours( input, VecOfVec{contours[i]}, -1, cv::Scalar(0,0,255), 2 );
cv::RotatedRect rect = cv::fitEllipse( contours[i] );
cv::ellipse( inputcopy, rect, cv::Scalar(0,0,255), 2 );
}
}
```
I should have cleaned the very small contours (in upper row second) (larger than the minimum 5 points) before drawing ellipses.
**\* edit \***
added Python predictor without the denoising and find-contours part. After learning the model, the time to predict is about 1.1 second
```
img = cv.imread('D:/tmp/8b3Lm.jpg', cv.IMREAD_GRAYSCALE )
class Predictor :
def train( self, img ):
self.em = cv.ml.EM_create()
self.em.setClustersNumber( 3 )
self.em.setTermCriteria( ( cv.TERM_CRITERIA_COUNT,4,0 ) )
samples = np.reshape( img, (img.shape[0]*img.shape[1], -1) ).astype('float')
self.em.trainEM( samples )
def predict( self, img ):
samples = np.reshape( img, (img.shape[0]*img.shape[1], -1) ).astype('float')
labels = np.zeros( samples.shape, 'uint8' )
for i in range ( samples.shape[0] ):
retval, probs = self.em.predict2( samples[i] )
labels[i] = retval[1] * (255/3) # make it [0,255] for imshow
return np.reshape( labels, img.shape )
predictor = Predictor()
predictor.train( img )
t = time.perf_counter()
predictor.train( img )
t = time.perf_counter() - t
print ( "train %s s" %t )
t = time.perf_counter()
labels = predictor.predict( img )
t = time.perf_counter() - t
print ( "predict %s s" %t )
cv.imshow( "prediction", labels )
cv.waitKey( 0 )
```
[](https://i.stack.imgur.com/8b3Lm.jpg)
[](https://i.stack.imgur.com/NFacS.jpg)
[](https://i.stack.imgur.com/cahH8.jpg)
[](https://i.stack.imgur.com/OXn51.png) | I use `cv2.ml.EM` to segment the image first in OpenCV (Python), it costs about `13 s`. If just `fitEllipse` on the contours of the threshed image, it costs `5 ms`, the the result maybe not that accurate. Just a tradeoff.
[](https://i.stack.imgur.com/4TXOn.jpg)
---
Details:
>
> 1. Convert into grayscale and threshed it
> 2. Morph to denoise
> 3. Find the external contours
> 4. Fit ellipses
>
>
>
---
Code:
```
#!/usr/bin/python3
# 2019/02/13
# https://stackoverflow.com/a/54604608/54661984
import cv2
import numpy as np
fpath = "sem.png"
img = cv2.imread(fpath)
## Convert into grayscale and threshed it
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)
## Morph to denoise
threshed = cv2.dilate(threshed, None)
threshed = cv2.erode(threshed, None)
## Find the external contours
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]
cv2.drawContours(img, cnts, -1, (255, 0, 0), 2, cv2.LINE_AA)
## Fit ellipses
for cnt in cnts:
if cnt.size < 10 or cv2.contourArea(cnt) < 100:
continue
rbox = cv2.fitEllipse(cnt)
cv2.ellipse(img, rbox, (255, 100, 255), 2, cv2.LINE_AA)
## This it
cv2.imwrite("dst.jpg", img)
``` |
12,285,754 | >
> **Possible Duplicate:**
>
> [Python dictionaries - find second character in a 2-character string which yields minimum value](https://stackoverflow.com/questions/12284913/python-dictionaries-find-second-character-in-a-2-character-string-which-yields)
>
>
>
I would like to submit the first item of a tuple key and return the remaining item of that key which minimizes the tuple key value.
For example:
```
d = {('a','b'): 100,
('a','c'): 200,
('a','d'): 500}
```
If I were to pass in `'a'`, I would like to return `'b'`. | 2012/09/05 | [
"https://Stackoverflow.com/questions/12285754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096991/"
] | ```
def func(d,y):
lis=sorted((x for x in d.items() if x[0][0]==y),key=lambda x:x[1])
return lis[0][0][1]
d ={('a','b'):100,('a','c'):200,('a','d'):500,('b','c'):1000,('b','e'):100}
```
output:
```
>>> func(d,'a')
'b'
>>> func(d,'b')
'e'
``` | ```
def minval(my_dict,var_name):
return min(filter(lambda x: x[0][0] == var_name,my_dict.items()),key=lambda x:x[1])[0][1]
print minval(d,'a')
```
I think Ashwins answer is probably better by pythonic simple is better than complex standards and they probably perform simillarly on a time scale ... his may even be faster ... |
12,285,754 | >
> **Possible Duplicate:**
>
> [Python dictionaries - find second character in a 2-character string which yields minimum value](https://stackoverflow.com/questions/12284913/python-dictionaries-find-second-character-in-a-2-character-string-which-yields)
>
>
>
I would like to submit the first item of a tuple key and return the remaining item of that key which minimizes the tuple key value.
For example:
```
d = {('a','b'): 100,
('a','c'): 200,
('a','d'): 500}
```
If I were to pass in `'a'`, I would like to return `'b'`. | 2012/09/05 | [
"https://Stackoverflow.com/questions/12285754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096991/"
] | Sorting is unnecessary here:
```
>>> d ={('a','b'):100,('a','c'):200,('a','d'):500,('b','c'):1000,('b','e'):100}
>>> def func(d, k0):
... return min((k for k in d if k[0] == k0), key=d.get)[1]
...
>>> func(d, 'a')
'b'
>>> func(d, 'b')
'e'
```
This works by using a generator expression to give only the keys in the dictionary whose first element matches the input, and uses as the associated "weight" (unfortunately named the "key" here in this context) the associated value in the dictionary. Dictionaries have a `.get` method which returns the value given a specific key, so that's the natural one to use.
Note that in the case of ties, this returns an arbitrary key. | ```
def minval(my_dict,var_name):
return min(filter(lambda x: x[0][0] == var_name,my_dict.items()),key=lambda x:x[1])[0][1]
print minval(d,'a')
```
I think Ashwins answer is probably better by pythonic simple is better than complex standards and they probably perform simillarly on a time scale ... his may even be faster ... |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Try adding:
```
position:absolute;
bottom: 0;
```
to your footer selector. | Well maybe it's because you have a min-height of 95%. If not, you can try:
```
#footer {
position: absolute;
bottom: 0;
margin: 0 auto;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Try adding:
```
position:absolute;
bottom: 0;
```
to your footer selector. | Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content.
In order to make sure your body's `min-height` styling works, add:
```
html { height: 100% }
```
Additionally, to make sure your footer always appears below the content, add
```
body {
margin: 0; //remove default margin. you may not need
//this, but it will prevent problems with
//the body being too big
min-height: 100%;
box-sizing: border-box; //making sure padding works with 100% sizing.
padding-bottom: 40px; //just enough for your footer
}
#footer {
position: absolute;
bottom: 0;
}
```
This will remove your footer from the flow of the page, *but that's OK*, since we have allocated a 40px space at the bottom of the page for it. |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Try adding:
```
position:absolute;
bottom: 0;
```
to your footer selector. | try this
```
#footer {
background: none repeat scroll 0 0 transparent;
color: #4BB3E6;
position: fixed;
text-align: right;
width: 100%;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Try adding:
```
position:absolute;
bottom: 0;
```
to your footer selector. | Use `positon:fixed`, DEMO <http://jsfiddle.net/VDfcC/>
```
#footer {
position:fixed;
left:0;
bottom:0;
z-index:10;
margin-right: 10%;
min-width: 100%;
color: #4bb3e6;
text-align: right;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content.
In order to make sure your body's `min-height` styling works, add:
```
html { height: 100% }
```
Additionally, to make sure your footer always appears below the content, add
```
body {
margin: 0; //remove default margin. you may not need
//this, but it will prevent problems with
//the body being too big
min-height: 100%;
box-sizing: border-box; //making sure padding works with 100% sizing.
padding-bottom: 40px; //just enough for your footer
}
#footer {
position: absolute;
bottom: 0;
}
```
This will remove your footer from the flow of the page, *but that's OK*, since we have allocated a 40px space at the bottom of the page for it. | Well maybe it's because you have a min-height of 95%. If not, you can try:
```
#footer {
position: absolute;
bottom: 0;
margin: 0 auto;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | try this
```
#footer {
background: none repeat scroll 0 0 transparent;
color: #4BB3E6;
position: fixed;
text-align: right;
width: 100%;
}
``` | Well maybe it's because you have a min-height of 95%. If not, you can try:
```
#footer {
position: absolute;
bottom: 0;
margin: 0 auto;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Use `positon:fixed`, DEMO <http://jsfiddle.net/VDfcC/>
```
#footer {
position:fixed;
left:0;
bottom:0;
z-index:10;
margin-right: 10%;
min-width: 100%;
color: #4bb3e6;
text-align: right;
}
``` | Well maybe it's because you have a min-height of 95%. If not, you can try:
```
#footer {
position: absolute;
bottom: 0;
margin: 0 auto;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content.
In order to make sure your body's `min-height` styling works, add:
```
html { height: 100% }
```
Additionally, to make sure your footer always appears below the content, add
```
body {
margin: 0; //remove default margin. you may not need
//this, but it will prevent problems with
//the body being too big
min-height: 100%;
box-sizing: border-box; //making sure padding works with 100% sizing.
padding-bottom: 40px; //just enough for your footer
}
#footer {
position: absolute;
bottom: 0;
}
```
This will remove your footer from the flow of the page, *but that's OK*, since we have allocated a 40px space at the bottom of the page for it. | try this
```
#footer {
background: none repeat scroll 0 0 transparent;
color: #4BB3E6;
position: fixed;
text-align: right;
width: 100%;
}
``` |
17,499,757 | I have configured a keyboard shortcut using xbindkeys to run a python script.
Now, while editing any vim file if that user press that keyboard shortcut-
* I want my python script to run this command to paste the path and line no to the system clipboard-
`:let @+=expand("%") . ':' . line(".")`
* Then I want my script to copy that path from the system clipboard and process it further
Can you please suggest me a good solution for this.
Thanks In advance | 2013/07/06 | [
"https://Stackoverflow.com/questions/17499757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1908544/"
] | Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content.
In order to make sure your body's `min-height` styling works, add:
```
html { height: 100% }
```
Additionally, to make sure your footer always appears below the content, add
```
body {
margin: 0; //remove default margin. you may not need
//this, but it will prevent problems with
//the body being too big
min-height: 100%;
box-sizing: border-box; //making sure padding works with 100% sizing.
padding-bottom: 40px; //just enough for your footer
}
#footer {
position: absolute;
bottom: 0;
}
```
This will remove your footer from the flow of the page, *but that's OK*, since we have allocated a 40px space at the bottom of the page for it. | Use `positon:fixed`, DEMO <http://jsfiddle.net/VDfcC/>
```
#footer {
position:fixed;
left:0;
bottom:0;
z-index:10;
margin-right: 10%;
min-width: 100%;
color: #4bb3e6;
text-align: right;
}
``` |
12,080,786 | I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
```
This naturally barfs with:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
```
How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?
Thanks! | 2012/08/22 | [
"https://Stackoverflow.com/questions/12080786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650424/"
] | When needing a literal `%` inside a Python formatting expression, use `%%`:
```
statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl)
```
See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information. | You don't need to use string interpolation. The execute method handles it for you, so you can do this instead:
```
statmt="select id from %s WHERE `email` LIKE %blah%"
self.cursor.execute(statmt, tbl)
``` |
12,080,786 | I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
```
This naturally barfs with:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
```
How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?
Thanks! | 2012/08/22 | [
"https://Stackoverflow.com/questions/12080786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650424/"
] | When needing a literal `%` inside a Python formatting expression, use `%%`:
```
statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl)
```
See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information. | You can use [`str.format`](http://docs.python.org/library/string.html#formatstrings):
```
statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl)
```
Make sure you're not creating a SQL injection vulnerability. |
12,080,786 | I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
```
This naturally barfs with:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
```
How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?
Thanks! | 2012/08/22 | [
"https://Stackoverflow.com/questions/12080786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650424/"
] | When needing a literal `%` inside a Python formatting expression, use `%%`:
```
statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl)
```
See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information. | you should escape your percent sign with `%%`
You should probably user parameterized queries though with `?` and `,` instead of string interpolation. |
12,080,786 | I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
```
This naturally barfs with:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
```
How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?
Thanks! | 2012/08/22 | [
"https://Stackoverflow.com/questions/12080786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650424/"
] | You don't need to use string interpolation. The execute method handles it for you, so you can do this instead:
```
statmt="select id from %s WHERE `email` LIKE %blah%"
self.cursor.execute(statmt, tbl)
``` | You can use [`str.format`](http://docs.python.org/library/string.html#formatstrings):
```
statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl)
```
Make sure you're not creating a SQL injection vulnerability. |
12,080,786 | I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
```
This naturally barfs with:
```
statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
```
How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?
Thanks! | 2012/08/22 | [
"https://Stackoverflow.com/questions/12080786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650424/"
] | you should escape your percent sign with `%%`
You should probably user parameterized queries though with `?` and `,` instead of string interpolation. | You can use [`str.format`](http://docs.python.org/library/string.html#formatstrings):
```
statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl)
```
Make sure you're not creating a SQL injection vulnerability. |
32,239,094 | I have text files which look like this (much longer, this is just some lines from it):
```
ATOM 6 H2 ACD Z 1 47.434 34.593 -4.121 1.000
ATOM 7 C ACT Z 2 47.465 33.050 -2.458 1.000
ATOM 8 O ACT Z 2 48.004 33.835 -1.687 1.000
ATOM 9 CH1 ACT Z 2 47.586 33.197 -3.960 1.000
ATOM 79 H1 EOL Z 14 46.340 32.495 2.495 1.000
ATOM 80 C1 PHN Z 15 46.992 33.059 -2.874 1.000
ATOM 81 C2 PHN Z 15 46.876 32.765 -1.499 1.000
ATOM 82 C3 PHN Z 15 46.836 31.422 -1.079 1.000
```
In the 6. "column" I have to change all of the numbers to 1, without changing the other numbers. I tried to define a function but it doesn't work (replace\_numbers). This means that the script runs and everything is ok just the numbers don't change.
Here is an example what I want:
```
ATOM 6 H2 LIG Z 1 47.434 34.593 -4.121 1.000
ATOM 7 C LIG Z 1 47.465 33.050 -2.458 1.000
ATOM 8 O LIG Z 1 48.004 33.835 -1.687 1.000
ATOM 9 CH1 LIG Z 1 47.586 33.197 -3.960 1.000
ATOM 79 H1 LIG Z 1 46.340 32.495 2.495 1.000
ATOM 80 C1 LIG Z 1 46.992 33.059 -2.874 1.000
ATOM 81 C2 LIG Z 1 46.876 32.765 -1.499 1.000
ATOM 82 C3 LIG Z 1 46.836 31.422 -1.079 1.000
```
I copy my whole script. Comments are in Hungarian.
```
#!/usr/bin/python
import os
import sys
import re
# en kodom
molecules = {"ETH":"LIG", "EOL":"LIG", "THS":"LIG", "BUT":"LIG", "ACN":"LIG",
"AMN":"LIG", "DFO":"LIG", "DME":"LIG", "BDY":"LIG", "BEN":"LIG",
"CHX":"LIG", "PHN":"LIG", "ACD":"LIG", "ACT":"LIG", "ADY":"LIG",
"URE":"LIG"}
numbers = {x: '1' for x in range(1, 50)}
def replace_numbers(i):
i_list = i.split()
if i_list[0] == "ATOM":
i_list[5] = '1 '
i_list[0] = i_list[0] + ' '
i_list[1] = i_list[1] + ' '
i_list[2] = i_list[2] + ' '
i_list[3] = i_list[3] + ' '
i_list[4] = i_list[4] + ' '
i_list[6] = i_list[6] + ' '
i_list[7] = i_list[7] + ' '
i_list[8] = i_list[8] + ' '
i = ''.join(i_list)
return i
def replace_all(text, dic):
for z, zs in dic.iteritems():
text = text.replace(z, zs)
return text
# en kodom end
def split_file(f, n, dirname):
data = f.readlines() # az input fajl minden sorat olvassa es listat csinal a sorokbol
concat_data = "".join(data) # egy olyan szoveget ad vissza ami a data-bol all
split_data = concat_data.split("HEADER ") # felbontja a concat_data-t, a hatarolojel a HEADER - nincs benne
header = ""
result = []
for i in split_data:
if i.startswith("protein"):
header = i
if i.startswith("crosscluster"):
crs_cluster_num = int(re.findall(r"crosscluster\.\d*\.(\d*)\.pdb", i)[0])
# ez hogy csinalja amit csinal?
if crs_cluster_num > 16:
#en kodom
i = replace_all(i, molecules)
i = replace_numbers(i)
#en kodom end
result.append(i) # hozzaadja a result nevu listahoz
for output in result:
with open(str(dirname) + "_output"+str(n)+".pdb","w") as out_file: # az aoutput nevet es helyet adja meg
out_file.write("HEADER " + header) # hozzaadja a HEADER-t es beirja a proteint
out_file.write("HEADER " + output) # hozzaadja a HEADER szoveget illetve proteineket egyesevel
out_file.write("#PROTEINTAG\n#PROBETAG ZYXWVUTSR") # hozzaadja az utolso sorokat a vegehez
out_file.close()
n += 1 # ?
return n
if __name__ == "__main__": # ?
n = 1
for dirname, dirnames, filenames in os.walk("/home/georgina/proba"):
for filename in filenames:
file_path = str(os.path.join(dirname, filename))
print dirname
if filename.endswith(".pdb"):
file_to_split = open(file_path, "r") # megnyitja a szetbontando fajlt
n = split_file(file_to_split, n, dirname) # a split_file funkcio behivasa
file_to_split.close()
```
I tried this with regular expression, with same result.
```
def replace_numbers(text):
expr = re.compile(r'(LIG )([A-Z])\s*\d*(\s*)')
expr.sub(r'\1\2 1,\3', text)
return text
``` | 2015/08/27 | [
"https://Stackoverflow.com/questions/32239094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261433/"
] | I was looking for the same thing. I ended up with the following solution:
```
figure = plt.figure(figsize=(6,9), dpi=100);
graph = figure.add_subplot(111);
freq = pandas.value_counts(data)
bins = freq.index
x=graph.bar(bins, freq.values) #gives the graph without NaN
graphmissing = figure.add_subplot(111)
y = graphmissing.bar([0], freq[numpy.NaN]) #gives a bar for the number of missing values at x=0
figure.show()
```
This gave me a histogram with a column at 0 showing the number of missing values in the data. | As pointed out by [Sreeram TP](https://stackoverflow.com/users/7896849/sreeram-tp), it is possible to use the argument dropna=False in the function value\_counts to include the counts of NaNs.
```
df = pd.DataFrame({'feature1': [1, 2, 2, 4, 3, 2, 3, 4, np.NaN],
'feature2': [4, 4, 3, 4, 1, 4, 3, np.NaN, np.NaN]})
# Calculates the histogram for feature1
counts = df['feature1'].value_counts(dropna=False)
counts.plot.bar(title='feat1', grid=True)
```
I can not insert images. So, here is the result:
[image plot here](https://i.stack.imgur.com/fdXtl.png) |
32,239,094 | I have text files which look like this (much longer, this is just some lines from it):
```
ATOM 6 H2 ACD Z 1 47.434 34.593 -4.121 1.000
ATOM 7 C ACT Z 2 47.465 33.050 -2.458 1.000
ATOM 8 O ACT Z 2 48.004 33.835 -1.687 1.000
ATOM 9 CH1 ACT Z 2 47.586 33.197 -3.960 1.000
ATOM 79 H1 EOL Z 14 46.340 32.495 2.495 1.000
ATOM 80 C1 PHN Z 15 46.992 33.059 -2.874 1.000
ATOM 81 C2 PHN Z 15 46.876 32.765 -1.499 1.000
ATOM 82 C3 PHN Z 15 46.836 31.422 -1.079 1.000
```
In the 6. "column" I have to change all of the numbers to 1, without changing the other numbers. I tried to define a function but it doesn't work (replace\_numbers). This means that the script runs and everything is ok just the numbers don't change.
Here is an example what I want:
```
ATOM 6 H2 LIG Z 1 47.434 34.593 -4.121 1.000
ATOM 7 C LIG Z 1 47.465 33.050 -2.458 1.000
ATOM 8 O LIG Z 1 48.004 33.835 -1.687 1.000
ATOM 9 CH1 LIG Z 1 47.586 33.197 -3.960 1.000
ATOM 79 H1 LIG Z 1 46.340 32.495 2.495 1.000
ATOM 80 C1 LIG Z 1 46.992 33.059 -2.874 1.000
ATOM 81 C2 LIG Z 1 46.876 32.765 -1.499 1.000
ATOM 82 C3 LIG Z 1 46.836 31.422 -1.079 1.000
```
I copy my whole script. Comments are in Hungarian.
```
#!/usr/bin/python
import os
import sys
import re
# en kodom
molecules = {"ETH":"LIG", "EOL":"LIG", "THS":"LIG", "BUT":"LIG", "ACN":"LIG",
"AMN":"LIG", "DFO":"LIG", "DME":"LIG", "BDY":"LIG", "BEN":"LIG",
"CHX":"LIG", "PHN":"LIG", "ACD":"LIG", "ACT":"LIG", "ADY":"LIG",
"URE":"LIG"}
numbers = {x: '1' for x in range(1, 50)}
def replace_numbers(i):
i_list = i.split()
if i_list[0] == "ATOM":
i_list[5] = '1 '
i_list[0] = i_list[0] + ' '
i_list[1] = i_list[1] + ' '
i_list[2] = i_list[2] + ' '
i_list[3] = i_list[3] + ' '
i_list[4] = i_list[4] + ' '
i_list[6] = i_list[6] + ' '
i_list[7] = i_list[7] + ' '
i_list[8] = i_list[8] + ' '
i = ''.join(i_list)
return i
def replace_all(text, dic):
for z, zs in dic.iteritems():
text = text.replace(z, zs)
return text
# en kodom end
def split_file(f, n, dirname):
data = f.readlines() # az input fajl minden sorat olvassa es listat csinal a sorokbol
concat_data = "".join(data) # egy olyan szoveget ad vissza ami a data-bol all
split_data = concat_data.split("HEADER ") # felbontja a concat_data-t, a hatarolojel a HEADER - nincs benne
header = ""
result = []
for i in split_data:
if i.startswith("protein"):
header = i
if i.startswith("crosscluster"):
crs_cluster_num = int(re.findall(r"crosscluster\.\d*\.(\d*)\.pdb", i)[0])
# ez hogy csinalja amit csinal?
if crs_cluster_num > 16:
#en kodom
i = replace_all(i, molecules)
i = replace_numbers(i)
#en kodom end
result.append(i) # hozzaadja a result nevu listahoz
for output in result:
with open(str(dirname) + "_output"+str(n)+".pdb","w") as out_file: # az aoutput nevet es helyet adja meg
out_file.write("HEADER " + header) # hozzaadja a HEADER-t es beirja a proteint
out_file.write("HEADER " + output) # hozzaadja a HEADER szoveget illetve proteineket egyesevel
out_file.write("#PROTEINTAG\n#PROBETAG ZYXWVUTSR") # hozzaadja az utolso sorokat a vegehez
out_file.close()
n += 1 # ?
return n
if __name__ == "__main__": # ?
n = 1
for dirname, dirnames, filenames in os.walk("/home/georgina/proba"):
for filename in filenames:
file_path = str(os.path.join(dirname, filename))
print dirname
if filename.endswith(".pdb"):
file_to_split = open(file_path, "r") # megnyitja a szetbontando fajlt
n = split_file(file_to_split, n, dirname) # a split_file funkcio behivasa
file_to_split.close()
```
I tried this with regular expression, with same result.
```
def replace_numbers(text):
expr = re.compile(r'(LIG )([A-Z])\s*\d*(\s*)')
expr.sub(r'\1\2 1,\3', text)
return text
``` | 2015/08/27 | [
"https://Stackoverflow.com/questions/32239094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261433/"
] | I was looking for the same thing. I ended up with the following solution:
```
figure = plt.figure(figsize=(6,9), dpi=100);
graph = figure.add_subplot(111);
freq = pandas.value_counts(data)
bins = freq.index
x=graph.bar(bins, freq.values) #gives the graph without NaN
graphmissing = figure.add_subplot(111)
y = graphmissing.bar([0], freq[numpy.NaN]) #gives a bar for the number of missing values at x=0
figure.show()
```
This gave me a histogram with a column at 0 showing the number of missing values in the data. | Did you try replacing NaN with some other unique value and then plot the histogram?
```
x= some unique value
plt.hist(df.replace(np.nan, x)
``` |
8,774,032 | I'm trying to send a POST request to a web app. I'm using the mechanize module (itself a wrapper of urllib2). Anyway, when I try to send a POST request, I get `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)`. I tried putting the `unicode(string)`, the `unicode(string, encoding="utf-8")`, `unicode(string).encode()` etc, nothing worked - either returned the error above, or the `TypeError: decoding Unicode is not supported`
I looked at the other SO answers to similar questions, but none helped.
Thanks in advance!
**EDIT**: Example that produces an error:
```
prda = "šđćč" #valid UTF-8 characters
prda # typing in python shell
'\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d'
print prda # in shell
šđćč
prda.encode("utf-8") #in shell
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)
unicode(prda)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)
``` | 2012/01/07 | [
"https://Stackoverflow.com/questions/8774032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647897/"
] | I assume you're using Python 2.x.
Given a unicode object:
```
myUnicode = u'\u4f60\u597d'
```
encode it using utf-8:
```
mystr = myUnicode.encode('utf-8')
```
Note that you need to specify the encoding explicitly. By default it'll (usually) use ascii. | You don't need to wrap your chars in `unicode` calls, because they're already encoded :) if anything, you need to **DE**-code it to get a unicode object:
```
>>> s = '\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d' # your string
>>> s.decode('utf-8')
u'\u0161\u0111\u0107\u010d'
>>> type(s.decode('utf-8'))
<type 'unicode'>
```
I don't know `mechanize` so I don't know exactly whether it handles it correctly or not, I'm afraid.
What I'd do with a regular `urllib2` POST call, would be to use `urlencode` :
```
>>> from urllib import urlencode
>>> postData = urlencode({'test': s }) # note I'm NOT decoding it
>>> postData
'test=%C5%A1%C4%91%C4%87%C4%8D'
>>> urllib2.urlopen(url, postData) # etc etc etc
``` |
8,774,032 | I'm trying to send a POST request to a web app. I'm using the mechanize module (itself a wrapper of urllib2). Anyway, when I try to send a POST request, I get `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)`. I tried putting the `unicode(string)`, the `unicode(string, encoding="utf-8")`, `unicode(string).encode()` etc, nothing worked - either returned the error above, or the `TypeError: decoding Unicode is not supported`
I looked at the other SO answers to similar questions, but none helped.
Thanks in advance!
**EDIT**: Example that produces an error:
```
prda = "šđćč" #valid UTF-8 characters
prda # typing in python shell
'\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d'
print prda # in shell
šđćč
prda.encode("utf-8") #in shell
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)
unicode(prda)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)
``` | 2012/01/07 | [
"https://Stackoverflow.com/questions/8774032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647897/"
] | I assume you're using Python 2.x.
Given a unicode object:
```
myUnicode = u'\u4f60\u597d'
```
encode it using utf-8:
```
mystr = myUnicode.encode('utf-8')
```
Note that you need to specify the encoding explicitly. By default it'll (usually) use ascii. | In your example, you use a non-unicode string literal containing non-ascii characters, which results in `prda` becoming a *bytes* string.
To achieve this, python uses `sys.stdin.encoding` to automatically encode the string. In your case, this means the string is gets encoded as "utf-8".
To convert `prda` to a *unicode* object, you need to decode it using the appropriate encoding:
```
>>> print prda.decode('utf-8')
šđćč
```
Note that, in a script or module, you cannot rely on python to automatically guess the encoding - you would need to explicitly delare the encoding at the top of the file, like this:
```
# -*- coding: utf-8 -*-
```
Whenever you encounter unicode errors in Python 2, it is very often because your code is mixing bytes strings with unicode strings. So you should always check what kind of string is causing the error, by using `type(string)`.
If the string object is `<type 'str'>`, but you need unicode, *decode* it using the appropriate encoding. If the string object is `<type 'unicode'>`, but you need bytes, *encode* it using the appropriate encoding. |
8,774,032 | I'm trying to send a POST request to a web app. I'm using the mechanize module (itself a wrapper of urllib2). Anyway, when I try to send a POST request, I get `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)`. I tried putting the `unicode(string)`, the `unicode(string, encoding="utf-8")`, `unicode(string).encode()` etc, nothing worked - either returned the error above, or the `TypeError: decoding Unicode is not supported`
I looked at the other SO answers to similar questions, but none helped.
Thanks in advance!
**EDIT**: Example that produces an error:
```
prda = "šđćč" #valid UTF-8 characters
prda # typing in python shell
'\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d'
print prda # in shell
šđćč
prda.encode("utf-8") #in shell
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)
unicode(prda)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)
``` | 2012/01/07 | [
"https://Stackoverflow.com/questions/8774032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/647897/"
] | In your example, you use a non-unicode string literal containing non-ascii characters, which results in `prda` becoming a *bytes* string.
To achieve this, python uses `sys.stdin.encoding` to automatically encode the string. In your case, this means the string is gets encoded as "utf-8".
To convert `prda` to a *unicode* object, you need to decode it using the appropriate encoding:
```
>>> print prda.decode('utf-8')
šđćč
```
Note that, in a script or module, you cannot rely on python to automatically guess the encoding - you would need to explicitly delare the encoding at the top of the file, like this:
```
# -*- coding: utf-8 -*-
```
Whenever you encounter unicode errors in Python 2, it is very often because your code is mixing bytes strings with unicode strings. So you should always check what kind of string is causing the error, by using `type(string)`.
If the string object is `<type 'str'>`, but you need unicode, *decode* it using the appropriate encoding. If the string object is `<type 'unicode'>`, but you need bytes, *encode* it using the appropriate encoding. | You don't need to wrap your chars in `unicode` calls, because they're already encoded :) if anything, you need to **DE**-code it to get a unicode object:
```
>>> s = '\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d' # your string
>>> s.decode('utf-8')
u'\u0161\u0111\u0107\u010d'
>>> type(s.decode('utf-8'))
<type 'unicode'>
```
I don't know `mechanize` so I don't know exactly whether it handles it correctly or not, I'm afraid.
What I'd do with a regular `urllib2` POST call, would be to use `urlencode` :
```
>>> from urllib import urlencode
>>> postData = urlencode({'test': s }) # note I'm NOT decoding it
>>> postData
'test=%C5%A1%C4%91%C4%87%C4%8D'
>>> urllib2.urlopen(url, postData) # etc etc etc
``` |
60,230,124 | I am trying to read a stream from kafka using pyspark. I am using **spark version 3.0.0-preview2** and **spark-streaming-kafka-0-10\_2.12**
Before this I just stat zookeeper, kafka and create a new topic:
```
/usr/local/kafka/bin/zookeeper-server-start.sh /usr/local/kafka/config/zookeeper.properties
/usr/local/kafka/bin/kafka-server-start.sh /usr/local/kafka/config/server.properties
/usr/local/kafka/bin/kafka-topics.sh --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic data_wm
```
This is my code:
```
import pandas as pd
import os
import findspark
findspark.init("/usr/local/spark")
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("TestApp").getOrCreate()
df = spark \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092") \
.option("subscribe", "data_wm") \
.load()
value = df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)")
```
This how I run my script:
>
> sudo --preserve-env=pyspark /usr/local/spark/bin/pyspark --packages
> org.apache.spark:spark-streaming-kafka-0-10\_2.12:3.0.0-preview
>
>
>
As result for this command I have this :
```
: resolving dependencies :: org.apache.spark#spark-submit-parent-0d7b2a8d-a860-4766-a4c7-141a902d8365;1.0
confs: [default]
found org.apache.spark#spark-streaming-kafka-0-10_2.12;3.0.0-preview in central
found org.apache.spark#spark-token-provider-kafka-0-10_2.12;3.0.0-preview in central
found org.apache.kafka#kafka-clients;2.3.1 in central
found com.github.luben#zstd-jni;1.4.3-1 in central
found org.lz4#lz4-java;1.6.0 in central
found org.xerial.snappy#snappy-java;1.1.7.3 in central
found org.slf4j#slf4j-api;1.7.16 in central
found org.spark-project.spark#unused;1.0.0 in central :: resolution report :: resolve 380ms :: artifacts dl 7ms
:: modules in use:
com.github.luben#zstd-jni;1.4.3-1 from central in [default]
org.apache.kafka#kafka-clients;2.3.1 from central in [default]
org.apache.spark#spark-streaming-kafka-0-10_2.12;3.0.0-preview from central in [default]
org.apache.spark#spark-token-provider-kafka-0-10_2.12;3.0.0-preview from central in [default]
org.lz4#lz4-java;1.6.0 from central in [default]
org.slf4j#slf4j-api;1.7.16 from central in [default]
org.spark-project.spark#unused;1.0.0 from central in [default]
org.xerial.snappy#snappy-java;1.1.7.3 from central in [default]
```
But I have always this error:
d> f = spark \ ... .readStream \ ... .format("kafka") \ ...
>
> .option("kafka.bootstrap.servers", "localhost:9092") \ ...
>
> .option("subscribe", "data\_wm") \ ... .load() Traceback (most
> recent call last): File "", line 5, in File
> "/usr/local/spark/python/pyspark/sql/streaming.py", line 406, in load
> return self.\_df(self.\_jreader.load()) File "/usr/local/spark/python/lib/py4j-0.10.8.1-src.zip/py4j/java\_gateway.py",
> line 1286, in **call** File
> "/usr/local/spark/python/pyspark/sql/utils.py", line 102, in deco
> **raise converted pyspark.sql.utils.AnalysisException: Failed to find data source: kafka. Please deploy the application as per the
> deployment section of "Structured Streaming + Kafka Integration**
> Guide".;
>
>
>
I don't know the cause of this error, please help | 2020/02/14 | [
"https://Stackoverflow.com/questions/60230124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5674606/"
] | I have successfully resolved this error on Spark 3.0.1 (using PySpark).
I would keep things simple and provide the desired packages through the `--packages` argument:
```bash
spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.0.1 MyPythonScript.py
```
**Mind the order of arguments otherwise it will throw an error.**
Where `MyPythonScript.py` has:
```py
KAFKA_TOPIC = "data_wm"
KAFKA_SERVER = "localhost:9092"
# creating an instance of SparkSession
spark_session = SparkSession \
.builder \
.appName("Python Spark create RDD") \
.getOrCreate()
# Subscribe to 1 topic
df = spark_session \
.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", KAFKA_SERVER) \
.option("subscribe", KAFKA_TOPIC) \
.load()
print(df.selectExpr("CAST(key AS STRING)", "CAST(value AS STRING)"))
``` | If you check the documentation mentioned in the error, it indicates to download a different package - `spark-sql-kafka`, **not** `spark-streaming-kafka`. You can see in your `resolving dependencies` log section, you do not have that.
You can also add packages via findspark rather than at the CLI |
57,372,207 | ```
G:\Git\advsol\projects\autotune>conda env create -f env.yml -n auto-tune
Using Anaconda API: https://api.anaconda.org
Fetching package metadata .................
ResolvePackageNotFound:
- matplotlib 2.1.1 py35_0
G:\Git\advsol\projects\autotune>
```
I have tried "conda install matplotlib==2.1.1"
it doesn't work
this is the env.yml file
```
name: auto-tune
channels:
- menpo
- conda-forge
- defaults
dependencies:
- backports=1.0=py35_1
- backports.functools_lru_cache=1.4=py35_1
- boost-cpp=1.64.0=vc14_1
- ca-certificates=2017.7.27.1=0
- certifi=2017.7.27.1=py35_0
- cloudpickle=0.4.0=py35_0
- colorama=0.3.9=py35_0
- cycler=0.10.0=py35_0
- dask-core=0.16.0=py_0
- decorator=4.1.2=py35_0
- eigen=3.3.3=0
- expat=2.2.5=vc14_0
- freetype=2.7=vc14_2
- future=0.16.0=py35_0
- icu=58.1=vc14_1
- imageio=2.2.0=py35_0
- ipykernel=4.6.1=py35_0
- ipyparallel=6.0.2=py35_0
- ipython=6.2.1=py35_0
- ipython_genutils=0.2.0=py35_0
- jedi=0.10.2=py35_0
- jpeg=9b=vc14_2
- jupyter_client=5.2.2=py35_0
- jupyter_core=4.4.0=py_0
- libiconv=1.14=vc14_4
- libpng=1.6.28=vc14_2
- libsodium=1.0.15=vc14_1
- libtiff=4.0.7=vc14_1
- libxml2=2.9.5=vc14_1
- matplotlib=2.1.1=py35_0
- mayavi=4.5.0=np111py35_vc14_1
- networkx=1.11=py35_0
- nlopt=2.4.2=py35_vc14_2
- olefile=0.44=py35_0
- openssl=1.0.2l=vc14_0
- pagmo=2.4=vc14_1
- pickleshare=0.7.4=py35_0
- pillow=4.3.0=py35_1
- prompt_toolkit=1.0.15=py35_0
- pygments=2.2.0=py35_0
- pygmo=2.4=np111py35_0
- pyparsing=2.2.0=py35_0
- pyqt=5.6.0=py35_4
- python=3.5.4=0
- python-dateutil=2.6.1=py35_0
- pytz=2017.3=py_2
- pywavelets=0.5.2=py35_1
- pyzmq=16.0.2=py35_3
- qt=5.6.2=vc14_1
- scikit-image=0.13.0=py35_3
- setuptools=36.6.0=py35_1
- simplegeneric=0.8.1=py35_0
- sip=4.18=py35_1
- six=1.11.0=py35_1
- sqlite=3.20.1=vc14_2
- tbb=2018_20170919=vc14_0
- tk=8.5.19=vc14_1
- toolz=0.8.2=py_2
- tornado=4.5.2=py35_0
- traitlets=4.3.2=py35_0
- traits=4.6.0=py35_1
- vc=14=0
- vs2015_runtime=14.0.25420=0
- vtk=7.1.0=py35_vc14_4
- wcwidth=0.1.7=py35_0
- wheel=0.30.0=py35_2
- win_unicode_console=0.5=py35_0
- wincertstore=0.2=py35_0
- yaml=0.1.7=vc14_0
- zeromq=4.2.3=vc14_2
- zlib=1.2.11=vc14_0
- configobj=5.0.6=py35_0
- icc_rt=2017.0.4=h97af966_0
- intel-openmp=2018.0.0=hcd89f80_7
- mkl=2018.0.0=h36b65af_4
- numpy=1.11.3=py35h4fc39be_3
- pip=9.0.1=py35_0
- scikit-learn=0.19.1=py35h2037775_0
- scipy=1.0.0=py35h75710e8_0
- apptools=4.4.0=py35_0
- boost=1.63.0=py35_vc14_2
- envisage=4.5.1=py35_0
- opencv3=3.1.0=py35_0
- pyface=5.1.0=py35_0
- traitsui=5.1.0=py35_0
- pip:
- absl-py==0.1.7
- backports.functools-lru-cache==1.4
- bleach==1.5.0
- colour-demosaicing==0.1.2
- colour-science==0.3.10
- dask==0.16.0
- entrypoints==0.2.3
- exifread==2.1.2
- gast==0.2.0
- html5lib==0.9999999
- ipython-genutils==0.2.0
- ipywidgets==7.1.1
- jinja2==2.10
- jsonschema==2.6.0
- jupyter==1.0.0
- jupyter-client==5.2.2
- jupyter-console==5.2.0
- jupyter-core==4.4.0
- markdown==2.6.10
- markupsafe==1.0
- mistune==0.8.3
- nbconvert==5.3.1
- nbformat==4.4.0
- nose==1.3.7
- notebook==5.4.0
- pandocfilters==1.4.2
- prompt-toolkit==1.0.15
- protobuf==3.5.1
- pywinpty==0.5.1
- qtconsole==4.3.1
- rawpy==0.10.1
- send2trash==1.4.2
- tb-nightly==1.5.0a20180102
- terminado==0.8.1
- testpath==0.3.1
- tf-nightly==1.5.0.dev20180102
- werkzeug==0.14.1
- widgetsnbextension==3.1.3
- win-unicode-console==0.5
prefix: G:\ProgramData\Anaconda3_501\envs\auto-tune
```
**Update I tried conda install matplotlib=2.1.1**
```
G:\Git\advsol\projects\autotune>conda install matplotlib=2.1.1
Fetching package metadata .............
Solving package specifications: .
Package plan for installation in environment C:\ProgramData\Anaconda3:
The following NEW packages will be INSTALLED:
blas: 1.0-mkl
conda-package-handling: 1.3.11-py36_0
libarchive: 3.3.3-h798a506_1
lz4-c: 1.8.1.2-h2fa13f4_0
python-libarchive-c: 2.8-py36_11
tqdm: 4.32.1-py_0
xz: 5.2.4-h2fa13f4_4
zstd: 1.3.3-hfe6a214_0
The following packages will be UPDATED:
conda: 4.3.30-py36h7e176b0_0 --> 4.7.10-py36_0
conda-env: 2.6.0-h36134e3_1 --> 2.6.0-1
libxml2: 2.9.4-vc14h8fd0f11_5 --> 2.9.8-hadb2253_1
matplotlib: 2.1.0-py36h11b4b9c_0 --> 2.1.1-py36h2062329_0
menuinst: 1.4.10-py36h42196fb_0 --> 1.4.14-py36hfa6e2cd_0
openssl: 1.0.2l-vc14hcac20b0_2 --> 1.0.2p-hfa6e2cd_0
pycosat: 0.6.2-py36hf17546d_1 --> 0.6.3-py36hfa6e2cd_0
Proceed ([y]/n)? y
menuinst-1.4.1 100% |###############################| Time: 0:00:00 11.74 MB/s
blas-1.0-mkl.t 100% |###############################| Time: 0:00:00 1.55 MB/s
conda-env-2.6. 100% |###############################| Time: 0:00:00 938.32 kB/s
lz4-c-1.8.1.2- 100% |###############################| Time: 0:00:00 18.51 MB/s
openssl-1.0.2p 100% |###############################| Time: 0:00:00 34.74 MB/s
xz-5.2.4-h2fa1 100% |###############################| Time: 0:00:00 16.77 MB/s
libxml2-2.9.8- 100% |###############################| Time: 0:00:00 28.75 MB/s
pycosat-0.6.3- 100% |###############################| Time: 0:00:00 16.66 MB/s
tqdm-4.32.1-py 100% |###############################| Time: 0:00:00 11.74 MB/s
zstd-1.3.3-hfe 100% |###############################| Time: 0:00:00 20.92 MB/s
libarchive-3.3 100% |###############################| Time: 0:00:00 22.73 MB/s
python-libarch 100% |###############################| Time: 0:00:00 7.77 MB/s
conda-package- 100% |###############################| Time: 0:00:00 28.76 MB/s
matplotlib-2.1 100% |###############################| Time: 0:00:00 29.00 MB/s
conda-4.7.10-p 100% |###############################| Time: 0:00:00 27.90 MB/s
ERROR conda.core.link:_execute_actions(337): An error occurred while installing package 'defaults::tqdm-4.32.1-py_0'.
CondaError: Cannot link a source that does not exist. C:\ProgramData\Anaconda3\Scripts\conda.exe
Running `conda clean --packages` may resolve your problem.
Attempting to roll back.
CondaError: Cannot link a source that does not exist. C:\ProgramData\Anaconda3\Scripts\conda.exe
Running `conda clean --packages` may resolve your problem.
``` | 2019/08/06 | [
"https://Stackoverflow.com/questions/57372207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1577580/"
] | Try
`conda install matplotlib=2.1.1` | create a new environment and try the below commands
```
conda install -c conda-forge matplotlib
```
or
```
conda install matplotlib
``` |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | `SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it. | SIGTSTP OR SIGSTOP signal is suspend, can't kill this program, use SIGCONT signal you can wake and continue it
```
Signal Description Signal number on Linux x86[1]
SIGABRT Process aborted 6
SIGALRM Signal raised by alarm 14
SIGBUS Bus error: "access to undefined portion of memory object" 7
SIGCHLD Child process terminated, stopped (or continued*) 17
SIGCONT Continue if stopped 18
SIGFPE Floating point exception: "erroneous arithmetic operation" 8
SIGHUP Hangup 1
SIGILL Illegal instruction 4
SIGINT Interrupt 2
SIGKILL Kill (terminate immediately) 9
SIGPIPE Write to pipe with no one reading 13
SIGQUIT Quit and dump core 3
SIGSEGV Segmentation violation 11
SIGSTOP Stop executing temporarily 19
SIGTERM Termination (request to terminate) 15
SIGTSTP Terminal stop signal 20
SIGTTIN Background process attempting to read from tty ("in") 21
SIGTTOU Background process attempting to write to tty ("out") 22
SIGUSR1 User-defined 1 10
SIGUSR2 User-defined 2 12
SIGPOLL Pollable event 29
SIGPROF Profiling timer expired 27
SIGSYS Bad syscall 31
SIGTRAP Trace/breakpoint trap 5
SIGURG Urgent data available on socket 23
SIGVTALRM Signal raised by timer counting virtual time: "virtual timer expired" 26
SIGXCPU CPU time limit exceeded 24
SIGXFSZ File size limit exceeded 25
``` |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | `SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it. | Ok,I found the solution.
Enter the following command on your linux terminal:
```
ps -ef |grep yourfile.py
```
You will see a number of processes that are still running in the background. To kill them enter the following command:
```
kill -9 pid
```
Don't type pid. Type the numbers identifying the process as shown in the terminal display
 |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | `SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it. | You should make sure your threads are running in Daemon mode. This could be what is preventing them from exiting cleanly when you hit `ctrl-c`. Set them up like this:
```
t = threading.Thread()
t.daemon = True // <- this is the important bit...
t.start()
``` |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | `SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it. | Use the following command to kill all processes and ensure no background processes running.
Ctrl+\ |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | SIGTSTP OR SIGSTOP signal is suspend, can't kill this program, use SIGCONT signal you can wake and continue it
```
Signal Description Signal number on Linux x86[1]
SIGABRT Process aborted 6
SIGALRM Signal raised by alarm 14
SIGBUS Bus error: "access to undefined portion of memory object" 7
SIGCHLD Child process terminated, stopped (or continued*) 17
SIGCONT Continue if stopped 18
SIGFPE Floating point exception: "erroneous arithmetic operation" 8
SIGHUP Hangup 1
SIGILL Illegal instruction 4
SIGINT Interrupt 2
SIGKILL Kill (terminate immediately) 9
SIGPIPE Write to pipe with no one reading 13
SIGQUIT Quit and dump core 3
SIGSEGV Segmentation violation 11
SIGSTOP Stop executing temporarily 19
SIGTERM Termination (request to terminate) 15
SIGTSTP Terminal stop signal 20
SIGTTIN Background process attempting to read from tty ("in") 21
SIGTTOU Background process attempting to write to tty ("out") 22
SIGUSR1 User-defined 1 10
SIGUSR2 User-defined 2 12
SIGPOLL Pollable event 29
SIGPROF Profiling timer expired 27
SIGSYS Bad syscall 31
SIGTRAP Trace/breakpoint trap 5
SIGURG Urgent data available on socket 23
SIGVTALRM Signal raised by timer counting virtual time: "virtual timer expired" 26
SIGXCPU CPU time limit exceeded 24
SIGXFSZ File size limit exceeded 25
``` | Ok,I found the solution.
Enter the following command on your linux terminal:
```
ps -ef |grep yourfile.py
```
You will see a number of processes that are still running in the background. To kill them enter the following command:
```
kill -9 pid
```
Don't type pid. Type the numbers identifying the process as shown in the terminal display
 |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | SIGTSTP OR SIGSTOP signal is suspend, can't kill this program, use SIGCONT signal you can wake and continue it
```
Signal Description Signal number on Linux x86[1]
SIGABRT Process aborted 6
SIGALRM Signal raised by alarm 14
SIGBUS Bus error: "access to undefined portion of memory object" 7
SIGCHLD Child process terminated, stopped (or continued*) 17
SIGCONT Continue if stopped 18
SIGFPE Floating point exception: "erroneous arithmetic operation" 8
SIGHUP Hangup 1
SIGILL Illegal instruction 4
SIGINT Interrupt 2
SIGKILL Kill (terminate immediately) 9
SIGPIPE Write to pipe with no one reading 13
SIGQUIT Quit and dump core 3
SIGSEGV Segmentation violation 11
SIGSTOP Stop executing temporarily 19
SIGTERM Termination (request to terminate) 15
SIGTSTP Terminal stop signal 20
SIGTTIN Background process attempting to read from tty ("in") 21
SIGTTOU Background process attempting to write to tty ("out") 22
SIGUSR1 User-defined 1 10
SIGUSR2 User-defined 2 12
SIGPOLL Pollable event 29
SIGPROF Profiling timer expired 27
SIGSYS Bad syscall 31
SIGTRAP Trace/breakpoint trap 5
SIGURG Urgent data available on socket 23
SIGVTALRM Signal raised by timer counting virtual time: "virtual timer expired" 26
SIGXCPU CPU time limit exceeded 24
SIGXFSZ File size limit exceeded 25
``` | Use the following command to kill all processes and ensure no background processes running.
Ctrl+\ |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | You should make sure your threads are running in Daemon mode. This could be what is preventing them from exiting cleanly when you hit `ctrl-c`. Set them up like this:
```
t = threading.Thread()
t.daemon = True // <- this is the important bit...
t.start()
``` | Ok,I found the solution.
Enter the following command on your linux terminal:
```
ps -ef |grep yourfile.py
```
You will see a number of processes that are still running in the background. To kill them enter the following command:
```
kill -9 pid
```
Don't type pid. Type the numbers identifying the process as shown in the terminal display
 |
37,477,755 | [](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to kill the program. However, when i run the program again,the program does not execute and linux prompts me to enter a new command. I tried killing pids and killing processes but its not resolve the problem. I have to restart the system in order to get the program working again. Kindly please advise for a solution so i can kill a program and run it again without having to restart my system. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37477755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444867/"
] | You should make sure your threads are running in Daemon mode. This could be what is preventing them from exiting cleanly when you hit `ctrl-c`. Set them up like this:
```
t = threading.Thread()
t.daemon = True // <- this is the important bit...
t.start()
``` | Use the following command to kill all processes and ensure no background processes running.
Ctrl+\ |
43,131,671 | Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?
my solution:
using dictionary:
```
from collections import defaultdict
L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
d=defaultdict(int)
for i in L:
d[i]+=1
for j in K:
d[j]+=1
print d
result=[]
for key,val in d.iteritems():
if val == 2:
result.append(key)
print result
```
My desired output would be:
```
['e', 'd', 'i', 'r']
```
Can I get a better pythonic solution?
Thanks. | 2017/03/31 | [
"https://Stackoverflow.com/questions/43131671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516609/"
] | You can use python `Counter` for getting count of each word in the list. <https://docs.python.org/2/library/collections.html#counter-objects>
```
>>> L=['a','b','c','d','a','d','e','e','g','h']
>>> from collections import Counter
>>> c = Counter(L)
>>> c
Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1})
```
After doing this iterate over counter object and add elements to third list which have value 2. | This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time
```
set([x for x in L.extend(K) if L.extend(K).count(x) == 2])
```
Notice that this returns a set and not a list! |
43,131,671 | Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?
my solution:
using dictionary:
```
from collections import defaultdict
L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
d=defaultdict(int)
for i in L:
d[i]+=1
for j in K:
d[j]+=1
print d
result=[]
for key,val in d.iteritems():
if val == 2:
result.append(key)
print result
```
My desired output would be:
```
['e', 'd', 'i', 'r']
```
Can I get a better pythonic solution?
Thanks. | 2017/03/31 | [
"https://Stackoverflow.com/questions/43131671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516609/"
] | You can use the collection's counter class to simplify the code:
```
from collections import Counter
...
d = Counter(L+K) #we are combining to process both at once
```
Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array.
```
L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
print [k for k, v in Counter(L+K).iteritems() if v == 2]
``` | You can use python `Counter` for getting count of each word in the list. <https://docs.python.org/2/library/collections.html#counter-objects>
```
>>> L=['a','b','c','d','a','d','e','e','g','h']
>>> from collections import Counter
>>> c = Counter(L)
>>> c
Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1})
```
After doing this iterate over counter object and add elements to third list which have value 2. |
43,131,671 | Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?
my solution:
using dictionary:
```
from collections import defaultdict
L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
d=defaultdict(int)
for i in L:
d[i]+=1
for j in K:
d[j]+=1
print d
result=[]
for key,val in d.iteritems():
if val == 2:
result.append(key)
print result
```
My desired output would be:
```
['e', 'd', 'i', 'r']
```
Can I get a better pythonic solution?
Thanks. | 2017/03/31 | [
"https://Stackoverflow.com/questions/43131671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4516609/"
] | You can use the collection's counter class to simplify the code:
```
from collections import Counter
...
d = Counter(L+K) #we are combining to process both at once
```
Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array.
```
L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
print [k for k, v in Counter(L+K).iteritems() if v == 2]
``` | This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time
```
set([x for x in L.extend(K) if L.extend(K).count(x) == 2])
```
Notice that this returns a set and not a list! |
40,639,665 | Not able to solve what is the error.
```
django.db.utils.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```
I keep on getting the Trace when i run any of the command below
1. python manage.py makemigrations
2. python manage.py runserver
```
Unhandled exception in thread started by <function wrapper at 0x0000000003DAC4A8>
Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs)
File "C:\Python27\lib\site packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check_migrations()
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 437, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__
self.loader = MigrationLoader(self.connection)
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__
self.build_graph()
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 203, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations
self.ensure_schema()
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor
self.ensure_connection()
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection
self.connect()
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection
self.connect()
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 171, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Python27\lib\site-packages\django\db\backends\postgresql\base.py", line 176, in get_new_connection
connection = Database.connect(**conn_params)
File "C:\Python27\lib\site-packages\psycopg2\__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```
Thanks in advance. | 2016/11/16 | [
"https://Stackoverflow.com/questions/40639665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5474316/"
] | This usually means that your PostgreSQL server is not running properly. You may want to restart it by
Linux
```
sudo /etc/init.d/postgresql restart
```
Windows
```
sc stop postgresql
sc start postgresql
```
Mac OS X
[How to start PostgreSQL server on Mac OS X?](https://stackoverflow.com/questions/7975556/how-to-start-postgresql-server-on-mac-os-x)
If restart fixes it, note that the root cause of the previous server failure still needs investigation. | I solved this problem uninstalling and installing postgresql again.
**On Mac**
Uninstall:
```
brew uninstall --force postgres
```
Install:
```
brew install postgres
```
PS: Change commands for Linux or Windows.
After, run makemigrations and migrate. |
40,639,665 | Not able to solve what is the error.
```
django.db.utils.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```
I keep on getting the Trace when i run any of the command below
1. python manage.py makemigrations
2. python manage.py runserver
```
Unhandled exception in thread started by <function wrapper at 0x0000000003DAC4A8>
Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs)
File "C:\Python27\lib\site packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check_migrations()
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 437, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__
self.loader = MigrationLoader(self.connection)
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 52, in __init__
self.build_graph()
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 203, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations
self.ensure_schema()
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor
self.ensure_connection()
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection
self.connect()
File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection
self.connect()
File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 171, in connect
self.connection = self.get_new_connection(conn_params)
File "C:\Python27\lib\site-packages\django\db\backends\postgresql\base.py", line 176, in get_new_connection
connection = Database.connect(**conn_params)
File "C:\Python27\lib\site-packages\psycopg2\__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```
Thanks in advance. | 2016/11/16 | [
"https://Stackoverflow.com/questions/40639665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5474316/"
] | This usually means that your PostgreSQL server is not running properly. You may want to restart it by
Linux
```
sudo /etc/init.d/postgresql restart
```
Windows
```
sc stop postgresql
sc start postgresql
```
Mac OS X
[How to start PostgreSQL server on Mac OS X?](https://stackoverflow.com/questions/7975556/how-to-start-postgresql-server-on-mac-os-x)
If restart fixes it, note that the root cause of the previous server failure still needs investigation. | Happens when a process forks and connection established in parent process don't work in child processes.
I was using `huggingface/tokenizers` and `BERT` to get sentence embeddings and then inserting those into a Postgres database. The database connection was getting established first and then the tokenizer was forking which resulted in the same `django.db.utils.OperationalError`.
I solved it [by disabling](https://stackoverflow.com/a/62703850) `TOKENIZER_PARALLELISM`. Though for your issue, upgrading to a higher version of Django might help as mentioned [here](https://stackoverflow.com/a/54741079/6799207). |
22,720,012 | I've been bashing my head on this problem for a while now.
I'm dealing with properties setting using the DBus-java bindings for DBus. When Set is called, the value to set is wrapped in a org.freedesktop.types.Variant object from which I have to extract it. Normally if the data is a primitive I can use generics in the Set parameters and the bindings does the type conversion before calling the Set method.
However I am trying to set using a org.freedesktop.types.DBusStructType which is a complex type and which needs to be manually unpacked. So far I've gotten to the point where I can extract the type from the variant but I can't cast the value wrapped in the Variant to a DBusStructType even though it is clearly identified as a DBusStructType
The following code throws a `ClassCastException: Cannot cast [Ljava.lang.Object; to org.freedesktop.dbus.types.DBusStructType` when called with a DBus.Struct from a python dbus test. I have checked the variant signature is packed right, but I can't find a way to cast the object returned by the Variant.getValue() to the type specified by Variant.getType() and access the structure fields.
```
public void Set(String interface_name, String property_name, Variant new_value) throws Exception {
Type t = new_value.getType();
Object s = new_value.getValue();
t.getClass().cast(s);
System.out.println("Object cast to "+s.getClass().getName());
}
```
Any pointers would be really appreciated, I have started digging more into reflection as I'm still new to it but there is probably something I am missing. | 2014/03/28 | [
"https://Stackoverflow.com/questions/22720012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444649/"
] | Found the root cause. Changing the SpringServlet's Url mappings to "Rest" resources specific path fixed it.
Earlier "/\*" was also interpreted by SpringServlet and was not able to render the index.html.
```
class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run([Application, "classpath:/META-INF/com/my/package/mgmt/bootstrap.xml"] as Object[], args)
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application);
}
@Bean
ServletRegistrationBean jerseyServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new SpringServlet(), "/rest/*");
Map<String, String> params = ["com.sun.jersey.config.property.packages": "com.my.package.mgmt.impl;com.wordnik.swagger.jersey.listing"]
registration.setInitParameters(params)
return registration;
}
@Bean
ServletRegistrationBean jerseyJaxrsConfig() {
ServletRegistrationBean registration = new ServletRegistrationBean(new DefaultJaxrsConfig(), "/api/*");
Map<String, String> params = ["swagger.api.basepath": "http://localhost:8080/api", "api.version": "0.1.0"]
registration.setInitParameters(params)
return registration;
}
``` | ```
@Configuration
public class WebConfig implements WebMvcConfigurer {
/** do not interpret .123 extension as a lotus spreadsheet */
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer)
{
configurer.favorPathExtension(false);
}
/**
./resources/public is not working without this
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/public/");
}
```
} |
30,958,835 | I would like to have a function as an optional argument
of another function in python but it is not clear for me how I can do that.
For example I define the following function:
```
import os, time, datetime
def f(t=datetime.datetime.now()):
return t.timetuple()
```
I have placed `t=datetime.datetime.now()`
in order for the argument to be optional so
to be able to call `f()` with no arguments.
Now whenever in time I execute `f()` I get the same datetime A (which is wrong according to what I expect), but whenever in time I execute `f(datetime.datetime.now())` I get different datetimes (which is correct as expected).
For example
```
>>> f()
time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1)
>>> f()
time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1)
>>> f(datetime.datetime.now())
time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=37, tm_sec=1, tm_wday=5, tm_yday=171, tm_isdst=-1)
>>> f()
time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1)
```
So why the fourth call returns me back to min 36 and sec 2
while the call was made before that?
Why the first two calls give the same exact time even if I let plenty of time between them? | 2015/06/20 | [
"https://Stackoverflow.com/questions/30958835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/805417/"
] | As mentioned by flask, the default value is evaluated when the function is parsed, so it will be set to one time.
The typical solution to this, is to not have the default a mutable value. You can do the followings:
```
def f(t=None):
if not t:
t = datetime.datetime.now()
return t.timetuple()
```
BTW, for the readers' benefit, you should try to use meaningful method and variable names. | The default parameter value is evaluated only once when the function is defined. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.