qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
21,310,125 | I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation?
I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that ca... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21310125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1112656/"
] | **AWS Beanstalk:**
It is Deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs yor web applications with Elastic Beanstalk.
No need to worry about EC2 or else installations.
**AWS OpsWorks**
AWS OpsWorks is nothing but an application management service that makes it easy f... | Just use terraform and ECS or EKS.
opsworks, elastic beanstalk and cloudformation old tech now. -) |
21,310,125 | I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation?
I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that ca... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21310125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1112656/"
] | **AWS OpsWorks** - This is a part of AWS management service. It helps to configure the application using scripting. It uses Chef as the devops framework for this application management and operation.
There are templates which can be used for configuration of server, database, storage. The templates can also be customi... | You should use OpsWorks in place of CloudFormation if you need to deploy an application that requires updates to its EC2 instances. If your application uses a lot of AWS resources and services, including EC2, use a combination of CloudFormation and OpsWorks
If your application will need other AWS resources, such as da... |
46,044,003 | I'm trying to write a function that guesses a type of a variable represented as a string.
So if I've got a variable of some type then in order to find out what type of a variable it is I can use python's `type()` function like this `type(var)`. But how do I concisely and pythonicaly convert the output of this function ... | 2017/09/04 | [
"https://Stackoverflow.com/questions/46044003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8243859/"
] | ```
>>> type(0).__name__
'int'
>>> type('').__name__
'str'
>>> type({}).__name__
'dict'
``` | What are you actually trying to do? If you just want to get the name of the class of the object you could use:
```
type(var).__name__
```
This will give you the name of the class of the object `var`. |
7,389,567 | I have a webpage generated from python that works as it should, using:
```
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
```
I want to add images to this webpage, but... | 2011/09/12 | [
"https://Stackoverflow.com/questions/7389567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/828573/"
] | You can use this code to directly embed the image in your HTML:
Python 3
```
import base64
data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)
```
Python 2.7
```
data_uri = open('11.png', 'rb').read().encode('b... | Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like `<img src='the_url_to_the_image'>`. Then the browser makes a second request to the server, and gets the image data.
The only option you have to serve images and HTML together is ... |
7,389,567 | I have a webpage generated from python that works as it should, using:
```
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
```
I want to add images to this webpage, but... | 2011/09/12 | [
"https://Stackoverflow.com/questions/7389567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/828573/"
] | Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like `<img src='the_url_to_the_image'>`. Then the browser makes a second request to the server, and gets the image data.
The only option you have to serve images and HTML together is ... | You can't just dump image data into HTML.
You need to either have the file served and link to it or embed the image encoded in base64. |
7,389,567 | I have a webpage generated from python that works as it should, using:
```
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
```
I want to add images to this webpage, but... | 2011/09/12 | [
"https://Stackoverflow.com/questions/7389567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/828573/"
] | You can use this code to directly embed the image in your HTML:
Python 3
```
import base64
data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)
```
Python 2.7
```
data_uri = open('11.png', 'rb').read().encode('b... | You can't just dump image data into HTML.
You need to either have the file served and link to it or embed the image encoded in base64. |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use splits to have both vim and a bash prompt in the same terminal window.
I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and ... | You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this:
```
:!python %
```
I should probably also add, as another option, that you can split t... |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can't execute a file if that file doesn't exist.
Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`.
Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. ... | You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this:
```
:!python %
```
I should probably also add, as another option, that you can split t... |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this:
```
:!python %
```
I should probably also add, as another option, that you can split t... | in vim type :w yourfilenamehere.py and press enter |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use splits to have both vim and a bash prompt in the same terminal window.
I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and ... | You can use "[quickrun](https://github.com/thinca/vim-quickrun)" plugin.
This plugin run a command and show its result quickly.
install this one, then type `<Leader>r`(default `\r`) to run program.
or
Use [tmux](http://tmux.sourceforge.net/).This tool is a terminal multiplexer.can split window in the same terminal. |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can't execute a file if that file doesn't exist.
Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`.
Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. ... | You can use splits to have both vim and a bash prompt in the same terminal window.
I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and ... |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use splits to have both vim and a bash prompt in the same terminal window.
I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and ... | in vim type :w yourfilenamehere.py and press enter |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can't execute a file if that file doesn't exist.
Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`.
Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. ... | You can use "[quickrun](https://github.com/thinca/vim-quickrun)" plugin.
This plugin run a command and show its result quickly.
install this one, then type `<Leader>r`(default `\r`) to run program.
or
Use [tmux](http://tmux.sourceforge.net/).This tool is a terminal multiplexer.can split window in the same terminal. |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use "[quickrun](https://github.com/thinca/vim-quickrun)" plugin.
This plugin run a command and show its result quickly.
install this one, then type `<Leader>r`(default `\r`) to run program.
or
Use [tmux](http://tmux.sourceforge.net/).This tool is a terminal multiplexer.can split window in the same terminal. | in vim type :w yourfilenamehere.py and press enter |
19,330,790 | I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window.
I'm trying to use :!python % but I get the following error message:
E499: Empty file name for '%' or '#', only works with ":p:h"
Any... | 2013/10/12 | [
"https://Stackoverflow.com/questions/19330790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can't execute a file if that file doesn't exist.
Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`.
Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. ... | in vim type :w yourfilenamehere.py and press enter |
18,118,226 | I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file?
Thanks in advance | 2013/08/08 | [
"https://Stackoverflow.com/questions/18118226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286286/"
] | I think you're looking for the [`filecmp` module](http://docs.python.org/2/library/filecmp.html). You can use it like this:
```
import filecmp
cmp = filecmp.cmp('f1.xml', 'f2.xml')
# Files are equal
if cmp:
continue
else:
out_file.write('f1.xml')
```
Replace `f1.xml` and `f2.xml` with your xml files. | Building on @Xaranke's answer:
```
import filecmp
out_file = open("diff_xml_names.txt")
# Not sure what format your filenames will come in, but here's one possibility.
filePairs = [('f1a.xml', 'f1b.xml'), ('f2a.xml', 'f2b.xml'), ('f3a.xml', 'f3b.xml')]
for f1, f2 in filePairs:
if not filecmp.cmp(f1, f2):
... |
18,118,226 | I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file?
Thanks in advance | 2013/08/08 | [
"https://Stackoverflow.com/questions/18118226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286286/"
] | I think you're looking for the [`filecmp` module](http://docs.python.org/2/library/filecmp.html). You can use it like this:
```
import filecmp
cmp = filecmp.cmp('f1.xml', 'f2.xml')
# Files are equal
if cmp:
continue
else:
out_file.write('f1.xml')
```
Replace `f1.xml` and `f2.xml` with your xml files. | What about the following snippet :
```
def separator(self):
return "!@#$%^&*" # Very ugly separator
def _traverseXML(self, xmlElem, tags, xpaths):
tags.append(xmlElem.tag)
for e in xmlElem:
self._traverseXML(e, tags, xpaths)
text = ''
if (xmlElem.text):
text = xmlElem.text.strip()... |
18,118,226 | I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file?
Thanks in advance | 2013/08/08 | [
"https://Stackoverflow.com/questions/18118226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286286/"
] | Do you speak of comparing them byte-wise or for semantic equality?
(Is `<tag attr1="1" attr2="2" />` equal to `<tag attr2="2" attr1="1" />`?)
If you want to check for semantic equality have a look at [Xml comparison in Python](https://stackoverflow.com/questions/3007330/xml-comparison-in-python)
When generating xml es... | Building on @Xaranke's answer:
```
import filecmp
out_file = open("diff_xml_names.txt")
# Not sure what format your filenames will come in, but here's one possibility.
filePairs = [('f1a.xml', 'f1b.xml'), ('f2a.xml', 'f2b.xml'), ('f3a.xml', 'f3b.xml')]
for f1, f2 in filePairs:
if not filecmp.cmp(f1, f2):
... |
18,118,226 | I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file?
Thanks in advance | 2013/08/08 | [
"https://Stackoverflow.com/questions/18118226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286286/"
] | Do you speak of comparing them byte-wise or for semantic equality?
(Is `<tag attr1="1" attr2="2" />` equal to `<tag attr2="2" attr1="1" />`?)
If you want to check for semantic equality have a look at [Xml comparison in Python](https://stackoverflow.com/questions/3007330/xml-comparison-in-python)
When generating xml es... | What about the following snippet :
```
def separator(self):
return "!@#$%^&*" # Very ugly separator
def _traverseXML(self, xmlElem, tags, xpaths):
tags.append(xmlElem.tag)
for e in xmlElem:
self._traverseXML(e, tags, xpaths)
text = ''
if (xmlElem.text):
text = xmlElem.text.strip()... |
44,513,308 | Can I use macros with the PythonOperator? I tried following, but I was unable to get the macros rendered:
```
dag = DAG(
'temp',
default_args=default_args,
description='temp dag',
schedule_interval=timedelta(days=1))
def temp_def(a, b, **kwargs):
print '{{ds}}'
print '{{execution_date}}'
p... | 2017/06/13 | [
"https://Stackoverflow.com/questions/44513308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4116268/"
] | Macros only get processed for templated fields. To get Jinja to process this field, extend the `PythonOperator` with your own.
```py
class MyPythonOperator(PythonOperator):
template_fields = ('templates_dict','op_args')
```
I added `'templates_dict'` to the `template_fields` because the `PythonOperator` itself h... | In my opinion a more native Airflow way of approaching this would be to use the included PythonOperator and use the `provide_context=True` parameter as such.
```py
t1 = MyPythonOperator(
task_id='temp_task',
python_callable=temp_def,
provide_context=True,
dag=dag)
```
Now you have access to all of th... |
3,853,136 | The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light?
This is in windows 7 BTW.
My code:
```
#!/usr/bin/e... | 2010/10/04 | [
"https://Stackoverflow.com/questions/3853136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433417/"
] | unless you've been messing around with your standard library, it seems that you have a file named `threading.py` somewhere on your python path that is replacing the standard one. Try:
```
>>>import threading
>>>print threading.__file__
```
and make sure that it's the one in your python lib directory (it should be`C:... | You most likely need to adjust your [PYTHONPATH](http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH); this is a list of directories Python uses to find modules. See also [How to add to the pythonpath in windows 7?](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7). |
3,853,136 | The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light?
This is in windows 7 BTW.
My code:
```
#!/usr/bin/e... | 2010/10/04 | [
"https://Stackoverflow.com/questions/3853136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433417/"
] | unless you've been messing around with your standard library, it seems that you have a file named `threading.py` somewhere on your python path that is replacing the standard one. Try:
```
>>>import threading
>>>print threading.__file__
```
and make sure that it's the one in your python lib directory (it should be`C:... | From Windows command shell get into python shell by typing python binary (you should get something like '>>>'). Here type **import matplotlib** (your package name which you are trying to import), if you get an error like **ImportError: No module named matplotlib** that means as Matthew F suggested you need to update yo... |
64,405,461 | Trying to add Densenet121 functional block to the model.
I need Keras model to be written in this format, not using
```
model=Sequential()
model.add()
```
method
What's wrong the function, build\_img\_encod
```
---------------------------------------------------------------------------
AttributeError ... | 2020/10/17 | [
"https://Stackoverflow.com/questions/64405461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14309081/"
] | The reason why you get that error is that you need to provide the `input_shape` of the `base_model`, instead of the `base_model` per say.
Replace this line: `model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)`
with: `model = keras.models.Model(inputs=base_model.input, outputs = img_dense_encod... | ```
def build_img_encod( ):
dense = DenseNet121(input_shape=(150,150,3),
include_top=False,
weights='imagenet')
for layer in dense.layers:
layer.trainable = False
img_input = Input(shape=(150,150,3))
base_model = dense(img_inp... |
39,612,416 | I have a linux machine to which i installed Anaconda.
I am following:
<https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html>
pip instaltion part.
To be more specific:
```
which python
```
gives
```
/home/user/anaconda2/bin/python
```
After which i entered:
```
export TF_BINARY_URL=https://... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39612416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6857504/"
] | The problem is here:
```
xs foldLeft((0,0,0))(logic _)
```
Never go for the dotless notation unless it's for an operator. This way it works.
```
xs.foldLeft((0,0,0))(logic _)
```
Without a context I believe this is idiomatic enough. | I don't get the goal of your code but the problem you described can be solved this way:
```
val to = xs.foldLeft((0,0,0))(logic)
``` |
39,612,416 | I have a linux machine to which i installed Anaconda.
I am following:
<https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html>
pip instaltion part.
To be more specific:
```
which python
```
gives
```
/home/user/anaconda2/bin/python
```
After which i entered:
```
export TF_BINARY_URL=https://... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39612416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6857504/"
] | The problem is here:
```
xs foldLeft((0,0,0))(logic _)
```
Never go for the dotless notation unless it's for an operator. This way it works.
```
xs.foldLeft((0,0,0))(logic _)
```
Without a context I believe this is idiomatic enough. | Try this
```
xs.foldLeft((0,0,0), logic)
``` |
39,612,416 | I have a linux machine to which i installed Anaconda.
I am following:
<https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html>
pip instaltion part.
To be more specific:
```
which python
```
gives
```
/home/user/anaconda2/bin/python
```
After which i entered:
```
export TF_BINARY_URL=https://... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39612416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6857504/"
] | The problem is here:
```
xs foldLeft((0,0,0))(logic _)
```
Never go for the dotless notation unless it's for an operator. This way it works.
```
xs.foldLeft((0,0,0))(logic _)
```
Without a context I believe this is idiomatic enough. | `foldLeft` is a curried function so it requires a `.` - go for `xs.foldLeft` and it will work. |
61,858,954 | I'm trying to get two attributes at the time from my json data and add them as an item on my python list. However, when trying to add those two: `['emailTypeDesc']['createdDate']` it throws an error. Could someone help with this? thanks in advance!
json:
```
{
'readOnly': False,
'senderDetails': {'firstName': 'John'... | 2020/05/17 | [
"https://Stackoverflow.com/questions/61858954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488179/"
] | I think you're misunderstanding the syntax. `mails['emailTypeDesc']['createdDate']` is looking for the key `'createdDate'` *inside* the object `mails['emailTypeDesc']`, but in fact they are two items at the same level.
Since `mails['emailTypeDesc']` is a string, not a dictionary, you get the error you have quoted. It ... | Strings in JSON must be in double quotes, not single.
Edit: As well as names. |
74,558,107 | Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner:
```
tail file.txt -n `python 123*456`
```
instead of having to calculate 123\*456 in a separate step. | 2022/11/24 | [
"https://Stackoverflow.com/questions/74558107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4746861/"
] | I don't understand your question: you say "I would like to do something using Python", but when you show what you want to do, Python seems not to be needed for achieving that.
Let me show you: what you want to achieve, can be done as follows:
```
tail -f file.txt -n $((123*456))
```
The `$((...))` notation is capab... | You can try the `-c` option. For e.g, `tail test_log.txt -n `python -c "print(1 + 2)"`` |
58,165,158 | I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript:
```
C:\WINDOWS\system32> pip install pinyin_utils ... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58165158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] | You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items.
```js
let array = [[1,2], [10, 15], [30, 40], [-1, -50]],
max = array.map(a => Math.max(...a));
console.log(max);
``` | Empty numeric values wouldn't help you either using your logic, because you are setting wrong initial values for comparison. See this, same as yours, with minor fix:
```
let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];
let newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
for (let x = 0; x < arr.length; x++... |
58,165,158 | I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript:
```
C:\WINDOWS\system32> pip install pinyin_utils ... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58165158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] | Your issue is that `-1` is not smaller than `0`, and so your array will not be updated, instead, start your `newArr` with `-Infinity`s instead of `0` such that any number will be bigger than it like so:
```js
let arr = [
[1, 2],
[10, 15],
[30, 40],
[-1, -50]
];
let newArr = [];
for (let x = 0; x < ar... | You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items.
```js
let array = [[1,2], [10, 15], [30, 40], [-1, -50]],
max = array.map(a => Math.max(...a));
console.log(max);
``` |
58,165,158 | I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript:
```
C:\WINDOWS\system32> pip install pinyin_utils ... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58165158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] | You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items.
```js
let array = [[1,2], [10, 15], [30, 40], [-1, -50]],
max = array.map(a => Math.max(...a));
console.log(max);
``` | You can use the initial value as the 1st element or sub-array.
```js
let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];
newArr = [] // Instead of 0 I need an empty numeric
for (let x = 0; x < arr.length; x++) {
newArr[x] = arr[x][0]
for (let y = 0; y < arr[x].length; y++) {
if (newArr[x] < arr[x... |
58,165,158 | I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript:
```
C:\WINDOWS\system32> pip install pinyin_utils ... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58165158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] | Your issue is that `-1` is not smaller than `0`, and so your array will not be updated, instead, start your `newArr` with `-Infinity`s instead of `0` such that any number will be bigger than it like so:
```js
let arr = [
[1, 2],
[10, 15],
[30, 40],
[-1, -50]
];
let newArr = [];
for (let x = 0; x < ar... | Empty numeric values wouldn't help you either using your logic, because you are setting wrong initial values for comparison. See this, same as yours, with minor fix:
```
let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];
let newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
for (let x = 0; x < arr.length; x++... |
58,165,158 | I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript:
```
C:\WINDOWS\system32> pip install pinyin_utils ... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58165158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] | Your issue is that `-1` is not smaller than `0`, and so your array will not be updated, instead, start your `newArr` with `-Infinity`s instead of `0` such that any number will be bigger than it like so:
```js
let arr = [
[1, 2],
[10, 15],
[30, 40],
[-1, -50]
];
let newArr = [];
for (let x = 0; x < ar... | You can use the initial value as the 1st element or sub-array.
```js
let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];
newArr = [] // Instead of 0 I need an empty numeric
for (let x = 0; x < arr.length; x++) {
newArr[x] = arr[x][0]
for (let y = 0; y < arr[x].length; y++) {
if (newArr[x] < arr[x... |
59,307,815 | I am currently developing a python project where I am concerned with performance because my CPU is always using like 90-98% of its computing capacity.
So I was thinking about what could I change in my code to make it faster, and noticed that I have a string variable which always receives one of two values:
```
state... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59307815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619301/"
] | To parse HTML and XML documents (page source) and get elements with locators, you can use [beautifulsoup](/questions/tagged/beautifulsoup "show questions tagged 'beautifulsoup'"), [how to use it](https://pypi.org/project/beautifulsoup4/).
Regular expression do not parsing HTML documents. You get **NULL** because `Ch... | From the code you have posted, the strings you have hardcoded are all the same other than the index of the DD element. Since the Status index is always 7 less than the index of Checkpath, you can just loop through 15-12, do your search, and then Status is just 15-7. The code is below.
```
src = driver.page_source
loop... |
59,307,815 | I am currently developing a python project where I am concerned with performance because my CPU is always using like 90-98% of its computing capacity.
So I was thinking about what could I change in my code to make it faster, and noticed that I have a string variable which always receives one of two values:
```
state... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59307815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619301/"
] | My solution to this bug is listed below
I was able to perform a nest while loop within a for loop. My list XpathLoop shows the numerical values of the dd items. This loops through until it finds my desired dt 'Status Date'. After it finds the desired text it enteres a while loop until the status date format appears. Th... | From the code you have posted, the strings you have hardcoded are all the same other than the index of the DD element. Since the Status index is always 7 less than the index of Checkpath, you can just loop through 15-12, do your search, and then Status is just 15-7. The code is below.
```
src = driver.page_source
loop... |
8,275,650 | I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying.
I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If th... | 2011/11/26 | [
"https://Stackoverflow.com/questions/8275650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066430/"
] | You've got two questions mashed into one. The first is: how do you remove non-alphanumeric chars from a string? You can do it a few ways, but regular expression substitution is a nice way.
```
import re
def removeWhitespace( s ):
return re.sub( '\s', '', s )
```
The second part of the question is about how to k... | I think you could use `enumerate` in that situation:
```
# remove unwanted stuff
l = [ c for c in Text if c.isalpha() ]
for n,k in enumerate(l):
print n, (Keyword[n % len(Keyword)], Text[l])
```
that gives you:
```
0 ('l', 'h')
1 ('e', 'i')
2 ('m', 't')
3 ('o', 'h')
4 ('n', 'e')
5 ('l', 'r')
6 ('e', 'e')
```
... |
8,275,650 | I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying.
I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If th... | 2011/11/26 | [
"https://Stackoverflow.com/questions/8275650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066430/"
] | Here's a solution:
```
import itertools
def task(kw,text):
i = itertools.cycle(kw)
return tuple(next(i)+t if t.isalpha() else t for t in text)
print(task('lemon','hi there!'))
```
### Output
```
('lh', 'ei', ' ', 'mt', 'oh', 'ne', 'lr', 'ee', '!')
```
[itertools.cycle](http://docs.python.org/library/ite... | You've got two questions mashed into one. The first is: how do you remove non-alphanumeric chars from a string? You can do it a few ways, but regular expression substitution is a nice way.
```
import re
def removeWhitespace( s ):
return re.sub( '\s', '', s )
```
The second part of the question is about how to k... |
8,275,650 | I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying.
I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If th... | 2011/11/26 | [
"https://Stackoverflow.com/questions/8275650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066430/"
] | Here's a solution:
```
import itertools
def task(kw,text):
i = itertools.cycle(kw)
return tuple(next(i)+t if t.isalpha() else t for t in text)
print(task('lemon','hi there!'))
```
### Output
```
('lh', 'ei', ' ', 'mt', 'oh', 'ne', 'lr', 'ee', '!')
```
[itertools.cycle](http://docs.python.org/library/ite... | I think you could use `enumerate` in that situation:
```
# remove unwanted stuff
l = [ c for c in Text if c.isalpha() ]
for n,k in enumerate(l):
print n, (Keyword[n % len(Keyword)], Text[l])
```
that gives you:
```
0 ('l', 'h')
1 ('e', 'i')
2 ('m', 't')
3 ('o', 'h')
4 ('n', 'e')
5 ('l', 'r')
6 ('e', 'e')
```
... |
8,912,338 | I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via
```
(gdb) python mystruct = gdb.parse_and_eval("mystruct")
```
Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply u... | 2012/01/18 | [
"https://Stackoverflow.com/questions/8912338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154311/"
] | From GDB [documentation](http://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior):
You can get the type of `mystruct` like so:
```
tp = mystruct.type
```
and iterate over the [fields](http://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python) via `tp.fields()`
No... | Evil workaround:
```
python print eval("dict(" + str(mystruct)[1:-2] + ")")
```
I don't know if this is generalisable. As a demo, I wrote a minimal example `test.cpp`
```
#include <iostream>
struct mystruct
{
int i;
double x;
} mystruct_1;
int main ()
{
mystruct_1.i = 2;
mystruct_1.x = 1.242;
std::cout ... |
8,912,338 | I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via
```
(gdb) python mystruct = gdb.parse_and_eval("mystruct")
```
Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply u... | 2012/01/18 | [
"https://Stackoverflow.com/questions/8912338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154311/"
] | Evil workaround:
```
python print eval("dict(" + str(mystruct)[1:-2] + ")")
```
I don't know if this is generalisable. As a demo, I wrote a minimal example `test.cpp`
```
#include <iostream>
struct mystruct
{
int i;
double x;
} mystruct_1;
int main ()
{
mystruct_1.i = 2;
mystruct_1.x = 1.242;
std::cout ... | These days:
```
(gdb) python import sys; print(sys.version)
3.10.8 (main, Oct 15 2022, 19:00:40) [GCC 12.2.0 64 bit (AMD64)]
```
... it got a lot easier, properties are keys in dict - here is an example:
`test_struct.c`:
```c
#include <stdint.h>
#include <stdio.h>
struct mystruct_s {
uint8_t member;
uint8_t ... |
8,912,338 | I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via
```
(gdb) python mystruct = gdb.parse_and_eval("mystruct")
```
Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply u... | 2012/01/18 | [
"https://Stackoverflow.com/questions/8912338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154311/"
] | From GDB [documentation](http://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior):
You can get the type of `mystruct` like so:
```
tp = mystruct.type
```
and iterate over the [fields](http://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python) via `tp.fields()`
No... | These days:
```
(gdb) python import sys; print(sys.version)
3.10.8 (main, Oct 15 2022, 19:00:40) [GCC 12.2.0 64 bit (AMD64)]
```
... it got a lot easier, properties are keys in dict - here is an example:
`test_struct.c`:
```c
#include <stdint.h>
#include <stdio.h>
struct mystruct_s {
uint8_t member;
uint8_t ... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787.
This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on... | Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!).
Very simple translation (I have never used this library but it's rather straightforward):
```none
:- use_module(library(clpb)).
% sat(Expr) sets up a... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787.
This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on... | Here is an implementation in Picat with my experimental bitwise module (<http://hakank.org/picat/bitwise.pi> ) using constraint programming. It took 0.007s on my machine. The model is also here: <http://hakank.org/picat/bit_patterns.pi>
```
import bitwise.
import cp.
main => go.
go ?=>
Size = 16,
Type = unsign... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787.
This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on... | However, for doing these kind of bit calculation, z3 (<https://github.com/Z3Prover/z3> ) is probably the way to go, both in terms of modelling and features: it handle arbitrary long sizes, etc.
Here's a z3 model using the Python interface (also here: <http://hakank.org/z3/bit_patterns.py> ):
```
from z3 import *
sol... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787.
This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on... | A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/):
```py
"""Solve a problem of bitwise arithmetic using binary decision diagrams."""
import pprint
from omega.symbolic import temporal as trl
def solve(values):
"""Encode and solve the problem."""
aut = trl... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!).
Very simple translation (I have never used this library but it's rather straightforward):
```none
:- use_module(library(clpb)).
% sat(Expr) sets up a... | Here is an implementation in Picat with my experimental bitwise module (<http://hakank.org/picat/bitwise.pi> ) using constraint programming. It took 0.007s on my machine. The model is also here: <http://hakank.org/picat/bit_patterns.pi>
```
import bitwise.
import cp.
main => go.
go ?=>
Size = 16,
Type = unsign... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!).
Very simple translation (I have never used this library but it's rather straightforward):
```none
:- use_module(library(clpb)).
% sat(Expr) sets up a... | However, for doing these kind of bit calculation, z3 (<https://github.com/Z3Prover/z3> ) is probably the way to go, both in terms of modelling and features: it handle arbitrary long sizes, etc.
Here's a z3 model using the Python interface (also here: <http://hakank.org/z3/bit_patterns.py> ):
```
from z3 import *
sol... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!).
Very simple translation (I have never used this library but it's rather straightforward):
```none
:- use_module(library(clpb)).
% sat(Expr) sets up a... | A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/):
```py
"""Solve a problem of bitwise arithmetic using binary decision diagrams."""
import pprint
from omega.symbolic import temporal as trl
def solve(values):
"""Encode and solve the problem."""
aut = trl... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | Here is an implementation in Picat with my experimental bitwise module (<http://hakank.org/picat/bitwise.pi> ) using constraint programming. It took 0.007s on my machine. The model is also here: <http://hakank.org/picat/bit_patterns.pi>
```
import bitwise.
import cp.
main => go.
go ?=>
Size = 16,
Type = unsign... | A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/):
```py
"""Solve a problem of bitwise arithmetic using binary decision diagrams."""
import pprint
from omega.symbolic import temporal as trl
def solve(values):
"""Encode and solve the problem."""
aut = trl... |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | However, for doing these kind of bit calculation, z3 (<https://github.com/Z3Prover/z3> ) is probably the way to go, both in terms of modelling and features: it handle arbitrary long sizes, etc.
Here's a z3 model using the Python interface (also here: <http://hakank.org/z3/bit_patterns.py> ):
```
from z3 import *
sol... | A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/):
```py
"""Solve a problem of bitwise arithmetic using binary decision diagrams."""
import pprint
from omega.symbolic import temporal as trl
def solve(values):
"""Encode and solve the problem."""
aut = trl... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`:
```
import datetime
def is_expected_datetime_format(timestamp):
format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
try:
colon = timestamp[-3]
if not colon == ':':
raise ValueError()
colon... | Given the constraints you've put on the problem, you could easily solve it with a regular expression.
```
>>> import re
>>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00')
<_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'>
```
If you ... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | <https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html>
give many variants for validating date and times in ISO8601 format (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). The regex for the XML Schema dateTime type is given as:
```
>>> regex = r'^(-?(?:[1-9][0-... | Given the constraints you've put on the problem, you could easily solve it with a regular expression.
```
>>> import re
>>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00')
<_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'>
```
If you ... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | Recent versions of Python (from 3.7 onwards) have a `fromisoformat()` function in the `datetime` standard library. See: <https://docs.python.org/3.7/library/datetime.html>
So this will do the trick:
```
from datetime import datetime
def datetime_valid(dt_str):
try:
datetime.fromisoformat(dt_str)
exce... | Given the constraints you've put on the problem, you could easily solve it with a regular expression.
```
>>> import re
>>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00')
<_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'>
```
If you ... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | <https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html>
give many variants for validating date and times in ISO8601 format (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). The regex for the XML Schema dateTime type is given as:
```
>>> regex = r'^(-?(?:[1-9][0-... | Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`:
```
import datetime
def is_expected_datetime_format(timestamp):
format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
try:
colon = timestamp[-3]
if not colon == ':':
raise ValueError()
colon... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`:
```
import datetime
def is_expected_datetime_format(timestamp):
format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
try:
colon = timestamp[-3]
if not colon == ':':
raise ValueError()
colon... | ```
In [1] import dateutil.parser as dp
In [2]: import re
...: def validate_iso8601_us(str_val):
...: try:
...: dp.parse(str_val)
...: if re.search('\.\d\d\d\d\d\d',str_val):
...: return True
...: except:
...: pass
...: return Fal... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | Recent versions of Python (from 3.7 onwards) have a `fromisoformat()` function in the `datetime` standard library. See: <https://docs.python.org/3.7/library/datetime.html>
So this will do the trick:
```
from datetime import datetime
def datetime_valid(dt_str):
try:
datetime.fromisoformat(dt_str)
exce... | Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`:
```
import datetime
def is_expected_datetime_format(timestamp):
format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
try:
colon = timestamp[-3]
if not colon == ':':
raise ValueError()
colon... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | <https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html>
give many variants for validating date and times in ISO8601 format (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). The regex for the XML Schema dateTime type is given as:
```
>>> regex = r'^(-?(?:[1-9][0-... | ```
In [1] import dateutil.parser as dp
In [2]: import re
...: def validate_iso8601_us(str_val):
...: try:
...: dp.parse(str_val)
...: if re.search('\.\d\d\d\d\d\d',str_val):
...: return True
...: except:
...: pass
...: return Fal... |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | Recent versions of Python (from 3.7 onwards) have a `fromisoformat()` function in the `datetime` standard library. See: <https://docs.python.org/3.7/library/datetime.html>
So this will do the trick:
```
from datetime import datetime
def datetime_valid(dt_str):
try:
datetime.fromisoformat(dt_str)
exce... | ```
In [1] import dateutil.parser as dp
In [2]: import re
...: def validate_iso8601_us(str_val):
...: try:
...: dp.parse(str_val)
...: if re.search('\.\d\d\d\d\d\d',str_val):
...: return True
...: except:
...: pass
...: return Fal... |
19,593,456 | Can the "standard" subprocess pipeline technique (e.g. <http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline>) be "upgraded" to two pipelines?
```
# How about
p1 = Popen(["cmd1"], stdout=PIPE, stderr=PIPE)
p2 = Popen(["cmd2"], stdin=p1.stdout)
p3 = Popen(["cmd3"], stdin=p1.stderr)
p1.stdout.close(... | 2013/10/25 | [
"https://Stackoverflow.com/questions/19593456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690620/"
] | You could use bash's [process substitution](http://en.wikipedia.org/wiki/Process_substitution):
```
from subprocess import check_call
check_call("cmd1 > >(cmd2) 2> >(cmd3)", shell=True, executable="/bin/bash")
```
It redirects `cmd1`'s stdout to `cmd2` and `cmd1`'s stderr to `cmd3`.
If you don't want to use `bash`... | The solution here is to create a couple of background threads which read the output from one process and then write that into the inputs of several processes:
```
targets = [...] # list of processes as returned by Popen()
while True:
line = p1.readline()
if line is None: break
for p in targets:
p.s... |
56,293,981 | I'm writing a python script which has to internally create output path from the input path. However, I am facing issues to create the path which I can use irrespective of OS.
I have tried to use os.path.join and it has its own limitations.
Apart from that, I think simple string concatenation is not the way to go.
Path... | 2019/05/24 | [
"https://Stackoverflow.com/questions/56293981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5729921/"
] | From the documentation `os.path.join` can join "**one or more** path components...". So you could split `"\internal\morelevel\outputpath"` up into each of its components and pass all of them to your `os.path.join` function instead. That way you don't need to "hard-code" the separator between the path components. For ex... | Assuming your original path is "C:\projects\django\hereisinput", your other part of the path as "internal\morelevel\outputpath" (notice this is a relative path, not absolute), you could always move your primary back one folder (or more) and then append the second part. Do note that your first path needs to contain only... |
41,247,105 | I am trying to run this script in parallel, for i<=4 in each set. The `runspr.py` is itself parallel, and thats fine. What I am trying to do is running only 4 i loop in any instance.
In my present code, it will run everything.
```
#!bin/bash
for i in *
do
if [[ -d $i ]]; then
echo "$i id dir"
cd $i
... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41247105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005559/"
] | You don't need to use `for` loop. You can use [`gnu parallel`](https://www.gnu.org/software/parallel/parallel_tutorial.html) like this with `find`:
```
find . -mindepth 1 -maxdepth 1 -type d ! -print0 |
parallel -0 --jobs 4 'cd {}; python3 ~/bin/runspr.py SCF'
``` | Another possible solution is:
```
find . -mindepth 1 -maxdepth 1 -type d ! -print0 |
xargs -I {} -P 4 sh -c 'cd {}; python3 ~/bin/runspr.py SCF'
``` |
58,478,181 | I'm looking at breaking the enigma cipher with python, and need to generate plugboard combinations - what I need is a function which takes a `length` parameter and returns a generator object of all possible combinations as a list.
Example code:
```py
for comb in func(2):
print(comb)
```
```py
# Example output
['... | 2019/10/20 | [
"https://Stackoverflow.com/questions/58478181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I think what you're looking for is [itertools.combinations](https://docs.python.org/3/library/itertools.html#itertools.combinations)
```
>>> from itertools import combinations
>>> list(combinations('abcd', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(comb) for comb in combi... | Is this something close to what you're after? Let me know and I can revise.
The `plugboard()` function returns (`yield`) a `generator` object which can be accessed either by an iterable loop, or by calling the `next()` function.
```
from itertools import product
def plugboard(chars, length):
for comb in product(... |
63,810,966 | I try to remove outliers in a python list. But it removes only the first one (190000) and not the second (20000). What is the problem ?
```
import statistics
dataset = [25000, 30000, 52000, 28000, 150000, 190000, 200000]
def detect_outlier(data_1):
threshold = 1
mean_1 = statistics.mean(data_1)
std_1 = st... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63810966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669017/"
] | It is because you are trying to make operations on the same data address.
dataset's address is equals to the data\_1 address and when you are removing an element from the list, it pass the next element according to the foreach structure of Python. You must not make operations on a list during iteration.
Shortly, try t... | ```
import statistics
def detect_outlier(data_1):
threshold = 1
mean_1 = statistics.mean(data_1)
std_1 = statistics.stdev(data_1)
result_dataset = [y for y in data_1 if abs((y - mean_1)/std_1)<=threshold ]
return result_dataset
if __name__=="__main__":
dataset = [25000, 30000, 52000, 28000, 1... |
61,660,067 | This is the code i used:
```
df = None
from pyspark.sql.functions import lit
for category in file_list_filtered:
data_files = os.listdir('HMP_Dataset/'+category)
for data_file in data_files:
print(data_file)
temp_df = spark.read.option('header', 'false').option('delimiter', ' ').csv('HMP_Dat... | 2020/05/07 | [
"https://Stackoverflow.com/questions/61660067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13491209/"
] | You can try *regular expressions* in order to parse. First, let's extract a model: since commands are in format
```
Start (zero or more Modifiers)
```
E.g.
```
%today-5day+3hour%
```
where `today` is `Start` and `-5day` and `+3hour` are `Modifiers` we want two *models*
```
using System.Linq;
using System.Text.R... | This is a small example of parsing a string that has today and day in it (using the example of %today-5day%).
Note: this will only work if the value passed in for the added days is between 0-9, to handle large numbers you will have to loop over the result of the string.
You can follow this code block to parse other ... |
46,574,860 | I am trying to get percentage frequencies in pyspark. I did this in python as follows
```
Companies = df['Company'].value_counts(normalize = True)
```
Getting the frequencies is fairly straightforward:
```
# Dates in descending order of complaint frequency
df.createOrReplaceTempView('Comp')
CompDF = spark.sql("SE... | 2017/10/04 | [
"https://Stackoverflow.com/questions/46574860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8722941/"
] | As Suresh implies in the comments, assuming that `total_count` is the number of rows in dataframe `Companies`, you can use `withColumn` to add a new column named `percentages` in `CompDF`:
```
total_count = Companies.count()
df = CompDF.withColumn('percentage', CompDF.cnt/float(total_counts))
``` | May be modifying the SQL query will get you the result you want.
```
"SELECT Company,cnt/(SELECT SUM(cnt) from (SELECT Company, count(*) as cnt
FROM Comp GROUP BY Company ORDER BY cnt DESC) temp_tab) sum_freq from
(SELECT Company, count(*) as cnt FROM Comp GROUP BY Company ORDER BY cnt
DESC)"
``` |
67,205,402 | I have a file and its name is (Pro\_data.sh) which contains these commands:
```
python preprocess.py dex
python preprocess.py lex
python process.py
```
I do not know how can I run the file in the python terminal (pycharm as an example).
I can run each command alone but I want to know the right way to run the .sh ... | 2021/04/22 | [
"https://Stackoverflow.com/questions/67205402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585944/"
] | Is this what you're looking for?
main.py
```
import os
os.system('sh x.sh')
```
x.sh
```
python test2.py
```
test2.py
```
print('up')
```
output from main.py
```
up
``` | .sh is a mac/Linux shell. for windows: create one with the name Pro\_data.bat and put those three commands in it, and run Prod\_data.bat
**Prod\_data.bat**
```
python preprocess.py dex
python preprocess.py lex
python process.py
``` |
4,743,016 | I search a python builder IDE for wxpython similar to boa constructor.
any suggestions ? | 2011/01/20 | [
"https://Stackoverflow.com/questions/4743016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348081/"
] | Well, there is [wxGlade](http://wxglade.sourceforge.net/), [DialogBlocks](http://www.dialogblocks.com/) and [wxDesigner](http://www.wxdesigner-software.de/), with both DialogBlocks and wxDesigner being commercial tools. There also used to be a open-source editor called wxFormBuilder, but the site hosting it seems down ... | Boa constructor is working here....works with windows 10
<https://bitbucket.org/cwt/boa-constructor/overview> |
68,640,517 | I am trying to run a simple python script within a docker run command scheduled with Airflow.
I have followed the instructions here [Airflow init](https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html).
My `.env` file:
```
AIRFLOW_UID=1000
AIRFLOW_GID=0
```
And the `docker-compose.yaml` is based ... | 2021/08/03 | [
"https://Stackoverflow.com/questions/68640517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390189/"
] | There was a bug in Docker Provider 2.0.0 which prevented Docker Operator to run with Docker-In-Docker solution.
You need to upgrade to the latest Docker Provider 2.1.0
<https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/index.html#id1>
You can do it by extending the image as described in <https://... | I had the same issue and all "recommended" ways of solving the issue here and setting up mount\_dir params as descripted [here](https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/_api/airflow/providers/docker/operators/docker/index.html) just lead to other errors. The one solution that helped me was... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do `s[::-1]`. | I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal.
```
def tail_rev(in_string,rev_string):
if in_string=='':
return rev_string
... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | ```
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
```
(Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).) | if you do not want to return response than you can use this solution. This question is part of LeetCode.
```
class Solution:
i = 0
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if self.i >= (len(s)//2):
retu... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do `s[::-1]`. | ```
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 ... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, ... | ```
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 ... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | ```
def reverse_string(s):
if s: return s[-1] + reverse_string(s[0:-1])
else: return s
```
or
```
def reverse_string(s):
return s[-1] + reverse_string(s[0:-1]) if s else s
``` | if you do not want to return response than you can use this solution. This question is part of LeetCode.
```
class Solution:
i = 0
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
if self.i >= (len(s)//2):
retu... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | ```
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
```
(Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).) | ```
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 ... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, ... | ```
def reverse_string(s):
if s: return s[-1] + reverse_string(s[0:-1])
else: return s
```
or
```
def reverse_string(s):
return s[-1] + reverse_string(s[0:-1]) if s else s
``` |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | ```
def rreverse(s):
if s == "":
return s
else:
return rreverse(s[1:]) + s[0]
```
(Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).) | To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, ... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself.
What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, ... | I just want to add some explanations based on [Fred Foo's answer](https://stackoverflow.com/a/5532914).
Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'.
```
def reverse(s):
if s == "":
return s
else:
return reverse(s[1:]) + s[0]
s = "abc"
print ... |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | ```
def reverse_string(s):
if s: return s[-1] + reverse_string(s[0:-1])
else: return s
```
or
```
def reverse_string(s):
return s[-1] + reverse_string(s[0:-1]) if s else s
``` | ```
s = input("Enter your string: ")
def rev(s):
if len(s) == 1:
print(s[0])
exit()
else:
#print the last char in string
#end="" prints all chars in string on same line
print(s[-1], end="")
"""Next line replaces whole string with same
string, but with 1 ... |
69,422,541 | I am using the python code below to attempt to create a graph that fills the entire figure. The problem is I need the graph portion to stretch to fill the entire figure, there should not be any of the green showing and the graphed data should start at one side and go all the way to the other. I have found similar examp... | 2021/10/03 | [
"https://Stackoverflow.com/questions/69422541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2231017/"
] | Just use `IsNullOrWhiteSpace`; it does what `IsNullOrEmpty` does:
>
> Return `true` if the value parameter is null or Empty, or if value consists exclusively of white-space characters.
> *-- documentation for IsNullOrWhiteSpace*
>
>
>
And it is mapped by EF Core to an SQL of
```
@value IS NULL OR LTRIM(RTRIM(@va... | You cannot translate this method to SQL Server. However, you can use a method that returns Expression. For example:
```
public static Expression<Func<Student, bool>> IsSomething()
{
return (s) => string.IsNullOrEmpty(s.FirstName) || string.IsNullOrWhiteSpace(s.FirstName);
}
```
Usually, you should call AsEnumera... |
15,034,105 | Let say I have the a list of list
```
[ ['B','2'] , ['o','0'], ['y']]
```
and I want to combine the list into something like this without using iteratool
```
["Boy","B0y","2oy","20y"]
```
I can't use itertool because I have to use python 2.5. | 2013/02/22 | [
"https://Stackoverflow.com/questions/15034105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968057/"
] | [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product) does what you want.
```
>>> [''.join(x) for x in itertools.product(*[['B', '2'], ['o', '0'], ['y']])]
['Boy', 'B0y', '2oy', '20y']
``` | If you don't want to use itertools, this list comprehension produces your output:
```
>>> LoL=[['B','2'], ['o','0'], ['y']]
>>> [a+b+c for a in LoL[0] for b in LoL[1] for c in LoL[2]]
['Boy', 'B0y', '2oy', '20y']
```
This is a more compact version of this:
```
LoL=[['B','2'], ['o','0'], ['y']]
r=[]
for a in LoL[0]:... |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | You can add --user in the end of your command. This works well in my case!
```
--user
```
My example:
```
python -m pip install --upgrade pip --user
``` | Just try on Administrator cmd
```
pip install --user numpy
``` |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Add `--user` to the command.
eg:
```
pip install -r requirements.txt --user
``` | The question was for windows but if any linux users that stumbled here (like me) : Permission Error Persists by adding `--user` in my virtualenv on Ubuntu 19 when I want to generate **requirements.txt**. Also, I can't `pip install --user` as well since I'm in an virtualenv. My solution was just using `sudo pip3 install... |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Run your command Prompt on Admin-Mode in Windows,it will stop throwing errors for user-rights.
Steps:
1. On Windows, type "Cmd" on searchbox to search for command prompt.
2. When "Command Prompt" search result appears,right-click>Run as Administrator. | Run your command prompt on admin mode.
type :
`cd\`
then type:
`cd [Your python location path]`
on mycomputer it's:
`cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32`
then type:
```
python -m pip install --upgrade pip
```
You can follow this guide~
<https://datatofish.com/upgrade-pip/> |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Run your command Prompt on Admin-Mode in Windows,it will stop throwing errors for user-rights.
Steps:
1. On Windows, type "Cmd" on searchbox to search for command prompt.
2. When "Command Prompt" search result appears,right-click>Run as Administrator. | You can add --user in the end of your command. This works well in my case!
```
--user
```
My example:
```
python -m pip install --upgrade pip --user
``` |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Add `--user` to the command.
eg:
```
pip install -r requirements.txt --user
``` | You can add --user in the end of your command. This works well in my case!
```
--user
```
My example:
```
python -m pip install --upgrade pip --user
``` |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Run your command prompt on admin mode.
type :
`cd\`
then type:
`cd [Your python location path]`
on mycomputer it's:
`cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32`
then type:
```
python -m pip install --upgrade pip
```
You can follow this guide~
<https://datatofish.com/upgrade-pip/> | I had the same problem.
After installing Python for all the users, wanted to install Django.
For that I've gone to the Command Prompt (without using Admin mode) and
```
pip.exe install django==2.2
```
This prompted the following message
>
> Could not install packages due to an EnvironmentError: [WinError 5]
> A... |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Append the `--user` modifier to your command as suggested in the error.
>
> `--user` makes pip install packages in your home directory instead, which doesn't require any special privileges.
>
>
>
More: [What is the purpose "pip install --user ..."?](https://stackoverflow.com/questions/42988977/what-is-the-purpos... | You can add --user in the end of your command. This works well in my case!
```
--user
```
My example:
```
python -m pip install --upgrade pip --user
``` |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Append the `--user` modifier to your command as suggested in the error.
>
> `--user` makes pip install packages in your home directory instead, which doesn't require any special privileges.
>
>
>
More: [What is the purpose "pip install --user ..."?](https://stackoverflow.com/questions/42988977/what-is-the-purpos... | Just try on Administrator cmd
```
pip install --user numpy
``` |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Add `--user` to the command.
eg:
```
pip install -r requirements.txt --user
``` | Run your command prompt on admin mode.
type :
`cd\`
then type:
`cd [Your python location path]`
on mycomputer it's:
`cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32`
then type:
```
python -m pip install --upgrade pip
```
You can follow this guide~
<https://datatofish.com/upgrade-pip/> |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | Add `--user` to the command.
eg:
```
pip install -r requirements.txt --user
``` | I wanted to throw an answer out here because I've been against a rock wall since upgrading to python 3.18. Pip install stopped working with a module error which was rectified with py -m pip install --user. *but* I would still get this permissions error. I uninstalled, reinstalled, and downgraded Python and Pip. I ran c... |
10,396,640 | My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this:
```
tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
```
I'm wonder... | 2012/05/01 | [
"https://Stackoverflow.com/questions/10396640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367581/"
] | ```
>>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
>>> min(int(j) for i in nums for j in i)
24
``` | ```
>>> from itertools import chain
>>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
>>> min(map(int,chain.from_iterable(nums)))
24
``` |
10,396,640 | My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this:
```
tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
```
I'm wonder... | 2012/05/01 | [
"https://Stackoverflow.com/questions/10396640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367581/"
] | ```
>>> from itertools import chain
>>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
>>> min(map(int,chain.from_iterable(nums)))
24
``` | ```
>>> min(reduce(lambda x, y: x + y, nums))
``` |
10,396,640 | My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this:
```
tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
```
I'm wonder... | 2012/05/01 | [
"https://Stackoverflow.com/questions/10396640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367581/"
] | ```
>>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
>>> min(int(j) for i in nums for j in i)
24
``` | ```
>>> min(reduce(lambda x, y: x + y, nums))
``` |
61,629,693 | I have a 3D numpy array with integer values, something defined as:
```
import numpy as np
x = np.random.randint(0, 100, (10, 10, 10))
```
Now what I want to do is find the last slice (or alternatively the first slice) along a given axes (say 1) where a particular value occurs. At the moment, I do something like:
`... | 2020/05/06 | [
"https://Stackoverflow.com/questions/61629693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2713740/"
] | You probably can optimize this to be faster, but here is a vectorized version of what you search:
```
axis = 1
mask = np.where(x==val)[axis]
first, last = np.amin(mask), np.amax(mask)
```
It first finds the element `val` in your array using `np.where` and returns the `min` and `max` of indices along desired axis. | Per your question, you want to check if there's any such valid slice and hence, get the start/first, stop/last indices. In absence of any such valid slice, we must return None's there. That needs extra check. Also, we can use `masking` to get those indices in an efficient manner, like so -
```
def slice_info(x, val):
... |
44,987,098 | Is it possible to install [nodejs](/questions/tagged/nodejs "show questions tagged 'nodejs'") packages (/modules) from files like in [ruby](/questions/tagged/ruby "show questions tagged 'ruby'")'s Gemfile as done with `bundle install` or [python](/questions/tagged/python "show questions tagged 'python'")'s requirements... | 2017/07/08 | [
"https://Stackoverflow.com/questions/44987098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just create your package JSON, you can use yarn to manage your packages instead of npm, it's faster.
Inside your package you can create a section of scripts accessed by `npm run`
`scripts: {
customBuild: 'your sh code/ruby/script whateve'
}`
And after you can run on terminal, `npm run customBuild` for example | you can use NPM init to create a package.json file which will store the node packages your application is dependent on, then use npm install which will install the node packages indicated in the package.json file |
55,317,792 | My sonar branch coverage results are not importing into sonarqube.
coverage.xml are generating in jenkins workspace.
following are the below jenkins and error details :
WARN: No report was found for sonar.python.coverage.reportPaths using pattern coverage-reports/coverage.xml
I have tried in my ways but nothing worked... | 2019/03/23 | [
"https://Stackoverflow.com/questions/55317792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11248384/"
] | You are having that error because you are specifying the coverage report path option wrong, and therefore sonar is using the default location `coverage-reports/coverage.xml`.
The correct option is `-Dsonar.python.coverage.reportPath` (in singular). | I still have this problem on Azure Pipelines. Tried many ways without success.
WARN: No report was found for sonar.python.coverage.reportPaths using pattern coverage.xml |
35,857,389 | Encountered the following problem when trying to use the module scipy.optimize.slsqp.
```
>>> import scipy.optimize.slsqp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/scipy/optimize/__init__.py",
line 233, in <module>
from ._minimize import ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35857389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6020400/"
] | Depending on the scope you use it would be loaded in an application context, therefore one time (say in a singleton class loaded at the application startup).
But I wouldn't recommend this approach, I would recommend a proper designed database where you can put your csv data into. This way you would have the database ... | I can read from a CSV file to build your arrays. You can then add the arrays to session scope. The CSV file will only be read at the servlet that processes it. Future usage will be retrieved from session. |
51,529,408 | I must be missing something but I look around and couldn't find reference to this issue.
I have the very basic code, as seen in flask-mongoengine documentation.
test.py:
```
from flask import Flask
from flask_mongoengine import MongoEngine
```
When I run
python test.py
...
```
from flask_mongoengine import Mong... | 2018/07/26 | [
"https://Stackoverflow.com/questions/51529408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5112112/"
] | Since your using a virtual environment did you try opening your editor from your virtual environment?
For example opening the vscode editor from command-line is "code". Go to your virtual environment via the terminal and activate then type "code" at your prompt.
```
terminal:~path/to/virtual-enviroment$ source bin/act... | I had this issue and managed to fix it by deactivating, reinstalling flask-mongoengine and reactivating the venv (all in the Terminal):
```
deactivate
pip install flask-mongoengine
# Not required but good to check it was properly installed
pip freeze
venv\Scripts\activate
flask run
``` |
55,659,835 | I am new to Python and I am trying to separate polygon data into x and y coordinates. I keep getting error: "AttributeError: ("'MultiPolygon' object has no attribute 'exterior'", 'occurred at index 1')"
From what I understand Python object MultiPolygon does not contain data exterior. But how do I remedy this to make ... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55659835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11053854/"
] | I have updated your function `getPolyCoords()` to enable the handling of other geometry types, namely, `MultiPolygon`, `Point`, and `LineString`. Hope it works for your project.
```
def getPolyCoords(row, geom, coord_type):
"""Returns the coordinates ('x|y') of edges/vertices of a Polygon/others"""
# Parse th... | See the shapely docs about [multipolygons](https://shapely.readthedocs.io/en/stable/manual.html#MultiPolygons)
A multipolygon is a sequence of polygons, and it is the polygon object that has the exterior attribute. You need to iterate through the polygons of the multipolygon, and get `exterior.coords` of each polygon.... |
65,146,279 | I need to run K-means clustering algorithm to cluster textual data but by using cosine distance measure instead of Euclidean distance. Any reliable implementation of this in python?
***Edit:***
I have tried to use NLTK as following:
```
NUM_CLUSTERS=3
kclusterer = KMeansClusterer(NUM_CLUSTERS, distance=
... | 2020/12/04 | [
"https://Stackoverflow.com/questions/65146279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10153492/"
] | If you want to do it yourself: [https://stanford.edu/~cpiech/cs221/handouts/kmeans.html](https://stanford.edu/%7Ecpiech/cs221/handouts/kmeans.html)
just change the distance measruing entry. The distance measuring is in the for loop over `i` of the pseudo code. | You can use NLTK for this. The K-means from NLTK allows you to specify which measure of distance you want to use.
[nltk](https://www.nltk.org/) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.