qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 29
22k
| response_k
stringlengths 26
13.4k
| __index_level_0__
int64 0
17.8k
|
---|---|---|---|---|---|---|
65,869,272 | I've created a TensorFlow model that uses RaggedTensors. Model works fine and when calling `model.predict` and I get the expected results.
```
input = tf.ragged.constant([[[-0.9984272718429565, -0.9422321319580078, -0.27657580375671387, -3.185823678970337, -0.6360141634941101, -1.6579184532165527, -1.9000954627990723, -0.49169546365737915, -0.6758883595466614, -0.6677696704864502, -0.532067060470581],
[-0.9984272718429565, -0.9421600103378296, 2.2048349380493164, -1.273996114730835, -0.6360141634941101, -1.5917999744415283, 0.6147914528846741, -0.49169546365737915, -0.6673409938812256, -0.6583622694015503, -0.5273991227149963],
[-0.9984272718429565, -0.942145586013794, 2.48842453956604, -1.6836735010147095, -0.6360141634941101, -1.5785763263702393, -1.900200605392456, -0.49169546365737915, -0.6656315326690674, -0.6583622694015503, -0.5273991227149963],
]])
model.predict(input)
>> array([[0.5138151 , 0.3277698 , 0.26122513]], dtype=float32)
```
I've deployed the model to a TensorFlow serving server and using the following code to invoke:
```
import json
import requests
headers = {"content-type": "application/json"}
data = json.dumps({"instances":[
[-1.3523329846758267, ... more data ],
[-1.3523329846758267, ... more data ],
[-1.3523329846758267, ... more data ],
[-1.3523329846758267, ... more data ,
[-1.3523329846758267, ... more data ],
[-1.3523329846758267, ... more data ],
[-1.3523329846758267, ... more data ],
[-1.3523329846758267, ... more data })
json_response = requests.post('http://localhost:8501/v1/models/fashion_model:predict', data=data, headers=headers)
predictions = json.loads(json_response.text)
```
But then I get the following error:
```
"instances is a plain list, but expecting list of objects as multiple input tensors required as per tensorinfo_map"
```
My model description:
```
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['__saved_model_init_op']:
The given SavedModel SignatureDef contains the following input(s):
The given SavedModel SignatureDef contains the following output(s):
outputs['__saved_model_init_op'] tensor_info:
dtype: DT_INVALID
shape: unknown_rank
name: NoOp
Method name is:
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['args_0'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 11)
name: serving_default_args_0:0
inputs['args_0_1'] tensor_info:
dtype: DT_INT64
shape: (-1)
name: serving_default_args_0_1:0
The given SavedModel SignatureDef contains the following output(s):
outputs['dense_2'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 3)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
WARNING: Logging before flag parsing goes to stderr.
W0124 09:33:16.365564 140189730998144 deprecation.py:506] From /usr/local/lib/python2.7/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1786: calling __init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
Defined Functions:
Function Name: '__call__'
Option #1
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None, 11]), tf.float32, 1, tf.int64)
Argument #2
DType: bool
Value: True
Argument #3
DType: NoneType
Value: None
Option #2
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None, 11]), tf.float32, 1, tf.int64)
Argument #2
DType: bool
Value: False
Argument #3
DType: NoneType
Value: None
Function Name: '_default_save_signature'
Option #1
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None, 11]), tf.float32, 1, tf.int64)
Function Name: 'call_and_return_all_conditional_losses'
Option #1
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None, 11]), tf.float32, 1, tf.int64)
Argument #2
DType: bool
Value: True
Argument #3
DType: NoneType
Value: None
Option #2
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None, 11]), tf.float32, 1, tf.int64)
Argument #2
DType: bool
Value: False
Argument #3
DType: NoneType
Value: None
```
What am I missing?
**Update:**
After inspecting `saved_model_cli` output, I suspect I should send the request as an object like below, but I'm not sure about the inputs...
```
{
"instances": [
{
"args_0": nested-list ?,
"args_0_1": ???
}
]
}
```
**Update2**
A [Colab](https://colab.research.google.com/drive/1DQT616SpJQNY8cMAgXdymANReC6sDfYW?usp=sharing) to test this scenario, a link to download the model is included in the Colab.
**Update 3:**
As suggested by @Niteya Shah I've called the API with:
```
data = json.dumps({
"inputs": {
"args_0": [[-0.9984272718429565, -0.9422321319580078, -0.27657580375671387, -3.185823678970337, -0.6360141634941101, -1.6579184532165527, -1.9000954627990723, -0.49169546365737915, -0.6758883595466614, -0.6677696704864502, -0.532067060470581],
[-0.9984272718429565, -0.9421600103378296, 2.2048349380493164, -1.273996114730835, -0.6360141634941101, -1.5917999744415283, 0.6147914528846741, -0.49169546365737915, -0.6673409938812256, -0.6583622694015503, -0.5273991227149963]],
"args_0_1": [1, 2] #Please Check what inputs come here ?
}
})
```
And got the results (Finally!):
```
{'outputs': [[0.466771603, 0.455221593, 0.581544757]]}
```
Then called the model with the same data like so:
```
import numpy as np
input = tf.ragged.constant([[
[-0.9984272718429565, -0.9422321319580078, -0.27657580375671387, -3.185823678970337, -0.6360141634941101, -1.6579184532165527, -1.9000954627990723, -0.49169546365737915, -0.6758883595466614, -0.6677696704864502, -0.532067060470581],
[-0.9984272718429565, -0.9421600103378296, 2.2048349380493164, -1.273996114730835, -0.6360141634941101, -1.5917999744415283, 0.6147914528846741, -0.49169546365737915, -0.6673409938812256, -0.6583622694015503, -0.5273991227149963]
]])
model.predict(input)
```
And got different results:
```
array([[0.4817084 , 0.3649785 , 0.01603118]], dtype=float32)
```
I guess I'm still not there. | 2021/01/24 | [
"https://Stackoverflow.com/questions/65869272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115237/"
] | <https://www.tensorflow.org/tfx/serving/api_rest#predict_api>
I think that you need to use a columnar format as recommended in the REST API instead of the row format because the dimensions of your 0th input do not match.
This means that instead of instances you will have to use inputs.
Since you also have multiple inputs, you will have to also mention that as a named input.
A sample data request could look like this
```
data = json.dumps({
"inputs": {
"args_0": [[-0.9984272718429565, -0.9422321319580078, -0.27657580375671387, -3.185823678970337, -0.6360141634941101, -1.6579184532165527, -1.9000954627990723, -0.49169546365737915, -0.6758883595466614, -0.6677696704864502, -0.532067060470581],
[-0.9984272718429565, -0.9421600103378296, 2.2048349380493164, -1.273996114730835, -0.6360141634941101, -1.5917999744415283, 0.6147914528846741, -0.49169546365737915, -0.6673409938812256, -0.6583622694015503, -0.5273991227149963]],
"args_0_1": [10, 11] #Substitute this with the correct row partition values.
}
})
```
Edit:
I read about Ragged tensors from [here](https://www.tensorflow.org/guide/ragged_tensor#raggedtensor_encoding) and it seems that the second input may be the row partitions. I couldn't find it in the documentation about what row partition style is normally used so I am using the row lengths method.
Luckily TensorFlow ragged provides [methods](https://www.tensorflow.org/guide/ragged_tensor#evaluating_ragged_tensors) that do this for us. Use the `values` and `row_splits` properties to access them. That should work. | Others may benefit from this, as it took me a while to stitch together:
1. Training a toy LSTM model on ragged tensors.
2. Loading it into TensorFlow Serving.
3. Making a prediction request with a serielized ragged tensor.
If anyone knows how to rename "args\_0" and "args\_0\_1", please add.
Relevant Git Issue: <https://github.com/tensorflow/tensorflow/issues/37226>
Build & Save Model
==================
TensorFlow version: 2.9.1
Python version: 3.8.12
```
# Task: predict whether each sentence is a question or not.
sentences = tf.constant(
['What makes you think she is a witch?',
'She turned me into a newt.',
'A newt?',
'Well, I got better.'])
is_question = tf.constant([True, False, True, False])
# Preprocess the input strings.
hash_buckets = 1000
words = tf.strings.split(sentences, ' ')
hashed_words = tf.strings.to_hash_bucket_fast(words, hash_buckets)
# Build the Keras model.
keras_model = tf.keras.Sequential([
tf.keras.layers.Input(shape=[None], dtype=tf.int64, ragged=True),
tf.keras.layers.Embedding(hash_buckets, 16),
tf.keras.layers.LSTM(32, use_bias=False),
tf.keras.layers.Dense(32),
tf.keras.layers.Activation(tf.nn.relu),
tf.keras.layers.Dense(1)
])
keras_model.compile(loss='binary_crossentropy', optimizer='rmsprop')
keras_model.fit(hashed_words, is_question, epochs=5)
print(keras_model.predict(hashed_words))
keras_module_path = "/home/ec2-user/SageMaker/keras-toy-lstm/1"
tf.keras.Model.save(keras_model, keras_module_path)
```
Load & Infer from Model
=======================
Load model into TensorFlow serving container
```
docker run -t --rm -p 8501:8501 -v "/home/ec2-user/SageMaker/keras-toy-lstm/:/models/keras-model" -e MODEL_NAME=keras-model tensorflow/serving
```
```
import requests
import json
payload = {"args_0": [940, 203, 668, 638],
"args_0_1": [0, 4]}
headers = {"content-type": "application/json"}
data = json.dumps({"inputs":payload})
r = requests.post('http://localhost:8501/v1/models/keras-model:predict', data=data, headers=headers)
r.text
```
SavedModelCLI Output
====================
```
(tensorflow2_p38) sh-4.2$ saved_model_cli show --dir /tmp/tmpgp0loz1v/ --all
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['__saved_model_init_op']:
The given SavedModel SignatureDef contains the following input(s):
The given SavedModel SignatureDef contains the following output(s):
outputs['__saved_model_init_op'] tensor_info:
dtype: DT_INVALID
shape: unknown_rank
name: NoOp
Method name is:
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['args_0'] tensor_info:
dtype: DT_INT64
shape: (-1)
name: serving_default_args_0:0
inputs['args_0_1'] tensor_info:
dtype: DT_INT64
shape: (-1)
name: serving_default_args_0_1:0
The given SavedModel SignatureDef contains the following output(s):
outputs['dense_1'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 1)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
Concrete Functions:
Function Name: '__call__'
Option #1
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None]), tf.int64, 1, tf.int64)
Argument #2
DType: bool
Value: True
Argument #3
DType: NoneType
Value: None
Option #2
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None]), tf.int64, 1, tf.int64)
Argument #2
DType: bool
Value: False
Argument #3
DType: NoneType
Value: None
Function Name: '_default_save_signature'
Option #1
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None]), tf.int64, 1, tf.int64)
Function Name: 'call_and_return_all_conditional_losses'
Option #1
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None]), tf.int64, 1, tf.int64)
Argument #2
DType: bool
Value: True
Argument #3
DType: NoneType
Value: None
Option #2
Callable with:
Argument #1
DType: RaggedTensorSpec
Value: RaggedTensorSpec(TensorShape([None, None]), tf.int64, 1, tf.int64)
Argument #2
DType: bool
Value: False
Argument #3
DType: NoneType
Value: None
``` | 4,001 |
69,929,986 | I tried many ways but neither worked. I have to convert string like `assdggg` to `a2sd3g` in python. If letters are next to each other we leave only one letter and before it we write how mamy of them were next to eachother. Any idea how can it be done? | 2021/11/11 | [
"https://Stackoverflow.com/questions/69929986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14868201/"
] | I'd suggest `itertools.groupby` then format as you need
```
from itertools import groupby
# groupby("assdggg")
# {'a': ['a'], 's': ['s', 's'], 'd': ['d'], 'g': ['g', 'g', 'g']}
result = ""
for k, v in groupby("assdggg"):
count = len(list(v))
result += (str(count) if count > 1 else "") + k
print(result) # a2sd3g
``` | Try using `.groupby()`:
```
from itertools import groupby
txt = "assdggg"
print(''.join(str(l) + k if (l := len(list(g))) != 1 else k for k, g in groupby(txt)))
```
output :
```
a2sd3g
``` | 4,002 |
16,704,588 | I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1].
[This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've tried:
1. `webbrowser.register(u'chrome', None, webbrowser.Chrome())`
2. `webbrowser.register(u'chrome', webbrowser.Chrome)`
3. `webbrowser.register(u'chrome', None, webbrowser.GenericBrowser('/Applications/Browsers/Chrome.app'))`
4. `webbrowser.register(u'chrome', None, webbrowser.GenericBrowser('/Applications/Browsers/Chrome.app/Contents/MacOS/Google\ Chrome'))`
All followed by `c.NotebookApp.browser = u'chrome'`
I've fiddled with `webbbrowser` in the interpreter, and couldn't figure out how to create an instance of Chrome.
---
[1]: PS Why is IPython Notebook *so slow* in firefox, especially for pylab with the inline backend? It's orders of magnitude faster (for rendering, scrolling, etc) in chrome. | 2013/05/23 | [
"https://Stackoverflow.com/questions/16704588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730674/"
] | This might not be the right things to do , but
```
$ open -a Google\ Chrome http://localhost:8888
$ open -a Firefox http://localhost:8888
```
Works from me (only on mac) to open any url in one of the 2 browser.
Use the `--no-browser` option and make an bash function that does that.
Or even have a bookmark in Chrome. | For future reference, this works looks the most elegant way to edit `jupyter_notebook_config.py` for me on macOS:
```
c.NotebookApp.browser = u'open -a "Google Chrome" %s'
```
>
> You can obviously replace `"Google Chrome"` with any other browser.
>
>
>
Full procedure:
1. `jupyter notebook --generate-config`
2. `open ./jupyter/jupyter_notebook_config.py`
3. Find the line `#c.NotebookApp.browser` and edit it as above | 4,005 |
7,022,148 | In the below python the message RSU is not supported on single node machine\*\* is not getting printed. can anyone help please??
```
#! /usr/bin/env python
import sys
class SWMException(Exception):
def __init__(self, arg):
print "inside exception"
Exception.__init__(self, arg)
class RSUNotSupported(SWMException):
def __init__(self):
SWMException.__init__(self, "**RSU is not supported on single node machine**")
def isPrepActionNeeded():
if 1==1:
raise RSUNotSupported()
try:
isPrepActionNeeded()
except:
sys.exit(1)
``` | 2011/08/11 | [
"https://Stackoverflow.com/questions/7022148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889384/"
] | It is not printed, because you're even not trying to print it :) Here:
```
try:
isPrepActionNeeded()
except RSUNotSupported as e:
print str(e)
sys.exit(1)
``` | Because you handle the exception with your try/except clause. | 4,015 |
68,435,024 | My code:
```py
import pyttsx3
#sapi5 is default windows voice api
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[1].id)
engine.setProperty('voice', voices[0].id)
def speak(audio):
pass
```
On running the code instead of getting that voice ID printed I am getting this error:
```
Traceback (most recent call last):
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 20, in init
eng = _activeEngines[driverName]
File "C:\Program Files\Python39\lib\weakref.py", line 134, in __getitem__
o = self.data[key]()
KeyError: 'sapi5'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\subha\Documents\Personal_Space\Code_Samples\Mavis\jarvis.py", line 4, in <module>
engine = pyttsx3.init('sapi5')
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\__init__.py", line 22, in init
eng = Engine(driverName, debug)
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\engine.py", line 30, in __init__
self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\driver.py", line 50, in __init__
self._module = importlib.import_module(name)
File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module>
import pythoncom
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\pythoncom.py", line 2, in <module>
import pywintypes
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 105, in <module>
__import_pywin32_system_module__("pywintypes", globals())
File "C:\Users\subha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__
raise ImportError("No system module '%s' (%s)" % (modname, filename))
ImportError: No system module 'pywintypes' (pywintypes39.dll)
```
On the other side I had a project based on cv2 that was working fine earlier but now that also stopped working.
The only change that happened recently is that I upgraded to windows11 yesterday. So is that the problem? How to fix it? | 2021/07/19 | [
"https://Stackoverflow.com/questions/68435024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15030983/"
] | No, they don't conflict with Windows 11! For me they still are running efficiently! Try to uninstall Python and pip including all modules as well and then download them.
If that doesn't work you, you could try switching to older versions of Python that support these quiet efficiently or you can download these libraries from internet optimized for Windows 11.
Or, if none of these help you can consider switching back to Windows 10!
Note- Windows 11 is still relatively new and there are lot of bugs which different users are facing which may be uncommon for others. I am myself facing some issues which are uncommon and the methods which I prescribed may not work for you! | Ok, I have tried the code and works fine for me now as per me there is no problem in your code and its probably the windows 11 or the installation has a defect / glitch cause windows 11 is not yet the smoothest and it may be causing your code to not run properly
i would also like to ask you to see if the permissions and stuff are allowed maybe they are stopping access i hope these words have been helpful i have tried my best to understand hope it goes well | 4,017 |
16,627,533 | I'm very new to python. How can I convert a unit in python? I mean not using a conversion function to do this. Just as a built-in syntax in python, like the complex numbers works.
E.g., when I typed 1mm in python command line, and expect the result is 0.001
```
>>> 1mm
0.001
#Just like the built-in complex numbers or scintific expressions
>>> 1j
1j
>>> 1e3
1000
```
I totally have no idea, do anybody knows how complex number or scintific expressions work in Python? Or any idea on how to do it.
thanks, | 2013/05/18 | [
"https://Stackoverflow.com/questions/16627533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2397416/"
] | how bout
```
mm = 0.001
1*mm
```
not sure if that is what you are asking for ... if you have ever messed with report lab they do simillar stuff. (although they use it to convert pixels to actual border sizes and what not)
eg:
```
inch = DPI*some_thing
margin = 2*inch
``` | If you are doing scientific work with physical units, it is a good idea to use a units library (not built-in) like [quantities](http://pythonhosted.org/quantities/user/tutorial.html) which also supports scientific packages like numpy. For example:
```
>>> from quantities import meter
>>> q = 1 * meter
>>> q.units = 'ft' # or 'foot' or 'feet'
>>> print q
3.280839895013123 ft
``` | 4,018 |
43,897,628 | I updated to pandas 0.20.1 recently and I tried to use the new feature of to\_json(orient='table')
```
import pandas as pd
pd.__version__
# '0.20.1'
a = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
a.to_json('a.json', orient='table')
```
But how can I read this JSON file to DataFrame?
I tried `pd.read_json('a.json', orient='table')` but it raised `ValueError`
```
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-22-7527b25107ef> in <module>()
----> 1 pd.read_json('a.json', orient='table')
C:\Anaconda3\lib\site-packages\pandas\io\json\json.py in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit, encoding, lines)
352 obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
353 keep_default_dates, numpy, precise_float,
--> 354 date_unit).parse()
355
356 if typ == 'series' or obj is None:
C:\Anaconda3\lib\site-packages\pandas\io\json\json.py in parse(self)
420
421 else:
--> 422 self._parse_no_numpy()
423
424 if self.obj is None:
C:\Anaconda3\lib\site-packages\pandas\io\json\json.py in _parse_no_numpy(self)
650 else:
651 self.obj = DataFrame(
--> 652 loads(json, precise_float=self.precise_float), dtype=None)
653
654 def _process_converter(self, f, filt=None):
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
273 dtype=dtype, copy=copy)
274 elif isinstance(data, dict):
--> 275 mgr = self._init_dict(data, index, columns, dtype=dtype)
276 elif isinstance(data, ma.MaskedArray):
277 import numpy.ma.mrecords as mrecords
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in _init_dict(self, data, index, columns, dtype)
409 arrays = [data[k] for k in keys]
410
--> 411 return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
412
413 def _init_ndarray(self, values, index, columns, dtype=None, copy=False):
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)
5592 # figure out the index, if necessary
5593 if index is None:
-> 5594 index = extract_index(arrays)
5595 else:
5596 index = _ensure_index(index)
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in extract_index(data)
5643
5644 if have_dicts:
-> 5645 raise ValueError('Mixing dicts with non-Series may lead to '
5646 'ambiguous ordering.')
5647
ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.
```
So is there a way i can read that JSON file? Thanks in advance.
PS: the JSON file looks like this:
```
{"schema": {"pandas_version":"0.20.0","fields":[{"type":"integer","name":"index"},{"type":"integer","name":"a"},{"type":"integer","name":"b"}],"primaryKey":["index"]}, "data": [{"index":0,"a":1,"b":4},{"index":1,"a":2,"b":5},{"index":2,"a":3,"b":6}]}
``` | 2017/05/10 | [
"https://Stackoverflow.com/questions/43897628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4956987/"
] | Apparently the new method outputs some metadata with the dataset into json such as the pandas version. Hence, consider using the built-in `json` module to read in this nested object to extract the value at *data* key:
```
import json
...
with open('a.json', 'r') as f:
json_obj = json.loads(f.read())
df = pd.DataFrame(json_obj['data']).set_index('index')
df.index.name = None
print(df)
# a b
# 0 1 4
# 1 2 5
# 2 3 6
```
---
Should you intend to use *type* and *name*, run dictionary and list comprehension on those parts in nested json. Though here, *integer* has to be sliced to *int*. The *dtype* argument cannot be used since names are not saved until after the step:
```
with open('a.json', 'r') as f:
json_obj = json.loads(f.read())
df = pd.DataFrame(json_obj['data'], columns=[t['name']
for t in json_obj['schema']['fields']])
df = df.astype(dtype={t['name']: t['type'][:3]
for t in json_obj['schema']['fields']}).set_index('index')
df.index.name = None
print(df)
# a b
# 0 1 4
# 1 2 5
# 2 3 6
``` | Here is a function I have developed from Parfait answer:
```
def table_to_df(table):
df = pd.DataFrame(table['data'],
columns=[t['name'] for t in table['schema']['fields']])
for t in table['schema']['fields']:
if t['type'] == "datetime":
df[t['name']] = pd.to_datetime(df[t['name']], infer_datetime_format=True)
df.set_index(table['schema']['primaryKey'], inplace=True)
return df
``` | 4,020 |
66,129,496 | I am using Featuretools library to try to generate custom features involving customer transactions. I tested the function and it returns the answer so I am not sure why I am getting this error.
I tried using the following link:
<https://featuretools.alteryx.com/en/stable/getting_started/primitives.html>
Thank you!
```
from featuretools.primitives import make_agg_primitive
from featuretools.variable_types import DatetimeTimeIndex, Numeric, Categorical
def test_fun(categorical, datetimeindex):
x = pd.DataFrame({'store_name': categorical, 'session_start_time': datetimeindex})
x_mode = list(x['store_name'].mode())[0]
x = x[x['store_name'] == x_mode]
y = x.session_start_time.diff().fillna(pd.Timedelta(seconds=0))/np.timedelta64(1, 's')
return y.median()
Test_Fun = make_agg_primitive(function = test_fun,
input_types = [Categorical, DatetimeTimeIndex],
return_type = [Numeric])
fm, fd = ft.dfs(
entityset = es,
target_entity = 'customers',
agg_primitives = [Test_Fun],
cutoff_time = lt,
cutoff_time_in_index = True,
include_cutoff_time = False,
verbose = True,
)
```
Results in the following error
```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-492-358f980bb6b0> in <module>
20 return_type = [Numeric])
21
---> 22 fm, fd = ft.dfs(
23 entityset = es,
24 target_entity = 'customers',
~\Anaconda3\lib\site-packages\featuretools\utils\entry_point.py in function_wrapper(*args, **kwargs)
38 ep.on_error(error=e,
39 runtime=runtime)
---> 40 raise e
41
42 # send return value
~\Anaconda3\lib\site-packages\featuretools\utils\entry_point.py in function_wrapper(*args, **kwargs)
30 # call function
31 start = time.time()
---> 32 return_value = func(*args, **kwargs)
33 runtime = time.time() - start
34 except Exception as e:
~\Anaconda3\lib\site-packages\featuretools\synthesis\dfs.py in dfs(entities, relationships, entityset, target_entity, cutoff_time, instance_ids, agg_primitives, trans_primitives, groupby_trans_primitives, allowed_paths, max_depth, ignore_entities, ignore_variables, primitive_options, seed_features, drop_contains, drop_exact, where_primitives, max_features, cutoff_time_in_index, save_progress, features_only, training_window, approximate, chunk_size, n_jobs, dask_kwargs, verbose, return_variable_types, progress_callback, include_cutoff_time)
259 seed_features=seed_features)
260
--> 261 features = dfs_object.build_features(
262 verbose=verbose, return_variable_types=return_variable_types)
263
~\Anaconda3\lib\site-packages\featuretools\synthesis\deep_feature_synthesis.py in build_features(self, return_variable_types, verbose)
287 assert isinstance(return_variable_types, list), msg
288
--> 289 self._run_dfs(self.es[self.target_entity_id], RelationshipPath([]),
290 all_features, max_depth=self.max_depth)
291
~\Anaconda3\lib\site-packages\featuretools\synthesis\deep_feature_synthesis.py in _run_dfs(self, entity, relationship_path, all_features, max_depth)
412 """
413
--> 414 self._build_transform_features(all_features, entity, max_depth=max_depth)
415
416 """
~\Anaconda3\lib\site-packages\featuretools\synthesis\deep_feature_synthesis.py in _build_transform_features(self, all_features, entity, max_depth, require_direct_input)
576 input_types = input_types[0]
577
--> 578 matching_inputs = self._get_matching_inputs(all_features,
579 entity,
580 new_max_depth,
~\Anaconda3\lib\site-packages\featuretools\synthesis\deep_feature_synthesis.py in _get_matching_inputs(self, all_features, entity, max_depth, input_types, primitive, primitive_options, require_direct_input, feature_filter)
793 primitive, primitive_options, require_direct_input=False,
794 feature_filter=None):
--> 795 features = self._features_by_type(all_features=all_features,
796 entity=entity,
797 max_depth=max_depth,
~\Anaconda3\lib\site-packages\featuretools\synthesis\deep_feature_synthesis.py in _features_by_type(self, all_features, entity, max_depth, variable_type)
768 if (variable_type == variable_types.PandasTypes._all or
769 f.variable_type == variable_type or
--> 770 any(issubclass(f.variable_type, vt) for vt in variable_type)):
771 if max_depth is None or f.get_depth(stop_at=self.seed_features) <= max_depth:
772 selected_features.append(f)
~\Anaconda3\lib\site-packages\featuretools\synthesis\deep_feature_synthesis.py in <genexpr>(.0)
768 if (variable_type == variable_types.PandasTypes._all or
769 f.variable_type == variable_type or
--> 770 any(issubclass(f.variable_type, vt) for vt in variable_type)):
771 if max_depth is None or f.get_depth(stop_at=self.seed_features) <= max_depth:
772 selected_features.append(f)
TypeError: issubclass() arg 1 must be a class
``` | 2021/02/10 | [
"https://Stackoverflow.com/questions/66129496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15179950/"
] | Default CSS should be overridden by your CSS. SO your need to use `!important` in your CSS. Here is the css :
```
<style>
.toasting {
color: yellow !important;
background-color: pink !important;
}
</style>
```
Working [demo](https://codesandbox.io/s/vue-toasted-example-forked-hd4n3?file=/App.vue) | If someone is facing the same issue, the solution above works but keep in mind it's only **without** style scoping! | 4,021 |
15,777,992 | First, note that I understand that `==` is used for comparing two expressions, while `=` is used for assigning a value to a variable. However, python is such a clean language with minimal syntax requirements, that this seems like an easy operator to axe. Also I am not trying to start a debate or discussion, but rather learn if there is something that I'm missing to improve my knowledge of programming.
Just as (in python) we don't need to declare a variable to be an int, or a string, and the language determines this based on the value assigned, why doesn't the 'if' statement simply determine that the `=` is a comparison, not an assignment?
Another example is that python got rid of many of the {} and [] in other languages and simply used the indentation, because indenting and using braces is redundant. It seems to me that `if foo == goo:` is also redundant. But perhaps there's something I'm not yet aware of. Hence the question! | 2013/04/03 | [
"https://Stackoverflow.com/questions/15777992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2218093/"
] | One very simple reason is that python allows boolean expressions:
```
a = b == c
```
and also multiple assignment:
```
a = b = c
```
In the first case, `a` gets assigned a boolean value\* (`True` or `False`) depending on whether `b` and `c` are equal. In the second case, `a` and `b` end up referencing the same object (`c`). Clearly you can't support both with only a single operator.
I suppose that you could (in principle) overload `=` only within `if` statements (since assignment isn't allowed there), but that would get confusing -- Especially for people coming from `C` where [an assignment *is* allowed in an `if` statement.](https://stackoverflow.com/q/151850/748858) The zen wins again ("Explicit is better than implicit").
---
* It doesn't actually have to be a boolean value. It is actually whatever is returned by `a`'s `__eq__` method (or `b`'s `__eq__` if the former returns `NotImplemented`) -- *most* objects return a boolean, but a few don't (`numpy.ndarray` is one common object which has an `__eq__` which returns another `ndarray` for instance). | The two operators can overlap. For instance, consider
```
a = b = c
```
which sets `a` and `b` both to `c`, and
```
a = b == c
```
which sets `a` to either `True` or `False` based on whether `b` and `c` are equal.
---
More generally, Python attempts to avoid syntax that is even possibly ambiguous to allow the parser to be simpler. Even if the ambiguity above could be resolved, it would involve adding a number of special cases, and generally addng complexity to the parser. Keeping the two operators separate neatly avoids the issue. | 4,022 |
72,089,771 | I have a working python package that's a CLI tool and I wanted to convert it into a single `.exe` file to upload it to other package managers so I used Pyinstaller. After building the `.exe` file with this command:
```
pyinstaller -c --log-level=DEBUG main.py 2> build.txt --onefile --exclude-module=pytest --add-data "src;src"
```
I double-clicked the .exe file but it closed immediately but in that split second, I saw the expected output which is supposed to be the command-line interface so the .exe does work but not entirely.
**main.py**
```
from src.Categorize_CLI.__main__ import main
if __name__ == "__main__":
main()
```
**.spec file**
```
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['main.py'],
pathex=[],
binaries=[],
datas=[('src', 'src')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=['pytest'],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='main',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
```
**Update**
I got it working by dragging the main.exe file to a open command prompt and then pressed enter and it worked, and I got an error:
```
RuntimeError: 'package' is not installed. Try passing 'package_name' instead.
[15592] Failed to execute script 'main' due to unhandled exception!
``` | 2022/05/02 | [
"https://Stackoverflow.com/questions/72089771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15747757/"
] | It means that the parameter is optional and has a dynamic default value. Usually, optional parameters have default values that are static, like this:
```
foo (string $bar = null): bool
```
Or this:
```
foo (string $bar = 0): bool
```
But in some cases, the default value changes depending on environment. These are shown by a question mark:
```
assert(mixed $assertion, string $description = ?): bool
```
And then the description of the parameter will tell you more details about what the exact value is:
>
> From PHP 7, if no description is provided, a default description equal to the source code for the invocation of assert() is provided.
>
>
> | The `$description` argument is optional, but its default value is not a constant. The manual explains:
>
> From PHP 7, if no description is provided, a default description equal to the source code for the invocation of `assert()` is provided.
>
>
>
This can't be easily expressed in the syntax summary, so they used `?` as a placeholder. | 4,023 |
41,982,238 | Is there a way to add a header row to a CSV without loading the CSV into memory in python? I have an 18GB CSV I want to add a header to, and all the methods I've seen require loading the CSV into memory, which is obviously unfeasible. | 2017/02/01 | [
"https://Stackoverflow.com/questions/41982238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6637269/"
] | You will need to rewrite the whole file. Simplest is not to use python
```
echo 'col1, col2, col2,... ' > out.csv
cat in.csv >> out.csv
```
Python based solutions will work at much higher levels and will be a lot slower. 18GB is a lot of data after all. Better to work with operating system functionality, which will be the fastest. | Here is a comparison of the three suggested solutions for a ~200 MB CSV file with 10^6 rows and 10 columns (n=50).
The ratio stays approximately the same for larger and smaller files (10 MB to 8 GB).
>
> cp:shutil:csv\_reader 1:10:55
>
>
>
i.e. using the builtin `cp` function is approximately 55 times faster than using Python's `csv` module.
Computer:
* regular HDD
* Python 3.5.2 64-bit
* Ubuntu 16.04
* i7-3770
[](https://i.stack.imgur.com/9Kfil.png)
---
```
import csv
import random
import shutil
import time
import subprocess
rows = 1 * 10**3
cols = 10
repeats = 50
shell_script = '/tmp/csv.sh'
input_csv = '/tmp/temp.csv'
output_csv = '/tmp/huge_output.csv'
col_titles = ['titles_' + str(i) for i in range(cols)]
with open(shell_script, 'w') as f:
f.write("#!/bin/bash\necho '{0}' > {1}\ncat {2} >> {1}".format(','.join(col_titles), output_csv, input_csv))
with open(shell_script, 'w') as f:
f.write("echo '{0}' > {1}\ncat {2} >> {1}".format(','.join(col_titles), output_csv, input_csv))
subprocess.call(['chmod', '+x', shell_script])
run_times = dict([
('csv_writer', list()),
('external', list()),
('shutil', list())
])
def random_csv():
with open(input_csv, 'w') as csvfile:
csv_writer = csv.writer(csvfile, delimiter=',')
for i in range(rows):
csv_writer.writerow([str(random.random()) for i in range(cols)])
with open(output_csv, 'w'):
pass
for r in range(repeats):
random_csv()
#http://stackoverflow.com/a/41982368/2776376
start_time = time.time()
with open(input_csv) as fr, open(output_csv, "w", newline='') as fw:
cr = csv.reader(fr)
cw = csv.writer(fw)
cw.writerow(col_titles)
cw.writerows(cr)
run_times['csv_writer'].append(time.time() - start_time)
random_csv()
#http://stackoverflow.com/a/41982383/2776376
start_time = time.time()
subprocess.call(['bash', shell_script])
run_times['external'].append(time.time() - start_time)
random_csv()
#http://stackoverflow.com/a/41982383/2776376
start_time = time.time()
with open('header.txt', 'w') as header_file:
header_file.write(','.join(col_titles))
with open(output_csv, 'w') as new_file:
with open('header.txt', 'r') as header_file, open(input_csv, 'r') as main_file:
shutil.copyfileobj(header_file, new_file)
shutil.copyfileobj(main_file, new_file)
run_times['shutil'].append(time.time() - start_time)
print('#'*20)
for key in run_times:
print('{0}: {1:.2f} seconds'.format(key, run_times[key][-1]))
print('#'*20)
print('Averages')
for key in run_times:
print('{0}: {1:.2f} seconds'.format(key, sum(run_times[key])/len(run_times[key])))
```
---
If you really want to do it in Python, you could create the header file first and then merge it with your 2nd file via [`shutil.copyfileobj`](https://docs.python.org/3/library/shutil.html).
```
import shutil
with open('header.txt', 'w') as header_file:
header_file.write('col1;col2;col3')
with open('new_file.csv', 'w') as new_file:
with open('header.txt', 'r') as header_file, open('main.csv', 'r') as main_file:
shutil.copyfileobj(header_file, new_file)
shutil.copyfileobj(main_file, new_file)
``` | 4,026 |
54,195,111 | I have a JSON data set that looks like this:
```
{"sequence":109428985,"bids":[["0.1243","53",5],["0.12429","24",2],["0.12428","6",1],["0.12427","6",2],["0.12426","6",1],["0.12425","6",1],["0.12424","6",1],["0.12423","6",1],["0.12422","6",1],["0.12421","6",1],["0.124206","6496",2],["0.124205","36032",1],["0.124201","20",1],["0.1242","191",2],["0.124193","400",1],["0.12419","6",1],["0.124189","1214",1],["0.12418","6",1],["0.12417","6",1],["0.12416","6",1],["0.12415","6",1],["0.12414","6",1],["0.12413","6",1],["0.12412","6",1],["0.12411","6",1],["0.1241","6",1],["0.12409","6",1],["0.12408","6",1],["0.12407","6",1],["0.12406","6",1],["0.12405","6",1],["0.124044","14",1],["0.12404","6",1],["0.12403","6",1],["0.12402","6",1],["0.12401","6",1],["0.124","64576",5],["0.12399","6",1],["0.12398","6",1],["0.12397","6",1],["0.12396","6",1],["0.12395","6",1],["0.12394","6",1],["0.12393","6",1],["0.12392","6",1],["0.12391","6",1],["0.1239","6",1],["0.12389","6",1],["0.12388","6",1],["0.12387","6",1]],"asks":[["0.124304","20",1],["0.12434","6",1],["0.12435","6",1],["0.12436","6",1],["0.12437","6",2],["0.12438","6",2],["0.12439","7",2],["0.124453","20",1],["0.124481","1",1],["0.124559","535",1],["0.12456","1210",1],["0.124566","10058",1],["0.124601","7480",1],["0.12462","19",2],["0.124621","1",1],["0.12463","6",1],["0.12464","6",1],["0.12465","6",1],["0.12466","6",1],["0.124668","5306",1],["0.124669","1",1],["0.12467","6",1],["0.124671","20",1],["0.124674","691",1],["0.12468","6",1],["0.124683","20",1],["0.12469","6",1],["0.124697","20",1],["0.1247","6",1],["0.12471","6",1],["0.12472","6",1],["0.12473","6",1],["0.12474","6",1],["0.12475","6",1],["0.12476","6",1],["0.12477","7",2],["0.124779","20",1],["0.12478","7",2],["0.124784","12",1],["0.12479","6",1],["0.124796","1",1],["0.1248","6",1],["0.12481","6",1],["0.12483","6",1],["0.12484","6",1],["0.12485","6",1],["0.124855","1",1],["0.12487","6",1],["0.124889","16500",1],["0.12489","6",1]]}
```
I am trying to pull the data from the first two elements in the lists, and change them so I can put them in as numbers into a database.
For example, this:
```
["0.1243","53",5],["0.12429","24",2],["0.12428","6",1]
```
Should change to this:
```
0.1243 53
0.12429 24
0.12428 6
```
Here is my current code:
```
import requests
import json
import re
url = 'https://api.pro.coinbase.com/products/BAT-USDC/book?level=2'
trade_data = requests.get(url).json()
bid_data = trade_data['bids']
print(bid_data)
```
This is what is returned:
```
[[u'0.124456', u'1158', 3], [u'0.12445', u'6', 1], [u'0.12442', u'6', 1], [u'0.12441', u'6', 1], [u'0.1244', u'6', 1], [u'0.12439', u'6', 1], [u'0.12438', u'6', 1], [u'0.12437', u'6', 2], [u'0.12436', u'6', 2], [u'0.12435', u'6', 1], [u'0.12434', u'6', 1], [u'0.12433', u'6', 1], [u'0.124315', u'6991', 1], [u'0.124314', u'1212', 1], [u'0.1243', u'6', 3], [u'0.12429', u'6', 2], [u'0.12428', u'6', 1], [u'0.12427', u'6', 2], [u'0.124261', u'2419', 1], [u'0.12426', u'6', 1], [u'0.124251', u'20', 1], [u'0.12425', u'6', 1], [u'0.12424', u'6', 1], [u'0.12423', u'6', 1], [u'0.12422', u'6', 1], [u'0.12421', u'6', 1], [u'0.124206', u'20', 1], [u'0.124205', u'36032', 1], [u'0.124201', u'20', 1], [u'0.1242', u'391', 3], [u'0.124193', u'400', 1], [u'0.12419', u'6', 1], [u'0.12418', u'6', 1], [u'0.12417', u'6', 1], [u'0.12416', u'6', 1], [u'0.12415', u'6', 1], [u'0.12414', u'6', 1], [u'0.12413', u'6', 1], [u'0.12412', u'6', 1], [u'0.12411', u'6', 1], [u'0.1241', u'6', 1], [u'0.12409', u'6', 1], [u'0.12408', u'6', 1], [u'0.12407', u'6', 1], [u'0.12406', u'6', 1], [u'0.12405', u'6', 1], [u'0.124044', u'14', 1], [u'0.12404', u'6', 1], [u'0.12403', u'6', 1], [u'0.12402', u'6', 1]]
```
I do not know where the u's came from, and I do not know how to isolate the 2 numbers of importance to my calculations from this "list in list" format. I am a programming noob, and I apologize for that.
Any help is greatly appreciated, and thanks in advance!
Closest previous question I have found:
[how to extract string inside single quotes using python script](https://stackoverflow.com/questions/19449709/how-to-extract-string-inside-single-quotes-using-python-script) | 2019/01/15 | [
"https://Stackoverflow.com/questions/54195111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10915583/"
] | What I've done: I've recalculated the `viewBox` of your svg element, then I calculated the center of your svg. I've added a blue circle with the center in the center of the svg element.
To get the size of your svg I deleted first the transform and used the `getBBox()` method. I've used the properties of the bounding box for the new `viewBox` value
```css
svg{width:90vh;}
```
```html
<svg viewBox="64 32 1506 1506">
<circle cx="817" cy="785" r="680" fill="skyblue" />
<g
fill="red" stroke="none">
<path d="M715 1534 c-191 -31 -370 -134 -489 -280 -55 -67 -118 -192 -143
-284 -27 -101 -25 -293 5 -390 43 -136 97 -226 197 -326 80 -80 104 -98 195
-142 135 -66 235 -87 375 -79 510 28 846 542 664 1018 -87 228 -278 400 -514
463 -61 17 -236 28 -290 20z m285 -191 c176 -58 318 -202 372 -378 31 -97 31
-243 0 -340 -75 -243 -304 -415 -552 -415 -258 0 -486 168 -562 415 -31 97
-31 243 0 340 38 124 120 235 230 309 152 104 333 128 512 69z"/>
<path d="M746 1155 c-48 -17 -94 -59 -113 -105 -11 -24 -17 -86 -21 -199 l-5
-164 -52 58 c-50 56 -52 58 -58 34 -4 -13 -7 -51 -7 -84 l1 -60 87 -93 87 -93
97 88 98 88 0 84 0 84 -22 -19 c-13 -10 -40 -34 -61 -54 l-39 -35 4 152 c3
144 4 153 27 177 46 49 143 42 179 -12 15 -23 17 -54 13 -294 l-3 -268 65 0
65 0 7 284 c7 281 7 285 -15 330 -24 51 -58 79 -121 101 -52 19 -161 19 -213
0z"/>
</g>
</svg>
```
**Observation:** In my code the svg element has a width of 90vh. You may set it to whatever you need. | Just to expand on enxanetas answer to orient the arrow correctly, here is the code, with all transforms reduced and your viewbox/sizes intact (plus I tidied up the circles):
```html
<?xml version="1.0" encoding="utf-8"?>
<svg version="1.0" width="160pt" height="157pt" viewBox="0 0 160 157" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg">
<circle fill="skyblue" cx="80" cy="78.5" r="58.2"/>
<path fill="red" stroke="none" d="M 73 41.4 C 68.2 43.1 63.6 47.3 61.7 51.9 C 60.6 54.3 60 60.5 59.6 71.8 L 59.1 88.2 L 53.9 82.4 C 48.9 76.8 48.7 76.6 48.1 79 C 47.7 80.3 47.4 84.1 47.4 87.4 L 47.5 93.4 L 56.2 102.7 L 64.9 112 L 74.6 103.2 L 84.4 94.4 L 84.4 86 L 84.4 77.6 L 82.2 79.5 C 80.9 80.5 78.2 82.9 76.1 84.9 L 72.2 88.4 L 72.6 73.2 C 72.9 58.8 73 57.9 75.3 55.5 C 79.9 50.6 89.6 51.3 93.2 56.7 C 94.7 59 94.9 62.1 94.5 86.1 L 94.2 112.9 L 100.7 112.9 L 107.2 112.9 L 107.9 84.5 C 108.6 56.4 108.6 56 106.4 51.5 C 104 46.4 100.6 43.6 94.3 41.4 C 89.1 39.5 78.2 39.5 73 41.4 Z M 138.2 78.5 C 138.2 46.4 112.1 20.3 80 20.3 C 47.9 20.3 21.8 46.4 21.8 78.5 C 21.8 110.6 47.9 136.7 80 136.7 C 112.1 136.7 138.2 110.6 138.2 78.5 Z M 155.5 78.5 C 155.5 120.2 121.7 154 80 154 C 38.3 154 4.5 120.2 4.5 78.5 C 4.5 36.8 38.3 3 80 3 C 121.7 3 155.5 36.8 155.5 78.5 Z" />
</svg>
``` | 4,028 |
57,823,327 | I'm new to python and I'm trying to make user registration that is extend from user creation model, I created profile model with the fields I want and saved the profile object with signal when user is saved, the profile is created successfully and linked with the user but profile data is not saved (in this example: jobtitle, company, phone)are empty
in model.py
```
class profile (models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
company = models.CharField(max_length=100)
jobTitle = models.CharField(max_length = 100,default ='')
phonenumber = PhoneNumberField(null=False, blank=False, unique=True, help_text='Contact phone number', default ='')
@receiver(post_save, sender = User)
def create_user_profile( sender, instance, created, **kwargs):
if created:
profile.objects.create(user = instance)
instance.profile.save()
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
```
in forms.py
```
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required= True)
company = forms.CharField(required = True)
phonenumber = PhoneNumberField(widget=forms.TextInput(attrs={'placeholder': ('Phone')}), label=("Phone number"), required=True)
first_name = forms.CharField(required = True)
jobTitle = forms.CharField(required = True)
class Meta:
model = User
fields = [
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
'company',
'jobTitle'
]
def save(self, commit=True):
user = super(UserRegisterForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
```
in views.py
```
#User register
def signup(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save()
UserProfile = user.profile
username = form.cleaned_data.get('username')
company = form.cleaned_data.get('company')
jobTitle = form.cleaned_data.get('jobTitle')
phonenumber = form.cleaned_data.get('phonenumber')
UserProfile.save()
messages.success(request, f'Account is created for {username}!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/signup.html', {'form': form})
```
so can you help me to understand what is causing this issue? I'm expecting to save the inserted values when registering into the profile model.
Thank you | 2019/09/06 | [
"https://Stackoverflow.com/questions/57823327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2930966/"
] | Remove the second `@receiver(post_save, sender=User)`, it's useless (it's always done in the #1 profile).
When you do `user = form.save()`, the signal is raised, creating an *empty* `profile`.
So, just after `user = form.save()`, get the profile that has been created through the signal, like:
```
profile = Profile.objects.get(user=user)
username = form.cleaned_data.get('username')
company = form.cleaned_data.get('company')
jobTitle = form.cleaned_data.get('jobTitle')
phonenumber = form.cleaned_data.get('phonenumber')
profile.save()
```
And my advice: read PEP8 of Python: class always "UpCase", variable always lower\_case. | You need to also import signals in app to let django know about your implementation.
You can implement it in following manner:
```
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
``` | 4,030 |
38,134,900 | I'm following the `rangeslider` example on the Plotly website: <https://plot.ly/python/range-slider/>
Is there a way to automatically (or even manually) rescale the y axis as the x range changes? For example, if the date range in the example above is set between Nov 2008 - April 2009, how can we automatically rescale the y axis to a more appropriate range to see the features in the data better? | 2016/06/30 | [
"https://Stackoverflow.com/questions/38134900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4830338/"
] | There is no need to use triple pointer `***`. Passing two-dimensional array will work as is. Here is the code:
```
#include <stdio.h>
#include <stdlib.h>
// create zero initialized matrix
int** callocMatrix(int rmax, int colmax) {
int **mat = calloc(rmax, sizeof(int*));
for(int i = 0; i < rmax; i++) mat[i] = calloc(colmax, sizeof(int));
return mat;
}
// fill matrix
void setMatrix(int **mat, int r, int c){
printf("Insert the elements of your matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("Insert element [%d][%d]: ", i, j);
scanf("%d", &mat[i][j]); // no problem here
printf("matrix[%d][%d]: %d\n", i, j, mat[i][j]);
}
}
}
// print matrix
void printMatrix(int **mat, int r, int c){
for (int i=0; i<r;i++){
for (int j=0; j<c;j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
int main(int argc, char *argv[]) {
int r = 3, c = 3;
int **mat = callocMatrix(r, c);
setMatrix(mat, r, c);
printMatrix(mat, r, c);
}
``` | Should be:
```
scanf("%d", &(*mat)[i][j]);
```
You're passing a pointer to you matrix object, so you need to dereference it (with `*`) just as you do with `printf`. `scanf` then needs the address of the element to write into, so you need the `&` | 4,031 |
34,989,032 | ```
#code like this
import dns
import dns.resolver
import dns.name
import dns.message
import dns.query
request = dns.message.make_query("google.com",dns.rdatatype.NS)
response = dns.query.udp(request,"216.239.32.10")
print response.authority
```
but it's null
=============
and then when use " nslookup google.com 216.239.32.10 "
can get
Server: 216.239.32.10
Address: 216.239.32.10#53
Name: google.com
Address: 216.58.221.238
Obviously,it's an authority answer
but why can't I get the authority section when use dnspython? | 2016/01/25 | [
"https://Stackoverflow.com/questions/34989032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836175/"
] | Are you sure?
```
c:\srv>nslookup google.com 216.239.32.10
Server: ns1.google.com
Address: 216.239.32.10
Name: google.com
Addresses: 2a00:1450:400f:805::200e
178.74.30.16
178.74.30.49
178.74.30.37
178.74.30.24
178.74.30.26
178.74.30.59
178.74.30.57
178.74.30.48
178.74.30.46
178.74.30.27
178.74.30.53
178.74.30.35
178.74.30.20
178.74.30.42
178.74.30.31
178.74.30.38
c:\srv>python
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns
>>> import dns.resolver, dns.name
>>> import dns.message, dns.query
>>> r = dns.message.make_query('google.com', dns.rdatatype.NS)
>>> resp = dns.query.udp(r, '216.239.32.10')
>>> print resp.authority
[]
>>> print resp
id 63079
opcode QUERY
rcode NOERROR
flags QR AA RD
;QUESTION
google.com. IN NS
;ANSWER
google.com. 345600 IN NS ns3.google.com.
google.com. 345600 IN NS ns4.google.com.
google.com. 345600 IN NS ns2.google.com.
google.com. 345600 IN NS ns1.google.com.
;AUTHORITY
;ADDITIONAL
ns3.google.com. 345600 IN A 216.239.36.10
ns4.google.com. 345600 IN A 216.239.38.10
ns2.google.com. 345600 IN A 216.239.34.10
ns1.google.com. 345600 IN A 216.239.32.10
>>>
``` | I also encountered the same problem.
It turned out to be that some DNS resolvers do not reply with authority or additional sections (Check the packets using Wireshark).
Change the IP address to `127.0.1.1` in your python code and make sure that you have configured your DNS resolver is not pointing to your original resolver (Check `cat /etc/resolv.conf`).
You should see the authority section in you result. | 4,032 |
57,438,262 | I have a python function that reads random snippets from a large file and does some processing on it. I want the processing to happen in multiple processes and so make use of multiprocessing. I open the file (in binary mode) in the parent process and pass the file descriptor to each child process then use a multiprocessing.Lock() to synchronize access to the file. With a single worker things work as expected, but with more workers, even with the lock, the file reads will randomly return bad data (usually a bit from one part of the file and a bit from the another part of the file). In addition, the position within the file (as returned by file.tell()) will often get messed up. This all suggests a basic race condition accessing the descriptor, but my understanding is the multiprocessing.Lock() should prevent concurrent access to it. Does file.seek() and/or file.read() have some kind of asynchronous operations that don't get contained within the lock/unlock barriers? What is going here?
An easy workaround is to have each process open the file individually and get its own file descriptor (I've confirmed this does work), but I'd like to understand what I'm missing. Opening the file in text mode also prevents the issue from occurring, but doesn't work for my use case and doesn't explain what is happening in the binary case.
I've run the following reproducer on a number of Linux systems and OS X and on various local and remote file systems. I always get quite a few bad file positions and at least a couple of checksum errors. I know the read isn't guaranteed to read the full amount of data requested, but I've confirmed that is not what is happening here and omitted that code in an effort to keep things concise.
```
import argparse
import multiprocessing
import random
import string
def worker(worker, args):
rng = random.Random(1234 + worker)
for i in range(args.count):
block = rng.randrange(args.blockcount)
start = block * args.blocksize
with args.lock:
args.fd.seek(start)
data = args.fd.read(args.blocksize)
pos = args.fd.tell()
if pos != start + args.blocksize:
print(i, "bad file position", start, start + args.blocksize, pos)
cksm = sum(data)
if cksm != args.cksms[block]:
print(i, "bad checksum", cksm, args.cksms[block])
args = argparse.Namespace()
args.file = '/tmp/text'
args.count = 1000
args.blocksize = 1000
args.blockcount = args.count
args.filesize = args.blocksize * args.blockcount
args.num_workers = 4
args.cksms = multiprocessing.Array('i', [0] * args.blockcount)
with open(args.file, 'w') as f:
for i in range(args.blockcount):
data = ''.join(random.choice(string.ascii_lowercase) for x in range(args.blocksize))
args.cksms[i] = sum(data.encode())
f.write(data)
args.fd = open(args.file, 'rb')
args.lock = multiprocessing.Lock()
procs = []
for i in range(args.num_workers):
p = multiprocessing.Process(target=worker, args=(i, args))
procs.append(p)
p.start()
```
Example output:
```
$ python test.py
158 bad file position 969000 970000 741000
223 bad file position 908000 909000 13000
232 bad file position 679000 680000 960000
263 bad file position 959000 960000 205000
390 bad file position 771000 772000 36000
410 bad file position 148000 149000 42000
441 bad file position 677000 678000 21000
459 bad file position 143000 144000 636000
505 bad file position 579000 580000 731000
505 bad checksum 109372 109889
532 bad file position 962000 963000 243000
494 bad file position 418000 419000 2000
569 bad file position 266000 267000 991000
752 bad file position 732000 733000 264000
840 bad file position 801000 802000 933000
799 bad file position 332000 333000 989000
866 bad file position 150000 151000 248000
866 bad checksum 109116 109375
887 bad file position 39000 40000 974000
937 bad file position 18000 19000 938000
969 bad file position 20000 21000 24000
953 bad file position 542000 543000 767000
977 bad file position 694000 695000 782000
``` | 2019/08/09 | [
"https://Stackoverflow.com/questions/57438262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/601004/"
] | This seems to be caused by buffering: using `open(args.file, 'rb', buffering=0)` I can't reproduce anymore.
<https://docs.python.org/3/library/functions.html#open>
>
> buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off [...] When no buffering argument is given, the default buffering policy works as follows: [...] Binary files are buffered in fixed-size chunks; the size of the buffer [...] will typically be 4096 or 8192 bytes long. [...]
>
>
> | I've checked, only using multiprocessing.Lock (without buffering = 0), still met the `bad data`. with both `multiprocessing.Lock` and `buffering=0`, all things goes well | 4,033 |
11,836,748 | I am using
```
httplib.HTTPConnection ("http://ipaddr:port")
conn.request("GET", "", params, headers)
```
I am able to do PUT/GET using ipaddr:port using my firefox client!!.
But I am seeing this error on execution of the script:
```
File "post_python.py", line 5, in <module>
conn.request("GET", "", params, headers)
File "/usr/lib64/python2.6/httplib.py", line 914, in request
self._send_request(method, url, body, headers)
File "/usr/lib64/python2.6/httplib.py", line 951, in _send_request
self.endheaders()
File "/usr/lib64/python2.6/httplib.py", line 908, in endheaders
self._send_output()
File "/usr/lib64/python2.6/httplib.py", line 780, in _send_output
self.send(msg)
File "/usr/lib64/python2.6/httplib.py", line 739, in send
self.connect()
File "/usr/lib64/python2.6/httplib.py", line 720, in connect
self.timeout)
File "/usr/lib64/python2.6/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known"
```
Please can someone help me ?? | 2012/08/06 | [
"https://Stackoverflow.com/questions/11836748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1524625/"
] | Try this instead (without "http://" before the IP address):
```
conn = httplib.HTTPConnection("x.x.x.x", port)
conn.request("GET", "", params, headers)
``` | You might have a proxy in between that the browser already knows about. If you're under linux try setting `http_proxy` environment variable. | 4,034 |
54,496,251 | I'm trying to create a PDF file using Python and FPDF. I've read the project's page about unicode and I've tryed to follow their instructions, but everytime I run my program, I receave the error:
>
> File "eventsmanager.py", line 8 SyntaxError: Non-ASCII character
> '\xc3' in file eventsmanager.py on line 8, but no encoding declared;
> see <http://python.org/dev/peps/pep-0263/> for details
>
>
>
This is my program:
```
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.add_font('gargi', '', 'gargi.ttf', uni=True)
pdf.set_font('gargi', '', 14)
pdf.write(8, 'Olá!!')
pdf.ln(20)
pdf.output('tuto3.pdf', 'F')
```
Can you help me understanding what I'm doing wrong? | 2019/02/02 | [
"https://Stackoverflow.com/questions/54496251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10735382/"
] | You need to declare that the file encoding is UTF8 as Python 2 defaults to Latin-1. UTF8 became default in Python 3. The linked PEP contain the required line that you have to add at the beginning of the file:
```
# coding: utf8
```
This must be the first line after the `#!` line
EMACS and VIM formats are also supported.
It is sad that the error message doesn't include the solution. | If you are using Python 3.x you have to use:
```
pdf.output(dest='S').encode('latin-1','ignore')
```
or
```
text=text.encode('latin-1', 'ignore').decode('latin-1')
```
in order to get the output. | 4,037 |
52,641,587 | I made a class in python and when I tried to call it into another python file (after importing it) it doesn't recognizes it as a class but as an object and then it tells me that my class is not callable
here is my class:
```
class Cell:
def __init__(self,value=9,isVissible=False):
self.value=value
self.isVisible=isVissible
def setValue(self,value):
self.value=value
def setVisible(self):
self.visible=True
```
and here is where I tried to call it:
```
import Cell,random
class Board:
def __init__(self):
self.board = []
for i in range(12):
a = []
for j in range(12):
x = Cell() <=== right here it's an error
.
.
.(the rest of my program)
```
and finally here is the error:
```
x=Cell()
TypeError: 'module' object is not callable
```
can anyone help me fix this, even my teacher didn't understand my mistake | 2018/10/04 | [
"https://Stackoverflow.com/questions/52641587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10455256/"
] | The `Cell` has been used for both your imported module and your class. According to the error, python has mapped it to the module name. So, when you are writing `Cell()`, it tries to use the module name as a function, instead of calling the class constructor.
If the class `Cell` is inside the `Cell` module, use `Cell.Cell()` instead, or change your import to `from Cell import Cell`. Otherwise, rename either the module or the class. | Your import statement is wrong, you're importing a module called Cell instead of your Cell class. You should use lower case for your filenames and import it like so:
```
from cell import Cell
test = Cell()
``` | 4,038 |
26,979,711 | I am limited to python2.5, and I thought that threading.Thread was asynchronous. I run: python t.py and the script does not return to the shell until 3 seconds have gone by, which means its blocking. Why is it blocking?
My Code:
```
#!/usr/bin/python
import threading,time
def doit():
time.sleep(3)
print "DONE"
thr = threading.Thread(target=doit, args=(), kwargs={})
thr.start() # will run "foo"
``` | 2014/11/17 | [
"https://Stackoverflow.com/questions/26979711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420259/"
] | By default, threads in Python are non-daemonic. A Python application [will not exit](https://docs.python.org/2.7/library/threading.html#thread-objects) until the all non-daemon threads have completed, so in your case it won't exit until `doit` has finished. If you want to script to exit immediately upon reaching the end of the main thread, you need to make the thread a daemon, by setting the [`daemon` attribute](https://docs.python.org/2.7/library/threading.html#threading.Thread.daemon) prior to starting the thread:
```
thr = threading.Thread(target=doit, args=(), kwargs={})
thr.daemon = True
thr.start()
``` | Threading in Python is "kind-of" asynchronous. What does this mean?
* Only one thread can be running Python code at one time
* threads that are Python code and CPU intensive will not benefit
Your issue seems to be that you think a Python thread should keep running after Python itself quits -- that's not how it works. If you do make a thread a `daemon` then when Python quits those threads just die, instantly -- no cleanup, no error recovery, just dead.
If you want to actually make a daemon process, something that keeps running in the background after the main application exits, you want to look at `os.fork()`. If you want to do it the easier way, you can try my daemon library, [pandaemonium](https://pypi.python.org/pypi/pandaemonium) | 4,039 |
45,248,279 | I tried to run a script using turtle module on pythonanywere.com, however, got stuck at an error that cannot find the module named "**tkinter**" and I need to install python3-tk package. I followed this tutorial [installing new modules on pythonanywhere](https://help.pythonanywhere.com/pages/InstallingNewModules/) in attempt to install the package in Bash console on pythonanywere.com by running `pip3.5 install --user package3-tk`.
However, I got the error that "could not find the version that satisfies the requirement package3-tk".
I also tried to replace the package name with `tkinter` with no luck either. | 2017/07/21 | [
"https://Stackoverflow.com/questions/45248279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5186966/"
] | You can't use the tkinter module from a server such as pythonanywhere. It needs to have a connection to a display and not just a browser window.
<https://www.pythonanywhere.com/forums/topic/360/> | Just learnt the lesson of finding answer by asking question in different way. My purpose is to use turtle module on pythonanywere, which is not possible as explained in the answer above. However, I just found out that pythonanywhere has an affiliate website that is free and supports turtle ([www.trinker.io](http://www.trinker.io)) | 4,040 |
49,631,966 | I want to access a list which is field from different python function. Please refer below code for more details
```
abc = []
name = "apple,orange"
def foo(name):
abc = name.split(',')
print abc
foo(name)
print abc
print name
```
The output is as below.
>
> ['apple', 'orange']
>
>
> []
>
>
> apple,orange
>
>
>
Since I am new to python can anybody explain me why the 7th line (`print abc`) doesn't give the result as ['apple', 'orange']?
If I need to have the filled list at the line 7 (['apple', 'orange']), what should I do ? | 2018/04/03 | [
"https://Stackoverflow.com/questions/49631966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5993900/"
] | ```
abc = []
name = "apple,orange"
def foo(name):
global abc # do this
abc = name.split(',')
print abc
foo(name)
print abc
print name
``` | abc from function is not the same as abc from first line, because abc in def foo is a local variable, if you want to refer to abc declared above you have to use global abc. | 4,041 |
22,796,547 | I have an issue where I am trying to log some additional attributes (the user ID and connecting host IP) on a Python CGI script. This is running under python 2.6.8 on a RHEL 5 system. I am following the documentation for extending the attributes in the basic logging dictionary as follows:
```
from __future__ import print_function
import logging
import os
import sys
LOG_DIR = '/apps/log'
LOG_PAGE = re.sub(r'\/(.*)\/.*$', r'\1', os.environ['REQUEST_URI'])
#
# The log format should be
# <date stamp> <level> <remote user> <remote IP>: <message>
#
LOG_FORMAT = '%(asctime)-19s %(levelname)-9s %(user)-7s %(clientip)-15s - %(message)s'
LOG_DATE = '%Y-%m-%d %H:%M:%S'
orig_user = os.environ['REMOTE_USER']
orig_ip = os.environ['REMOTE_ADDR']
xtras = { 'user': orig_user, 'clientip': orig_ip }
#
# Set up logging
#
LOG_FILE = LOG_DIR + '/' + LOG_PAGE
logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=logging.DEBUG, filename=LOG_FILE)
logit = logging.getLogger('groups')
```
and I am calling it with:
```
logit.debug('user visited page',extra=xtras)
logit.warn('user has no account under domain %s', myDOM, extra=xtras)
```
Every time a message is logged, 3 KeyError exceptions are logged in the web servers error logs:
```
s = self._fmt % record.__dict__, referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
KeyError: 'user', referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
Traceback (most recent call last):, referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
File "/usr/lib64/python2.6/logging/__init__.py", line 776, in emit, referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
msg = self.format(record), referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
File "/usr/lib64/python2.6/logging/__init__.py", line 654, in format, referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
return fmt.format(record), referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
File "/usr/lib64/python2.6/logging/__init__.py", line 439, in format, referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
s = self._fmt % record.__dict__, referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
KeyError: 'user', referer: https://its-serv-dev.case.edu/googlegroups/index.cgi
```
What is odd is that the KeyError exceptions are only generated for one of the "extra" dictionary items, and that the information IS being logged into the file correctly. I've tried various combinations of removing the two extra components (the error just shifts to whatever is left) and nothing seems to stop the exception from being thrown unless I completely remove the extra information.
I suppose I could just include the information in a format string as part of the message, but it seems like reinventing the wheel. | 2014/04/01 | [
"https://Stackoverflow.com/questions/22796547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980968/"
] | I figured out what was happening here:
I am also importing Google's oauth2client.client module which is using the logging module as well. Since the oauth2cleint.client module is considered a "child" of my page, logging was being passed up to my logging object and since the Google module is not including the extra logging dictionary in its calls, the GOOGLE module was the item generating the KeyError exceptions, not my own code. I've worked around the issue for the moment by including the extra items as part of the message, and will need to dig a little more into the the logging module to see if there is a better way to keep the Google oauth2clent.client module logging from conflicting with the page logging. | Faced a similar problem. I guess the error occurs when there are loggers used which do not have filters added (to add the extra attributes on instantiating the loggers) but still passing the records to the formatters using formats corresponding to these attributes.
[Link to documentation example using filters](https://docs.python.org/2/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output) | 4,043 |
50,760,826 | I have the date in the following format:
```
data = """*Date:* May 31, 2018 at 1:49:05 PM EDT"""
```
I need to extract the date and month in 2 different variables:
```
date = 31
month = "May"
```
How can i do that using regex in python 3??. I tried using the below regex to get the date and month:
```
month , date = re.findall("^*Date:* (\w+) (\d+)", message_data, re.MULTILINE).groups()
```
Can anyone help with this regex? | 2018/06/08 | [
"https://Stackoverflow.com/questions/50760826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422965/"
] | **Update**: [@Markonius' answer](https://stackoverflow.com/a/54548429/288201) is the proper way to do it.
Here is a script that does this based on experimenting with an LFS repository. I didn't look at the LFS protocol in details, so there might be quirks unaccounted for, but it worked for my simple case.
[git-lfs-cat-file](https://github.com/koterpillar/desktop/blob/02c01fee06944ab3e211da253c201e1dc40c0595/bin/git-lfs-cat-file)
The relevant details are:
* LFS files are stored in the index with the following structure:
```
version https://git-lfs.github.com/spec/v1
oid sha256:abcdeffffffffffffff
size nnnnnnnn
```
* Actual LFS object will then be under `.git/lfs/objects/ab/cd/abcdeffffffffffffff`. | When last I was working with LFS, there were conversations on the project page about better integration - such as by writing diff and/or merge tools that could be plugged in via `.gitattributes`. These didn't seem to be considered high priority, since the main intended use case of LFS is to protect large *binary* files (but certainly I've come across multiple cases where either I had a large text file, or the only reasonable way to set up LFS tracking rules cast a wide enough net to catch some smaller text files). I'm not sure if there's been any progress on those tools, as I haven't looked at the project page in a while.
Absent those things, there's not a particularly "slick" way to do what you're asking. You can set up two work trees and check out different versions. You can check out one version, rename it, and then check out the other. | 4,045 |
45,225,741 | I'm learning how to use the python `xarray` package, however, I'm having troubles with multi-dimensional data. Specifically, how to add and use additional coordinates?
Here's an example.
```
import xarray as xr
import pandas as pd
import numpy as np
site_id = ['brw','sum','mlo']
dss = []
for site in site_id:
df = pd.DataFrame(np.random.randn(20,2),columns=['a','b'],index=pd.date_range('20160101',periods=20,freq='MS'))
ds = df.to_xarray()
dss.append(ds)
ds = xr.concat(dss, dim=pd.Index(site_id, name='site'))
ds.coords['latitude'] = [71.323, 72.58, 19.5362]
ds.coords['longitude'] = [156.6114, 38.48, 155.5763]
```
My `xarray` data set looks like:
```
>>> ds
<xarray.Dataset>
Dimensions: (index: 20, latitude: 3, longitude: 3, site: 3)
Coordinates:
* index (index) datetime64[ns] 2016-01-01 2016-02-01 2016-03-01 ...
* site (site) object 'brw' 'sum' 'mlo'
* latitude (latitude) float64 71.32 72.58 19.54
* longitude (longitude) float64 156.6 38.48 155.6
Data variables:
a (site, index) float64 -0.1403 -0.2225 -1.199 -0.8916 0.1149 ...
b (site, index) float64 -1.506 0.9106 -0.7359 2.123 -0.1987 ...
```
I can select a series by using the sel method based on a site code. For example:
```
>>> ds.sel(site='mlo')
```
But how do I select data based on the other coordinates (i.e. latitude or longitude)?
```
>>> ds.sel(latitude>50)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'latitude' is not defined
``` | 2017/07/20 | [
"https://Stackoverflow.com/questions/45225741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4603445/"
] | Thanks for the easy-to-reproduce example!
You can only use `.sel(x=y)` with `=`, because of the limitations of python. An example using `.isel` with latitude (`sel` is harder because it's a float type):
```
In [7]: ds.isel(latitude=0)
Out[7]:
<xarray.Dataset>
Dimensions: (index: 20, longitude: 3, site: 3)
Coordinates:
* index (index) datetime64[ns] 2016-01-01 2016-02-01 2016-03-01 ...
* site (site) object 'brw' 'sum' 'mlo'
latitude float64 71.32
* longitude (longitude) float64 156.6 38.48 155.6
Data variables:
a (site, index) float64 0.6493 -0.9105 -0.9963 -0.6206 0.6856 ...
b (site, index) float64 -0.03405 -1.49 0.2646 -0.3073 0.6326 ...
```
To use conditions such as `>`, you can use `.where`:
```
In [9]: ds.where(ds.latitude>50, drop=True)
Out[9]:
<xarray.Dataset>
Dimensions: (index: 20, latitude: 2, longitude: 3, site: 3)
Coordinates:
* index (index) datetime64[ns] 2016-01-01 2016-02-01 2016-03-01 ...
* site (site) object 'brw' 'sum' 'mlo'
* latitude (latitude) float64 71.32 72.58
* longitude (longitude) float64 156.6 38.48 155.6
Data variables:
a (site, index, latitude) float64 0.6493 0.6493 -0.9105 -0.9105 ...
b (site, index, latitude) float64 -0.03405 -0.03405 -1.49 -1.49 ...
``` | Another solution for selecting data through "sel" method would be using the "slice" object of Python.
So, in order to select data from a Xarray object whose latitude is greater than a given value (i.e. 50 degrees north), one could write the following:
```
ds.sel(dict(latitude=slice(50,None)))
```
I hope it helps.
Sincerely, | 4,048 |
62,113,084 | I googled it and tried lots of solutions, but this problem still happened.
This is my yum.conf:
```
[root@localhost etc]# cat yum.conf
[main]
gpgcheck=1
installonly_limit=3
clean_requirements_on_remove=True
best=True
```
I tried to re-install epel-release:
```
[root@localhost ~]# dnf update
Last metadata expiration check: 0:01:38 ago on Sat 09 May 2020 01:30:20 AM EDT.
Dependencies resolved.
Nothing to do.
Complete!
[root@localhost ~]# dnf install httpd
Last metadata expiration check: 0:01:45 ago on Sat 09 May 2020 01:30:20 AM EDT.
No match for argument: httpd
Error: Unable to find a match: httpd
[root@localhost ~]# dnf provides httpd
Last metadata expiration check: 0:01:56 ago on Sat 09 May 2020 01:30:20 AM EDT.
Error: No Matches found
[root@localhost ~]# dnf install epel-release
Last metadata expiration check: 0:02:31 ago on Sat 09 May 2020 01:30:20 AM EDT.
Package epel-release-8-8.el8.noarch is already installed.
Dependencies resolved.
Nothing to do.
Complete!
```
Re-enabled modules:
```
[root@localhost ~]# dnf search httpd
Last metadata expiration check: 0:02:45 ago on Sat 09 May 2020 01:30:20 AM EDT.
====================================================================== Name & Summary Matched: httpd =======================================================================
libmicrohttpd-doc.noarch : Documentation for libmicrohttpd
libmicrohttpd-devel.i686 : Development files for libmicrohttpd
libmicrohttpd-devel.x86_64 : Development files for libmicrohttpd
lighttpd-filesystem.noarch : The basic directory layout for lighttpd
centos-logos-httpd.noarch : CentOS-related icons and pictures used by httpd
lighttpd-mod_authn_pam.x86_64 : Authentication module for lighttpd that uses PAM
lighttpd-mod_authn_gssapi.x86_64 : Authentication module for lighttpd that uses GSSAPI
keycloak-httpd-client-install.noarch : Tools to configure Apache HTTPD as Keycloak client
lighttpd-mod_mysql_vhost.x86_64 : Virtual host module for lighttpd that uses a MySQL database
lighttpd-fastcgi.x86_64 : FastCGI module and spawning helper for lighttpd and PHP configuration
lighttpd-mod_authn_mysql.x86_64 : Authentication module for lighttpd that uses a MySQL database
python3-keycloak-httpd-client-install.noarch : Tools to configure Apache HTTPD as Keycloak client
=========================================================================== Name Matched: httpd ============================================================================
lighttpd.x86_64 : Lightning fast webserver with light system requirements
httpd-devel.x86_64 : Development interfaces for the Apache HTTP server
httpd-tools.x86_64 : Tools for use with the Apache HTTP Server
httpd-manual.noarch : Documentation for the Apache HTTP server
libmicrohttpd.i686 : Lightweight library for embedding a webserver in applications
libmicrohttpd.x86_64 : Lightweight library for embedding a webserver in applications
sysusage-httpd.noarch : Apache configuration for sysusage
httpd-filesystem.noarch : The basic directory layout for the Apache HTTP server
httpd-filesystem.noarch : The basic directory layout for the Apache HTTP server
========================================================================== Summary Matched: httpd ==========================================================================
mod_dav_svn.x86_64 : Apache httpd module for Subversion server
mod_auth_mellon.x86_64 : A SAML 2.0 authentication module for the Apache Httpd Server
[root@localhost ~]# dnf module list --enabled
Last metadata expiration check: 0:03:42 ago on Sat 09 May 2020 01:30:20 AM EDT.
CentOS-8 - AppStream
Name Stream Profiles Summary
go-toolset rhel8 [d][e] common [d] Go
httpd 2.4 [d][e] common [d], devel, minimal Apache HTTP Server
mariadb 10.3 [d][e] client, server [d], galera MariaDB Module
mysql 8.0 [d][e] client, server [d] MySQL Module
perl-DBD-MySQL 4.046 [d][e] common [d] A MySQL interface for Perl
perl-DBI 1.641 [d][e] common [d] A database access API for Perl
python27 2.7 [d][e] common [d] Python programming language, version 2.7
python36 3.6 [d][e] common [d], build Python programming language, version 3.6
satellite-5-client 1.0 [d][e] common [d], gui Red Hat Satellite 5 client packages
Remi's Modular repository for Enterprise Linux 8 - x86_64
Name Stream Profiles Summary
php remi-7.4 [e] common [d] [i], devel, minimal PHP scripting language
Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled
[root@localhost ~]# dnf module disable httpd
Last metadata expiration check: 0:04:00 ago on Sat 09 May 2020 01:30:20 AM EDT.
Dependencies resolved.
============================================================================================================================================================================
Package Architecture Version Repository Size
============================================================================================================================================================================
Disabling modules:
httpd
Transaction Summary
============================================================================================================================================================================
Is this ok [y/N]: y
Complete!
[root@localhost ~]# dnf module enable httpd:2.4/common
Last metadata expiration check: 0:04:19 ago on Sat 09 May 2020 01:30:20 AM EDT.
Ignoring unnecessary profile: 'httpd/common'
Dependencies resolved.
============================================================================================================================================================================
Package Architecture Version Repository Size
============================================================================================================================================================================
Enabling module streams:
httpd 2.4
Transaction Summary
============================================================================================================================================================================
Is this ok [y/N]: y
Complete!
[root@localhost ~]# dnf module list
CentOS-8 - AppStream 3.6 kB/s | 4.3 kB 00:01
CentOS-8 - Base 6.0 kB/s | 3.9 kB 00:00
CentOS-8 - Extras 441 B/s | 1.5 kB 00:03
CentOS-8 - PowerTools 1.9 kB/s | 4.3 kB 00:02
Extra Packages for Enterprise Linux Modular 8 - x86_64 9.5 kB/s | 9.4 kB 00:00
Extra Packages for Enterprise Linux 8 - x86_64 6.1 kB/s | 9.0 kB 00:01
Node.js Packages for Enterprise Linux 8 - x86_64 9.6 kB/s | 2.5 kB 00:00
Remi's Modular repository for Enterprise Linux 8 - x86_64 417 B/s | 3.5 kB 00:08
Safe Remi's RPM repository for Enterprise Linux 8 - x86_64 2.5 kB/s | 3.0 kB 00:01
CentOS-8 - AppStream
Name Stream Profiles Summary
389-ds 1.4 389 Directory Server (base)
ant 1.10 [d] common [d] Java build tool
container-tools rhel8 [d] common [d] Common tools and dependencies for container runtimes
container-tools 1.0 common [d] Common tools and dependencies for container runtimes
freeradius 3.0 [d] server [d] High-performance and highly configurable free RADIUS server
gimp 2.8 [d] common [d], devel gimp module
go-toolset rhel8 [d][e] common [d] Go
httpd 2.4 [d][e] common [d], devel, minimal Apache HTTP Server
idm DL1 common [d], adtrust, client, dns, server The Red Hat Enterprise Linux Identity Management system module
idm client [d] common [d] RHEL IdM long term support client module
inkscape 0.92.3 [d] common [d] Vector-based drawing program using SVG
javapackages-runtime 201801 [d] common [d] Basic runtime utilities to support Java applications
jmc rhel8 common, core Java Mission Control is a profiling and diagnostics tool for the Hotspot JVM
libselinux-python 2.8 common Python 2 bindings for libselinux
llvm-toolset rhel8 [d] common [d] LLVM
mailman 2.1 [d] common [d] Electronic mail discussion and e-newsletter lists managing software
mariadb 10.3 [d][e] client, server [d], galera MariaDB Module
maven 3.5 [d] common [d] Java project management and project comprehension tool
mercurial 4.8 [d] common [d] Mercurial -- a distributed SCM
mod_auth_openidc 2.3 Apache module suporting OpenID Connect authentication
mysql 8.0 [d][e] client, server [d] MySQL Module
nginx 1.14 [d] common [d] nginx webserver
nginx 1.16 common nginx webserver
nodejs 10 [d][x] common [d], development, minimal, s2i Javascript runtime
nodejs 12 [x] common, development, minimal, s2i Javascript runtime
parfait 0.5 common Parfait Module
perl 5.24 common [d], minimal Practical Extraction and Report Language
perl 5.26 [d] common [d], minimal Practical Extraction and Report Language
perl-App-cpanminus 1.7044 [d] common [d] Get, unpack, build and install CPAN modules
perl-DBD-MySQL 4.046 [d][e] common [d] A MySQL interface for Perl
perl-DBD-Pg 3.7 [d] common [d] A PostgreSQL interface for Perl
perl-DBD-SQLite 1.58 [d] common [d] SQLite DBI driver
perl-DBI 1.641 [d][e] common [d] A database access API for Perl
perl-FCGI 0.78 [d] common [d] FastCGI Perl bindings
perl-YAML 1.24 [d] common [d] Perl parser for YAML
php 7.2 [d] common [d], devel, minimal PHP scripting language
php 7.3 common, devel, minimal PHP scripting language
pki-core 10.6 PKI Core module for PKI 10.6 or later
pki-deps 10.6 PKI Dependencies module for PKI 10.6 or later
postgresql 9.6 client, server [d] PostgreSQL server and client module
postgresql 10 [d] client, server [d] PostgreSQL server and client module
postgresql 12 client, server PostgreSQL server and client module
python27 2.7 [d][e] common [d] Python programming language, version 2.7
python36 3.6 [d][e] common [d], build Python programming language, version 3.6
redis 5 [d] common [d] Redis persistent key-value database
rhn-tools 1.0 [d] common [d] Red Hat Satellite 5 tools for RHEL
ruby 2.5 [d] common [d] An interpreter of object-oriented scripting language
ruby 2.6 common An interpreter of object-oriented scripting language
rust-toolset rhel8 [d] common [d] Rust
satellite-5-client 1.0 [d][e] common [d], gui Red Hat Satellite 5 client packages
scala 2.10 [d] common [d] A hybrid functional/object-oriented language for the JVM
squid 4 [d] common [d] Squid - Optimising Web Delivery
subversion 1.10 [d] common [d], server Apache Subversion
swig 3.0 [d] common [d], complete Connects C/C++/Objective C to some high-level programming languages
varnish 6 [d] common [d] Varnish HTTP cache
virt rhel [d] common [d] Virtualization module
CentOS-8 - PowerTools
Name Stream Profiles Summary
javapackages-tools 201801 common Tools and macros for Java packaging support
mariadb-devel 10.3 MariaDB Module
virt-devel rhel Virtualization module
Extra Packages for Enterprise Linux Modular 8 - x86_64
Name Stream Profiles Summary
389-directory-server stable minimal, legacy, default [d] 389 Directory Server
389-directory-server testing minimal, legacy, default [d] 389 Directory Server
avocado latest minimal, default Framework with tools and libraries for Automated Testing
cobbler 3 default [d] Versatile Linux deployment server
libuv epel8-buildroot devel [d] libuv-devel for EPEL 8
nginx mainline common nginx webserver
nodejs 12 [x] development, minimal, default Javascript runtime
nodejs 13 [x] development, minimal, default Javascript runtime
Remi's Modular repository for Enterprise Linux 8 - x86_64
Name Stream Profiles Summary
glpi 9.3 common [d] Free IT asset management software
glpi 9.4 [d] common [d] Free IT asset management software
php remi-7.2 common [d], devel, minimal PHP scripting language
php remi-7.3 common [d], devel, minimal PHP scripting language
php remi-7.4 [e] common [d] [i], devel, minimal PHP scripting language
redis remi-5.0 common [d] Redis persistent key-value database
redis remi-6.0 common [d] Redis persistent key-value database
Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled
[root@localhost ~]# dnf install @httpd:2.4/common
Last metadata expiration check: 0:04:35 ago on Sat 09 May 2020 01:30:20 AM EDT.
Unable to resolve argument httpd:2.4/common
No match for package httpd
Error: Unable to find a match
```
Same problem to community repo:
```
[root@localhost ~]# vim /etc/yum.repos.d/nginx.repo
[root@localhost ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[root@localhost ~]# yum-config-manager --enable nginx-mainline
[root@localhost ~]# yum install nginx
CentOS-8 - AppStream 7.7 kB/s | 4.3 kB 00:00
CentOS-8 - Base 4.6 kB/s | 3.9 kB 00:00
CentOS-8 - Extras 1.6 kB/s | 1.5 kB 00:00
Extra Packages for Enterprise Linux Modular 8 - x86_64 2.7 kB/s | 8.7 kB 00:03
Extra Packages for Enterprise Linux 8 - x86_64 17 kB/s | 7.4 kB 00:00
nginx stable repo 485 B/s | 15 kB 00:31
nginx mainline repo 4.8 kB/s | 38 kB 00:07
No match for argument: nginx
Error: Unable to find a match: nginx
```
There are some my repo configuration files:
```
[root@localhost yum.repos.d]# ls
CentOS-AppStream.repo CentOS-Debuginfo.repo CentOS-HA.repo CentOS-Vault.repo epel-testing-modular.repo remi.repo
CentOS-Base.repo CentOS-Devel.repo CentOS-Media.repo epel-modular.repo epel-testing.repo remi-safe.repo
CentOS-centosplus.repo CentOS-Extras.repo CentOS-PowerTools.repo epel-playground.repo nodesource-el8.repo
CentOS-CR.repo CentOS-fasttrack.repo CentOS-Sources.repo epel.repo remi-modular.repo
[root@localhost yum.repos.d]# cat CentOS-AppStream.repo
# CentOS-AppStream.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[AppStream]
name=CentOS-$releasever - AppStream
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=AppStream&infra=$infra
#baseurl=http://mirror.centos.org/$contentdir/$releasever/AppStream/$basearch/os/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
[root@localhost yum.repos.d]# cat CentOS-Base.repo
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[BaseOS]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=BaseOS&infra=$infra
#baseurl=http://mirror.centos.org/$contentdir/$releasever/BaseOS/$basearch/os/
gpgcheck=1
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
```
Some details. Some details. Some details. Some details. Some details. Some details. Some details. Some details. Some details. Some details. Some details. Some details. Some details. | 2020/05/31 | [
"https://Stackoverflow.com/questions/62113084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13651016/"
] | You can find the below information useful to install the Nginx web server. But, Nginx is not available in CentOS 8 default repository. So, follow the below steps. And please let me know if it works for you or not.
**Step 1: Installation of EPEL repository**
You have to install the `EPEL` (Extra Package for Enterprise Linux) repository on your server. It is a free repository and allows you to connect many other open-source software packages. Use the below command to install `EPEL`.
```
sudo dnf install epel-release
```
Press `y` to accept the installation confirmation and press the `Enter` key.
After completing the EPEL installation, run the below command to view the available Nginx versions.
```
dnf module list nginx
```
**Step 2: Enabling the latest Nginx web server module**
After that, you have to enable the latest Nginx module. In other words, you have to tell the dnf command to install the newest version. So, use the below command for this purpose.
For instance, The available version of `Nginx` right now is in EPEL repository `1.8`.
```
sudo dnf module enable nginx:1.18
```
**Step 3: Install Nginx web server**
So, we have already installed the EPEL repository. As a result, we can install it directly using dnf command. Use the below command to install the latest version of Nginx.
```
sudo dnf -y install nginx
```
**Step 4: Starting and enabling the Nginx service daemon**
Use the below command, which will start the service immediately, and also it will enable the service on boot.
```
sudo systemctl enable --now nginx
```
**Step 5: Checking the Nginx service status**
```
sudo systemctl status nginx
```
**Step 6: Configuration of the firewall to allow the Nginx traffic**
You can run the below command to add HTTP and https service permanently in the firewall.
```
sudo firewall-cmd --permanent --add-service http
sudo firewall-cmd --permanent --add-service https
```
After allowing the service, we need to reload the firewall service daemon.
```
sudo firewall-cmd --reload
```
**Step 7: Checking the Nginx web server**
Now, you can test your Nginx web server that if it is up and running or not by accessing the public IP of your server or domain name from your web browser.
**http://domain\_name\_or\_IP**
For Instance, if the IP address of the server is **192.168.43.164**. So, the link will look like `http://192.168.43.164`
That's it about NGINX web server installation.
But, if you like to get a few extra details, then You can find a complete example on my blog:
[How to install Nginx web server on CentOS 8](https://www.linuxgurus.in/how-to-install-nginx-webserver-on-centos-8/) | I hope it helps you.
I am trying to install Nginx using Yum.
Instructions for installing Nginx can be found in the Download section of the NGINX official website.
```
sudo vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1
```
In the middle, you need to change the ‘OS’ and ‘OSRELEASE’ items to suit your OS.
I am installing in CentOS 7.0, so I set it as below.
```
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
```
Next step
```
sudo yum install -y nginx
```
Open the web server port in the firewall.
```
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
```
Run Nginx and change it to start automatically at boot time.
```
systemctl start nginx
systemctl enable nginx
```
Source: <http://blog.tjsrms.me/centos-7-nginx-%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0/> | 4,049 |
57,927,442 | On the following linke: <https://classicdb.ch/?quest=788>
here at `//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td`
it contains a text
>
> Mottled Boar slain (10)
>
>
>
```
//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/a
```
contains only:
>
> Mottled Boar
>
>
>
And I only need the second part that contains:
>
> slain (10)
>
>
>
In python with selenium i tried accessing the node directly with:
```
//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/text()
```
However the webdriver can contain only webelements and not text nodes.
>
> The result of the xpa th expression
> "//\*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/a/following-sibling::text()"
> is: [object Text]. It should be an element.
>
>
>
I also tried:
```
//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/a/following-sibling::text()
```
But does returns the same error that it should be an element not an object text.
I have found a workaround by first selecting the text only, then subtracting that from the whole text - but that's ugly.
How do achieve this properly?
Thank you!
EDIT: I must not use specific variables in the code like 'slain' or 'Mottled Boar', because these variables can change in other cases. | 2019/09/13 | [
"https://Stackoverflow.com/questions/57927442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6854832/"
] | Try this xpath.
```
//table[@class='iconlist']//tr//td[contains(.,'slain')]//a[contains(.,'Mottled Boar')]
```
**Edit**
```
//table[@class='iconlist']//tr//td//a
```
Use **javaScript** executor. where `firstChild` will return the `Mottled Boar` and
`lastChild` will return `slain (10)`
```
driver.get("https://classicdb.ch/?quest=788")
print(driver.execute_script('return arguments[0].lastChild.textContent;', driver.find_element_by_xpath("//table[@class='iconlist']//tr//td[1]")))
print(driver.execute_script('return arguments[0].firstChild.textContent;', driver.find_element_by_xpath("//table[@class='iconlist']//tr//td[1]")))
``` | You xpath is correct. you can try this approach to get the text directly from that node. you will need lxml import.
```
from lxml import html
tree = html.fromstring(driver.page_source)
myText = tree.xpath("//*[@id='main-contents']/div[1]/table[1]/tbody/tr/td/a/following-sibling::text()")
print(str(myText).replace('\\t', ''))
``` | 4,050 |
48,583,455 | I'm using the Python C API to call a method. At present I am using [`PyObject_CallMethodObjArgs`](https://docs.python.org/3/c-api/object.html#c.PyObject_CallMethodObjArgs) to do this. This is a variadic function:
```
PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL)
```
This is absolutely fine when the number of arguments is known at compile time. However, I have a scenario where the number of arguments is not known until runtime, they are supplied as an array.
In essence my issue is precisely the same as in this question: [How can I pass an array as parameters to a vararg function?](https://stackoverflow.com/questions/14705920/passing-an-array-as-parameters-to-a-vararg-function)
The accepted answer there tells me that there is no solution to my problem.
Is there are way around this hurdle. If I cannot solve the problem using `PyObject_CallMethodObjArgs` is there an alternative function in the Python C API that can meet my needs?
For instance, [`PyObject_Call`](https://docs.python.org/3/c-api/object.html#c.PyObject_Call) accepts parameters as a Python sequence object. Is it possible to use this function, or one with a similar interface? | 2018/02/02 | [
"https://Stackoverflow.com/questions/48583455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/505088/"
] | I am not sure if I am completey wrong, but AFAICT it should be possible to
* create a tuple with the required number of arguments
* pass this tuple to <https://docs.python.org/3/c-api/object.html#c.PyObject_CallObject> or <https://docs.python.org/3/c-api/object.html#c.PyObject_Call> (this decision depending on the need for kwargs). | A possible way might be to use [libffi](https://sourceware.org/libffi/), perhaps thru the [ctypes](https://docs.python.org/3/library/ctypes.html) Python library. It knows your [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) and [calling conventions](https://en.wikipedia.org/wiki/Calling_convention) (so is partly coded in assembler, for many popular implementations) and enables you to call an arbitrary function of arbitrary signature and arbitrary arity.
Notice that there is [no purely standard way of doing that](https://stackoverflow.com/a/14705987/841108) (without using some external library à la `libffi`...) in portable and standard [C11](https://en.wikipedia.org/wiki/C11_(C_standard_revision)) (check by reading [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf)).
BTW, `libffi` can be used from any C program. And `ctypes` can be used from any Python program.
The Python [*Embedding and extending Python*](https://docs.python.org/3/extending/index.html) chapter explains how to call Python from C, or C from Python. | 4,051 |
42,794,384 | [python update](https://i.stack.imgur.com/gyHJ2.png)
I have Python 3.5 installed on my (LinuxMint) computer by:
```
sudo apt-get install python3.5
```
However, when I run python -V, it shows that Python 2.7 is being used.
How do I tell the system to use the updated version of Python? | 2017/03/14 | [
"https://Stackoverflow.com/questions/42794384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have python2.7 installed and you already have a link to the `python2.7` executable so that when you simply run `python`, it actually runs `python2.7`. When you install python3.5, that link still exists.
You should either run `python3` (or `python3.5`) or you should replace the link with a new link like so (assuming python3.5 in /usr/bin):
```
ln -sf /usr/bin/python3.5 /usr/bin/python
```
Add `sudo` before the command if you don't have permissions to create the link and your user is a sudoer. | More dynamically,
```
ln -sf $(which python3) $(which python)
```
which forces the creation of symbolic link from python3 to python. | 4,052 |
50,619,846 | I'm trying to create a series of subplots:
```
count=0
fig1, axes1 = plt.subplots(nrows=2, ncols=1, figsize=(10,80))
for x in b:
"""code gets data here as a dataframe"""
axes1[count]=q1.plot()
count=count+1
```
However this creates two plots rather than 2 subplots in one figure. I am using python 3.5 in Pycharm. Been racking my brain at what i'm doing wrong here | 2018/05/31 | [
"https://Stackoverflow.com/questions/50619846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9874771/"
] | `DataReceived` event returns on another/secondary thread, which means you will have to marshal back to the UI thread to update your `TextBox`
[SerialPort.DataReceived Event](https://msdn.microsoft.com/fi-fi/library/system.io.ports.serialport.datareceived(v=vs.110).aspx)
>
> The DataReceived event is raised on a secondary thread when data is
> received from the SerialPort object. Because this event is raised on a
> secondary thread, and not the main thread, attempting to modify some
> elements in the main thread, such as UI elements, could raise a
> threading exception. If it is necessary to modify elements in the main
> Form or Control, post change requests back using Invoke, which will do
> the work on the proper thread.
>
>
>
You can use `Dispatcher.BeginInvoke` or `Dispatcher.Invoke Method` to marshal back to the main thread
**Exmaple**
```
Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
```
or
```
someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
``` | I got now the problem that when i send my command using **SerialPort.Write(string cmd)**, I can't read back the answer... | 4,053 |
57,551,049 | I am new to web scraping. I am trying to extract data using python from <https://www.clinicaltrialsregister.eu> using keywords "acute myeloid leukemia", "chronic myeloid leukemia", "acute lymphoblastic leukemia" to extract following information-EudraCT Number, Trial Status, Full title of the trial, Name of Sponsor, Country, Medical condition(s) being investigated, Investigator Networks to be involved in the Trial.
I am trying to collect URL from each link and then go to each page and extract the information, but I am not getting a proper link.
I want URL like "<https://www.clinicaltrialsregister.eu/ctr-search/trial/2014-000526-37/DE>" but getting
```
'/ctr-search/trial/2014-000526-37/DE',
'/ctr-search/trial/2006-001777-19/NL',
'/ctr-search/trial/2006-001777-19/BE',
'/ctr-search/trial/2007-000273-35/IT',
'/ctr-search/trial/2011-005934-20/FR',
'/ctr-search/trial/2006-004950-25/GB',
'/ctr-search/trial/2009-017347-33/DE',
'/ctr-search/trial/2012-000334-19/IT',
'/ctr-search/trial/2012-001594-93/FR',
'/ctr-search/trial/2012-001594-93/results',
'/ctr-search/trial/2007-003103-12/DE',
'/ctr-search/trial/2006-004517-17/FR',
'/ctr-search/trial/2013-003421-28/DE',
'/ctr-search/trial/2008-002986-30/FR',
'/ctr-search/trial/2008-002986-30/results',
'/ctr-search/trial/2013-000238-37/NL',
'/ctr-search/trial/2010-018418-53/FR',
'/ctr-search/trial/2010-018418-53/NL',
'/ctr-search/trial/2010-018418-53/HU',
'/ctr-search/trial/2010-018418-53/DE',
'/ctr-search/trial/2010-018418-53/results',
'/ctr-search/trial/2006-006852-37/DE',
'/ctr-search/trial/2006-006852-37/ES',
'/ctr-search/trial/2006-006852-37/AT',
'/ctr-search/trial/2006-006852-37/CZ',
'/ctr-search/trial/2006-006852-37/NL',
'/ctr-search/trial/2006-006852-37/SK',
'/ctr-search/trial/2006-006852-37/HU',
'/ctr-search/trial/2006-006852-37/BE',
'/ctr-search/trial/2006-006852-37/IT',
'/ctr-search/trial/2006-006852-37/FR',
'/ctr-search/trial/2006-006852-37/GB',
'/ctr-search/trial/2008-000664-16/IT',
'/ctr-search/trial/2005-005321-63/IT',
'/ctr-search/trial/2005-005321-63/results',
'/ctr-search/trial/2011-005023-40/GB',
'/ctr-search/trial/2010-022446-24/DE',
'/ctr-search/trial/2010-019710-24/IT',
```
Attempted Code -
```
import requests
from bs4 import BeautifulSoup
page = requests.get('https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+leukemia&page=1')
soup = BeautifulSoup(page.text, 'html.parser')
#links = [a['href'] for a in soup.find_all('a', href=True) if a.text]
#links_with_text = []
#for a in soup.find_all('a', href=True):
# if a.text:
# links_with_text.append(a['href'])
links = [a['href'] for a in soup.find_all('a', href=True)]
```
OutPut-
```
'/help.html',
'/ctr-search/search',
'/joiningtrial.html',
'/contacts.html',
'/about.html',
'/about.html',
'/whatsNew.html',
'/dataquality.html',
'/doc/Sponsor_Contact_Information_EUCTR.pdf',
'/natauthorities.html',
'/links.html',
'/about.html',
'/doc/How_to_Search_EU_CTR.pdf#zoom=100,0,0',
'javascript:void(0)',
'javascript:void(0)',
'javascript:void(0)',
'javascript:void();',
'#tabs-1',
'#tabs-2',
'&page=2',
'&page=3',
'&page=4',
'&page=5',
'&page=6',
'&page=7',
'&page=8',
'&page=9',
'&page=2',
'&page=19',
'/ctr-search/trial/2014-000526-37/DE',
'/ctr-search/trial/2006-001777-19/NL',
'/ctr-search/trial/2006-001777-19/BE',
'/ctr-search/trial/2007-000273-35/IT',
'/ctr-search/trial/2011-005934-20/FR',
'/ctr-search/trial/2006-004950-25/GB',
'/ctr-search/trial/2009-017347-33/DE',
'/ctr-search/trial/2012-000334-19/IT',
'/ctr-search/trial/2012-001594-93/FR',
'/ctr-search/trial/2012-001594-93/results',
'/ctr-search/trial/2007-003103-12/DE',
'/ctr-search/trial/2006-004517-17/FR',
'/ctr-search/trial/2013-003421-28/DE',
'/ctr-search/trial/2008-002986-30/FR',
'/ctr-search/trial/2008-002986-30/results',
'/ctr-search/trial/2013-000238-37/NL',
'/ctr-search/trial/2010-018418-53/FR',
'/ctr-search/trial/2010-018418-53/NL',
'/ctr-search/trial/2010-018418-53/HU',
'/ctr-search/trial/2010-018418-53/DE',
'/ctr-search/trial/2010-018418-53/results',
'/ctr-search/trial/2006-006852-37/DE',
'/ctr-search/trial/2006-006852-37/ES',
'/ctr-search/trial/2006-006852-37/AT',
'/ctr-search/trial/2006-006852-37/CZ',
'/ctr-search/trial/2006-006852-37/NL',
'/ctr-search/trial/2006-006852-37/SK',
'/ctr-search/trial/2006-006852-37/HU',
'/ctr-search/trial/2006-006852-37/BE',
'/ctr-search/trial/2006-006852-37/IT',
'/ctr-search/trial/2006-006852-37/FR',
'/ctr-search/trial/2006-006852-37/GB',
'/ctr-search/trial/2008-000664-16/IT',
'/ctr-search/trial/2005-005321-63/IT',
'/ctr-search/trial/2005-005321-63/results',
'/ctr-search/trial/2011-005023-40/GB',
'/ctr-search/trial/2010-022446-24/DE',
'/ctr-search/trial/2010-019710-24/IT',
'javascript:void(0)',
'&page=2',
'&page=3',
'&page=4',
'&page=5',
'&page=6',
'&page=7',
'&page=8',
'&page=9',
'&page=2',
'&page=19',
'https://servicedesk.ema.europa.eu',
'/disclaimer.html',
'http://www.ema.europa.eu',
'http://www.hma.eu'
``` | 2019/08/19 | [
"https://Stackoverflow.com/questions/57551049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11266219/"
] | As i said, you can achieve this by concatenating the required part of url to every result.
Try this code:
```
import requests
from bs4 import BeautifulSoup
page = requests.get('https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+leukemia&page=1')
soup = BeautifulSoup(page.text, 'html.parser')
links = ["https://www.clinicaltrialsregister.eu" + a['href'] for a in soup.find_all('a', href=True)]
``` | This script will traverse all pages of the search results and try to find relevant information.
It's necessary to add full url, not just `https://www.clinicaltrialsregister.eu`.
```
import requests
from bs4 import BeautifulSoup
base_url = 'https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+leukemia'
url = base_url + '&page=1'
soup = BeautifulSoup(requests.get(url).text, 'lxml')
page = 1
while True:
print('Page no.{}'.format(page))
print('-' * 160)
print()
for table in soup.select('table.result'):
print('EudraCT Number: ', end='')
for span in table.select('td:contains("EudraCT Number:")'):
print(span.get_text(strip=True).split(':')[1])
print('Full Title: ', end='')
for td in table.select('td:contains("Full Title:")'):
print(td.get_text(strip=True).split(':')[1])
print('Sponsor Name: ', end='')
for td in table.select('td:contains("Sponsor Name:")'):
print(td.get_text(strip=True).split(':')[1])
print('Trial protocol: ', end='')
for a in table.select('td:contains("Trial protocol:") a'):
print(a.get_text(strip=True), end=' ')
print()
print('Medical condition: ', end='')
for td in table.select('td:contains("Medical condition:")'):
print(td.get_text(strip=True).split(':')[1])
print('-' * 160)
next_page = soup.select_one('a:contains("Next»")')
if next_page:
soup = BeautifulSoup(requests.get(base_url + next_page['href']).text, 'lxml')
page += 1
else:
break
```
Prints:
```
Page no.1
----------------------------------------------------------------------------------------------------------------------------------------------------------------
EudraCT Number: 2014-000526-37
Full Title: An Investigator-Initiated Study To Evaluate Ara-C and Idarubicin in Combination with the Selective Inhibitor Of Nuclear Export (SINE)
Selinexor (KPT-330) in Patients with Relapsed Or Refractory A...
Sponsor Name: GSO Global Clinical Research B.V.
Trial protocol: DE
Medical condition: Patients with relapsed/refractory Acute Myeloid Leukemia (AML)
----------------------------------------------------------------------------------------------------------------------------------------------------------------
EudraCT Number: 2006-001777-19
Full Title: A Phase II multicenter study to assess the tolerability and efficacy of the addition of Bevacizumab to standard induction therapy in AML and
high risk MDS above 60 years.
Sponsor Name: HOVON foundation
Trial protocol: NL BE
Medical condition: Acute myeloid leukaemia (AML), AML FAB M0-M2 or M4-M7;
diagnosis with refractory anemia with excess of blasts (RAEB) or refractory anemia with excess of blasts in transformation (RAEB-T) with an IP...
----------------------------------------------------------------------------------------------------------------------------------------------------------------
EudraCT Number: 2007-000273-35
Full Title: A Phase II, Open-Label, Multi-centre, 2-part study to assess the Safety, Tolerability, and Efficacy of Tipifarnib Plus Bortezomib in the Treatment of Newly Diagnosed Acute Myeloid Leukemia AML ...
Sponsor Name: AZIENDA OSPEDALIERA DI BOLOGNA POLICLINICO S. ORSOLA M. MALPIGHI
Trial protocol: IT
Medical condition: Acute Myeloid Leukemia
----------------------------------------------------------------------------------------------------------------------------------------------------------------
...and so on.
``` | 4,054 |
11,300,737 | I cant import rdflib in python. error detailed:
```
Python 2.7.3 (default, Jun 27 2012, 23:48:21)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import rdflib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/rdflib/__init__.py", line 65, in <module>
from rdflib.term import URIRef, BNode, Literal, Variable
File "/usr/local/lib/python2.7/site-packages/rdflib/term.py", line 49, in <module>
from isodate import parse_time, parse_date, parse_datetime
ImportError: No module named isodate
```
I would be grateful if anybody can help.
Thanks. | 2012/07/02 | [
"https://Stackoverflow.com/questions/11300737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497041/"
] | If you actually install rdflib via `pip`, then its dependencies will come along with it (isodate included):
```
pip install -U rdflib
```
or
```
easy_install -U rdflib
```
Chances are you might have installed it directly from source, meaning you would have to take care of the deps yourself.
Information on installing pip if you dont have it already:
<http://www.pip-installer.org/en/latest/installing.html>
If you have easy\_install, you can do: `easy_install pip` | It seems there is a dependency to [isodate](http://pypi.python.org/pypi/isodate/), so try installing that via your favorite PyPI-Installer (*pip* oder \*easy\_install\*). | 4,055 |
5,646,322 | I've written a python cgi script to generate random numbers and add them together
than ask the user to give the answer.
But even user answer was correct, it gives him wrong. The answer will not be correct.
The problem is in the flow :
```
#!/usr/bin/python2.7
import cgi,sys,random
sys.stderr = sys.stdout
input_field = cgi.FieldStorage()
x = random.randrange(1,20)
y = random.randrange(1,20)
answer = x + y
print("Content-type: text/html\n")
print ("<center>")
if "input" in input_field:
if input_field["input"].value == answer:
print("Content-Type content=text/htm")
print "<br><br><b> Good :D </b"
else:
print "<br><br><b> Wrong :( </b><br><br>"
print "Your Answer :",input_field['input'].value
print "<br>","Correct Answer",answer
else:
print "<br><br>",x,"+",y,"<br><br>"
print("""
<form method=POST action="">
<TR>
<TH align=right>Answer:<TD>
<input type=text name=input>
<TR>
""")
print ("</center>")
```
e.g :
---
>
> 3 + 9
>
>
> Answer: [12 ]
>
>
>
---
>
> **Wrong :(**
>
>
> Your Answer : 12
> Correct Answer 17
>
>
>
Has anyone know what should I do to fix the flow? **It generate new numbers each time**
**Note : This is not a type error, it's *Logical* error** | 2011/04/13 | [
"https://Stackoverflow.com/questions/5646322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
javascript:
var all_product_ids = #{raw existing_ids.to_json};
var products_json = #{raw @filter.data.to_json};
``` | I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using [Gon](https://github.com/gazay/gon-sinatra). This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems. | 4,056 |
58,917,280 | I am trying to base64 encode using a custom character set in python3. Most of the examples I have seen in SO are related to Python 2, so I had to make some minor adjustments to the code. The issue that I am facing is that I am replacing the character `/` with `_`, but it is still printing with `/`. My code is: This is just an example, i am not trying to only base64 with urlsafe chars. `custom` could be anything with the correct length.
```py
import base64
data = 'some random? data'
print(base64.b64encode(data.encode()))
std_base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
custom = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
data = data.translate(str.maketrans(custom, std_base64chars)).encode()
print(base64.b64encode(data))
# Both prints
b'c29tZSByYW5kb20/IGRhdGE='
b'c29tZSByYW5kb20/IGRhdGE='
```
How can I get the translation to work so that occurrences of `/` are replaced correctly with `_`?
Edit
----
I should make it clear that I am not trying to do only one type of base64 encoding here like urlsafe, but any possible character set. This will be a function were a user can pass their own charset. I am looking for a character by character mapping, not string slicing.
Edit
----
Because there is some confusion around the clarity of my question, I am try to add more details.
I am trying to write a function that can take an arbitrary charset from a user, and then map them individually before base64 encoding. Most of the answers have been around manipulating `altchars` or string slice and replace, but that doesnt solve all the needs.
So for example, the itoa64 charset is:
`./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=` or unix crypt format is `./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`. The answers although correct, does not address these situations. | 2019/11/18 | [
"https://Stackoverflow.com/questions/58917280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7402287/"
] | If the only characters you want to switch are `+` and `\`, you can use [base64.urlsafe\_b64encode](https://docs.python.org/2/library/base64.html#base64.urlsafe_b64encode) to replace with `-` and `_` respectively.
```
>>> base64.urlsafe_b64encode(data.encode())
b'c29tZSByYW5kb20_IGRhdGE='
```
Alternatively, you can replace those characters with characters of your own choice using the optional argument of [base64.b64encode](https://docs.python.org/2/library/base64.html#base64.b64encode):
```
>>> base64.b64encode(data.encode(), '*&'.encode())
b'c29tZSByYW5kb20&IGRhdGE='
```
If you need to use an entirely new alphabet, you can do
```
import base64
data = 'some random? data'
print(base64.b64encode(data.encode()))
std_base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
custom = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
x = base64.b64encode(data.encode())
print(bytes(str(x)[2:-1].translate(str(x)[2:-1].maketrans(std_base64chars, custom)), 'utf-8'))
```
Which outputs:
```
b'c29tZSByYW5kb20/IGRhdGE='
b'C29TzsbYyw5KB20_igrHDge='
``` | Shouldn't this work:
```
import base64
data = 'some random? data'
custom = b"-_"
rslt = base64.b64encode(data)
print(rslt)
rslt = base64.b64encode(data, altchars=custom)
print(rslt)
```
I get following output:
```
c29tZSByYW5kb20/IGRhdGE=
c29tZSByYW5kb20_IGRhdGE=
```
or if you insist, that custom contains:
```
custom = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
```
then use:
```
rslt = base64.b64encode(data, altchars=custom[-2:])
``` | 4,066 |
65,335,763 | Good day I am using FastAPI and I want to render the database contents on index.html - however I get the following error:
```
INFO: 127.0.0.1:55139 - "GET /?skip=0&limit=100 HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 394, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/fastapi/applications.py", line 190, in __call__
await super().__call__(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/applications.py", line 111, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/middleware/cors.py", line 78, in __call__
await self.app(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/fastapi/routing.py", line 188, in app
raw_response = await run_endpoint_function(
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/fastapi/routing.py", line 137, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/Users/barnaby/.local/share/virtualenvs/fastapi-example-6xjq_vv2/lib/python3.9/site-packages/starlette/concurrency.py", line 34, in run_in_threadpool
return await loop.run_in_executor(None, func, *args)
File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/concurrent/futures/thread.py", line 52, in run
result = self.fn(*self.args, **self.kwargs)
File "./sql_app/main.py", line 51, in read_notes
"title": title,
NameError: name 'title' is not defined
```
Main.py
```
from fastapi import FastAPI
from typing import List, Dict
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from fastapi.templating import Jinja2Templates
from . import crud, models, schemas
from .database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
templates = Jinja2Templates(directory="templates")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# #original function
# @app.get("/notes", response_model=List[schemas.Note])
# def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
# notes = crud.get_notes(db=db, skip=skip, limit=limit)
# print(notes)
# return notes
@app.get("/", response_class=HTMLResponse)
def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
notes = crud.get_notes(db=db, skip=skip, limit=limit)
print(notes)
return templates.TemplateResponse("index.html",{
"request": request,
"id": id,
"title": title,
"description": description
})
@app.post("/notes", response_model=schemas.Note, status_code=201)
def create_note(note: schemas.NoteCreate, db: Session = Depends(get_db)):
return crud.create_note(db=db, note=note)
@app.get("/notes/{note_id}", response_model=schemas.Note)
def read_user(note_id: int, db: Session = Depends(get_db)):
db_note = crud.get_note(db=db, note_id=note_id)
if db_note is None:
raise HTTPException(status_code=404, detail="Note not found")
return db_note
@app.delete("/notes/{note_id}", status_code=204)
async def delete_note(note_id: int, db: Session = Depends(get_db)):
return crud.delete_note(db=db, note_id=note_id)
@app.put("/notes/{note_id}", status_code=200)
async def put_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
db_note = schemas.Note(id = note_id, title= note.title, description=note.description)
crud.update_note(db=db, note=db_note)
@app.patch("/notes/{note_id}", status_code=200)
async def patch_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
print(note_id)
print(note.title)
print(note.description)
db_note = schemas.Note(id = note_id, title= note.title, description=note.description)
crud.update_note(db=db, note=db_note)
if __name__ == '__main__':
uvicorn.run("main:app", host="127.0.0.1", port=8000)
```
crud.py
```
from sqlalchemy.orm import Session
from . import models, schemas
def get_note(db: Session, note_id: int):
return db.query(models.Note).filter(models.Note.id == note_id).first()
def delete_note(db: Session, note_id: int):
db_note = db.query(models.Note).filter(models.Note.id == note_id).first()
db.delete(db_note)
db.commit()
return {}
def get_notes(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.Note).offset(skip).limit(limit).all()
def create_note(db: Session, note: schemas.NoteCreate):
db_note = models.Note(title=note.title, description=note.description)
db.add(db_note)
db.commit()
db.refresh(db_note)
return db_note
def update_note(db: Session, note: schemas.Note):
db_note = db.query(models.Note).filter(models.Note.id == note.id).first()
db_note.title = note.title
db_note.description = note.description
db.commit()
db.refresh(db_note)
return db_note
```
schemas.py
```
class NoteBase(BaseModel):
title: str
description: str
class NoteCreate(NoteBase):
pass
class Note(NoteBase):
id: int
class Config:
orm_mode = True
```
models.py
```
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from .database import Base
class Note(Base):
__tablename__ = "notes"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=True, default="new")
description = Column(String, nullable=True, default="new")
```
index.html
```
{% extends 'layout.html' %} {% include 'header.html' %} {% block title %} Home {% endblock %} {% block body %}
<div class="container">
<div class="row">
<div class="col md-12">
<div class="jumbotron">
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
{% for note in notes%}
<td>{{notes.id}}</td>
<td>{{notes.title}}</td>
<td>{{notes.description}}</td>
</tr>
{% endfor %}
<tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
```
Is my schema/models set up incorrectly?
looking at this end point-- <http://127.0.0.1:8000/notes> i get the following displayed in index.html. However this is in list format.But somehow I am unable to render it via the HTML template.
```
[ { "title": "title 3", "description": "title 3 description", "id": 3 }, { "title": "title 1 updated", "description": "string", "id": 1 }, { "title": "Title updated 2", "description": "description updated2", "id": 2 }, { "title": "Note 4", "description": "Note 4 description", "id": 4 } ]
```
database.py
```
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:123456789@localhost/notes"
engine = create_engine (SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
``` | 2020/12/17 | [
"https://Stackoverflow.com/questions/65335763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372626/"
] | BMC does not use OS services. BMC is completely OS independent and it may monitor and control hardware even when no OS is running or installed. BMC power line is independent on the host power and BMC is powered even when the host is powered off. It is ensured by power source design. BMC can control the host power supply. BMC usually has a direct hardware link to the power supply. BMC sends to power-off command directly to the power supply and not to the host OS. | A general design is:
BMC connects to a CPLD, which controls the power sequence. When power off is needed, BMC will trigger the CPLD so that it is the same as if someone pushes the front panel power button. | 4,067 |
59,087,639 | I have the following code:
```
for i in range (0,20,1):
df = pd.read_excel(url, sheet_name=i,sep='\s*,\s*')
print('sample:',i+1)
df1 = df.loc[0:50] #initial push
ma=df1['Latest: Potential (V)'].values.tolist()
max_force_initial_push=max(ma)
```
And when I run it, I get the following `error`:
```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-e56ce0a5f5fd> in <module>
45 ma=df1['Latest: Potential (V)'].values.tolist()
46 print ('ma: ', ma)
---> 47 max_force_initial_push=max(ma)
TypeError: 'list' object is not callable
```
When I `print ma`, I get the following Result:
`ma: [3.25836181641, 3.26812744141, 3.22906494141, 3.18023681641, 3.10729980469, 3.08776855469]`
Can someone help me to troubleshoot the problem? I don't really understand what is going on
Thanks!
Any Help Will Be Appreciated! | 2019/11/28 | [
"https://Stackoverflow.com/questions/59087639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12007010/"
] | This happens because the Promise object holds its state internally .
So when you call `.then` on a Promise object it will either :
* Await for resolution, and then fire the callback
* If the promise is already resolved, the callback will execute immediately | >
> So does it mean that the compiler does sth to assist here? for example, the compiler merge the then clause right after the promise1 statement just like example 1?
>
>
>
No, there is much less magic happening than you think. `new Promise` returns a promise object. A promise object has a `.then` method. You use this method to tell the promise that *once* it is resolved, call the passed function. The promise object holds onto this callback.
You can think of this as registering an event handler. Once the "resolve event" happens, the function is executed.
Of the course the promises itself knows whether or not it is resolved. So if `.then` is called on a resolved promise, it can immediately schedule the invocation of the callback.
Here is a very poor man's implementation of a promise (doesn't handle rejects and other things), which might give you a better idea of how promises work. Note that I use `setTimeout` here to simulate how promises always execute callbacks on the next tick of the [event loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop), but in reality JavaScript uses some other internal API:
```js
class Promise {
constructor(handler) {
this._callbacks = [];
// Execute the passed handler, passing the "resolve" function
handler(value => {
// Mark the promise as resolved
this._resolved = true;
// Remember the value
this._value = value;
// Execute all registered callbacks
this._callbacks.forEach(cb => cb(value));
});
}
then(handler) {
let _resolve;
const promise = new Promise(resolve => _resolve = resolve);
const callback = value => {
setTimeout(
() => _resolve(handler(value)),
0
);
};
// Is the promise already resolved?
if (this._resolved) {
// Immediately schedule invocation of handler with the remembered value
callback(this._value);
} else {
// Remember callback for future invocation
this._callbacks.push(callback);
}
return promise;
}
}
const promise = new Promise(resolve => {
console.log('inside Promise');
resolve(42);
});
console.log('in between');
promise.then(v => {
console.log('inside then', v);
})
promise.then(v => {
console.log('inside another then', v);
return 21;
})
.then(v => {
console.log('.then returns a new promise', v);
});
``` | 4,068 |
69,614,180 | Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set.
My current set:
```
api = {
"9/30/2018": {
"Capital Expenditure": "-13313000",
"End Cash Position": "25913000",
"Financing Cash Flow": "-87876000",
"Free Cash Flow": "64121000",
"Income Tax Paid Supplemental Data": "10417000",
"Interest Paid Supplemental Data": "3022000",
"Investing Cash Flow": "16066000",
"Issuance of Capital Stock": "669000",
"Issuance of Debt": "6969000",
"Operating Cash Flow": "77434000",
"Repayment of Debt": "-6500000",
"Repurchase of Capital Stock": "-72738000"
},
"9/30/2019": {
"Capital Expenditure": "-10495000",
"End Cash Position": "50224000",
"Financing Cash Flow": "-90976000",
"Free Cash Flow": "58896000",
"Income Tax Paid Supplemental Data": "15263000",
"Interest Paid Supplemental Data": "3423000",
"Investing Cash Flow": "45896000",
"Issuance of Capital Stock": "781000",
"Issuance of Debt": "6963000",
"Operating Cash Flow": "69391000",
"Repayment of Debt": "-8805000",
"Repurchase of Capital Stock": "-66897000"
},
"9/30/2020": {
"Capital Expenditure": "-7309000",
"End Cash Position": "39789000",
"Financing Cash Flow": "-86820000",
"Free Cash Flow": "73365000",
"Income Tax Paid Supplemental Data": "9501000",
"Interest Paid Supplemental Data": "3002000",
"Investing Cash Flow": "-4289000",
"Issuance of Capital Stock": "880000",
"Issuance of Debt": "16091000",
"Operating Cash Flow": "80674000",
"Repayment of Debt": "-12629000",
"Repurchase of Capital Stock": "-72358000"
},
"ttm": {
"Capital Expenditure": "-9646000",
"End Cash Position": "35276000",
"Financing Cash Flow": "-94328000",
"Free Cash Flow": "94768000",
"Income Tax Paid Supplemental Data": "19627000",
"Interest Paid Supplemental Data": "2597000",
"Investing Cash Flow": "-9849000",
"Issuance of Capital Stock": "1011000",
"Issuance of Debt": "22370000",
"Operating Cash Flow": "104414000",
"Repayment of Debt": "-7500000",
"Repurchase of Capital Stock": "-83410000"
}
}
```
My desired outcome would be:
s\_19\_30\_2018 = ["Capital Expenditure": "-13313000"...]
s\_19\_30\_2019 = ["Capital Expenditure": "-10495000"...]
s\_19\_30\_2020 = ["Capital Expenditure": "-7309000"...]
s\_ttm = ["Capital Expenditure": "-9646000"...]
This is so that I can access the data with more ease and add them to a sql database.
I have tried by doing s\_19\_30\_2018 = api['19/30/2018'] but I keep getting 'type error string indices must be integers '.
Any help would be appreciated in python >.< | 2021/10/18 | [
"https://Stackoverflow.com/questions/69614180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13970042/"
] | Given this structure:
```
api = {
"9/30/2018": {
"Capital Expenditure": "-13313000",
"End Cash Position": "25913000",
},
"9/30/2019": {
....
```
to get a list of key,values for the first entry can run:
```
for key,value in api["9/30/2018"]:
l = [key, value]
print(f" {key}, {value}")
# prints "Capital Expenditure -133313000"
```
to go through all the items
```
#get the keys
ks = api.keys()
for k in ks:
for key, value, in api[k]:
print(f" {key}, {value}")
# prints "Capital Expenditure -133313000"] ...
``` | Your dictionary keys are string so use quotes when you access them like
```
s_19_30_2018 = api["9/30/2018"]
```
also I don't see any key such as "19\_30\_2018" in your dictionary. | 4,069 |
66,670,681 | I am working on a desktop application that I made by using the python language and some open-source library. When I convert that .py file to a .exe file using Pyinstaller it runs on window 10 but shows an error on window 7. Is there any way to make one .exe for all window versions 7/8/10?
* List item | 2021/03/17 | [
"https://Stackoverflow.com/questions/66670681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10975941/"
] | You do not need to "import" the functions, you would need just to create a `class` that keeps all your needed functions, and import that class.
I am supposing you use an IDE, you could go to your IDE and create a simple `class`.
e.g:
```java
public class Utils
{
public static int doSmth(/* Your parameters here */)
{
// Your code here
}
public static void yetAnotherFunction(/* Your parameters here */)
{
// Your code here
}
}
```
The most important keyword here is `static`, to understand it I suggest you check my answer here: [when to decide use static functions at java](https://stackoverflow.com/questions/66652425/when-to-decide-use-static-functions-at-java/66652634#66652634)
Then you import this class to any of your other classes and call the `static` functions, without creating an Object.
```java
import package.Utils;
public class MainClass
{
public static void main(String[] args)
{
Utils.doSmth();
}
}
``` | You can add at the beginning:
import
like-
```java
import utils;
```
Assuming it is in the same package as the current class
Else it should be:
```java
import <package name>.<class name>
``` | 4,074 |
19,162,812 | I have a python data structure like this
```
dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']},
{'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']},
{'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']},
{'plat': 'centOs', 'val':['', '', '', '', '', '202', '', '']},
{'plat': 'ubuntu', 'val':['', 'KL', '1', '', '', '', '', '9i0']}]
^ ^
| |
\ /
Delete these
```
I am trying to delete the position in the list `'val'` where the values in the same column in each list are empty. For example, position 0 and 3 in the list(dl). I am trying to get an output like this:
```
Output= [{'plat': 'unix', 'val':['', '1ju', '', '202', '', '']},
{'plat': 'Ios', 'val':['', '', 'Ty', '', 'Jk', '']},
{'plat': 'NT', 'val':['', 1, '' , '202', '', '']},
{'plat': 'centOs', 'val':['', '', '', '202', '', '']},
{'plat': 'ubuntu', 'val':['KL', '1', '', '', '', '9i0']}]
``` | 2013/10/03 | [
"https://Stackoverflow.com/questions/19162812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2843234/"
] | ```
dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']},
{'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']},
{'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']},
{'plat': 'centOs', 'val':['', '', '', '', '', '202', '', '']},
{'plat': 'ubuntu', 'val':['', 'KL','1', '', '', '', '', '9i0']}]
def empty_indices(lst):
return {i for i,v in enumerate(lst) if not v}
# Need to special-case the first one to initialize the set of "emtpy" indices.
remove_idx = empty_indices(dl[0]['val'])
# Here we do the first one twice. We could use itertools.islice but it's
# probably not worth the miniscule speedup.
for item in dl:
remove_idx &= empty_indices(item['val'])
for item in dl:
item['val'] = [k for i,k in enumerate(item['val']) if i not in remove_idx]
# print the results.
import pprint
pprint.pprint(dl)
``` | ```
from itertools import izip
from operator import itemgetter
# create an iterator over columns
columns = izip(*(d['val'] for d in dl))
# make function keeps non-empty columns
keepfunc = itemgetter(*(i for i, c in enumerate(columns) if any(c)))
# apply function to each list
for d in dl:
d['val'] = list(keepfunc(d['val']))
``` | 4,076 |
40,701,398 | I am trying to figure out how to take the following for loop that splits an array based on the index of the lowest value in the row and use vectorization. I've looked at this [link](https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/ch04.html) and have been trying to use the numpy.where function but currently unsuccessful.
For example if an array has *n* columns, then all the rows where *col[0]* has the lowest value are put in one array, all the rows where *col[1]* are put in another, etc.
Here's the code using a for loop.
```
import numpy
a = numpy.array([[ 0. 1. 3.]
[ 0. 1. 3.]
[ 0. 1. 3.]
[ 1. 0. 2.]
[ 1. 0. 2.]
[ 1. 0. 2.]
[ 3. 1. 0.]
[ 3. 1. 0.]
[ 3. 1. 0.]])
result_0 = []
result_1 = []
result_2 = []
for value in a:
if value[0] <= value[1] and value[0] <= value[2]:
result_0.append(value)
elif value[1] <= value[0] and value[1] <= value[2]:
result_1.append(value)
else:
result_2.append(value)
print(result_0)
>>[array([ 0. 1. 3.]), array([ 0. 1. 3.]), array([ 0. 1. 3.])]
print(result_1)
>>[array([ 1. 0. 2.]), array([ 1. 0. 2.]), array([ 1. 0. 2.])]
print(result_2)
>>[array([ 3. 1. 0.]), array([ 3. 1. 0.]), array([ 3. 1. 0.])]
``` | 2016/11/20 | [
"https://Stackoverflow.com/questions/40701398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5025845/"
] | First, use `argsort` to see where the lowest value in each row is:
```
>>> a.argsort(axis=1)
array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[1, 0, 2],
[1, 0, 2],
[1, 0, 2],
[2, 1, 0],
[2, 1, 0],
[2, 1, 0]])
```
Note that wherever a row has `0`, that is the smallest column in that row.
Now you can build the results:
```
>>> sortidx = a.argsort(axis=1)
>>> [a[sortidx[:,i] == 0] for i in range(a.shape[1])]
[array([[ 0., 1., 3.],
[ 0., 1., 3.],
[ 0., 1., 3.]]),
array([[ 1., 0., 2.],
[ 1., 0., 2.],
[ 1., 0., 2.]]),
array([[ 3., 1., 0.],
[ 3., 1., 0.],
[ 3., 1., 0.]])]
```
So it is done with only a single loop over the columns, which will give a huge speedup if the number of rows is much larger than the number of columns. | This is not the best solution since it relies on simple python loops and is not very efficient when you start dealing with large data sets but it should get you started.
The point is to create an array of "buckets" which store the data based on the depth of the lengthiest element. Then enumerate each element in `values`, selecting the smallest one and saving its offset which is subsequently appended to the correct results "bucket", for each `a`. Finally we print this out in the last loop.
**Solution using loops**:
```
import numpy
import pprint
# random data set
a = numpy.array([[0, 1, 3],
[0, 1, 3],
[0, 1, 3],
[1, 0, 2],
[1, 0, 2],
[1, 0, 2],
[3, 1, 0],
[3, 1, 0],
[3, 1, 0]])
# create a list of results as big as the depth of elements in an entry
results = list()
for l in range(max(len(i) for i in a)):
results.append(list())
# don't do the following because all the references to the lists will be the same and you get dups:
# results = [[]]*max(len(i) for i in a)
for value in a:
res_offset, _val = min(enumerate(value), key=lambda x: x[1]) # get the offset and min value
results[res_offset].append(value) # store the original Array obj in the correct "bucket"
# print for visualization
for c, r in enumerate(results):
print("result_%s: %s" % (c, r))
```
Outputs:
>
> result\_0: [array([0, 1, 3]), array([0, 1, 3]), array([0, 1, 3])]
>
> result\_1: [array([1, 0, 2]), array([1, 0, 2]), array([1, 0, 2])]
>
> result\_2: [array([3, 1, 0]), array([3, 1, 0]), array([3, 1, 0])]
>
>
> | 4,081 |
66,776,644 | My freelance client is giving FTP access to the shared hosting, I am new to web development and can't figure out how to deploy the flask app to cgi-bin folder, please help me understand how this works?
```
.htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files
RewriteRule ^(.*)$ /public_html/app.cgi/$1 [L]
app.py file
import sys, subprocess
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'flask'])
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, world"
if __name__ == '__main__':
app.run()
app.cgi file
#!/usr/bin/python3
from wsgiref.handlers import CGIHandler
from app import app
CGIHandler().run(app)
``` | 2021/03/24 | [
"https://Stackoverflow.com/questions/66776644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13993581/"
] | First create a python script which will contain:
```py
import sys
import subprocess
# implement pip as a subprocess:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'flask'])
```
And then follow the instructions given by **Hostgator**.
Please mark it as an answer if it is helpful!
[](https://stackoverflow.com/users/15467414/rajdeep) | Sorry but the Flask hosting can't be done within Shared-Hosting.
You need **DigitalOcean** or **Heroku** or **PythonAnywhere**(easiest) Hosting to deploy a **Flask**/**Django** Website. | 4,083 |
48,044,680 | I have a problem with python that is I want to generate a multidict like the one below, using a for loop. Numbers are generated randomly and if the two elements are the same, the value if 0.
```
arcs, capacity = multidict({
(0, 0): 0,
(0, 1): 80,
(0, 2): 11,
(1, 0): 15,
(1, 1): 0,
(1, 2): 120
(2, 0): 103,
(2, 1): 3,
(2, 2): 0 })
```
So far I coded this one:
```
arcs = {}
for i in range(N):
for j in range(N):
arcs[i,j]=(random.randint(1,101))
```
But it's nothing like the one I need.
Can anyone help me on how to code the for loop for this problem?
Many many thanks in advance. | 2017/12/31 | [
"https://Stackoverflow.com/questions/48044680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Unit tests call functions that they test. You want to know if a function F called by a unit test can eventually invoke malloc (or new or ...). Seems like what you really want to do is build a call graph for your entire system, and then ask for the critical functions F whether F can reach malloc etc. in the call graph. This is rather easy to compute once you have the call graph.
Getting the call graph is not so easy. Discovering that module A calls module B directly is "technically easy" if you have a real language front end that does name resolution. Finding out what A calls indirectly isn't easy; you need a (function pointer) points-to analysis and those are hard. And, of course, you have decide if you are going to dive into library (e.g., std::) routines or not.
Your call graph needs needs to be conservative (so you don't miss potential calls) and reasonably precise (so you don't drown in false positives) in the face of function pointers and method calls.
This Doxygen support claims to build call graphs: <http://clang.llvm.org/doxygen/CallGraph_8cpp.html> I don't know if it handles indirect/methods calls or how precise it is; I'm not very familiar with it and the documentation seems thin. Doxygen in the past did not have reputation for handling indirection well or being precise, but past versions weren't based on Clang. There is some further discussion of this applied on small scale at <http://stackoverflow.com/questions/5373714/generate-calling-graph-for-c-code>
Your question is tagged c/c++ but seems to be about C++. For C, our [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html) with its generic flow analysis and call graph generation support, coupled with DMS's [C Front End](http://www.semanticdesigns.com/Products/FrontEnds/CFrontEnd.html?Home=CTools), has been used to [analyze C systems of some 16 million lines/50,000 functions with indirect calls](http://www.semanticdesigns.com/Products/DMS/FlowAnalysis.html#CallGraphAnalysis) to produce conservatively correct call graphs.
We have not specifically tried to build C++ call graphs for large systems, but the same DMS generic flow analysis and call graph generation would be "technically straightforward" used with DMS's [C++ Front End](https://www.semanticdesigns.com/Products/FrontEnds/CppFrontEnd.html). When building a static analysis that operates correctly and at scale, nothing is trivial to do. | If you're using libraries which invoke malloc, then you might want to take a look at the [Joint Strike Fighter C++ Coding Standards](http://www.stroustrup.com/JSF-AV-rules.pdf). It's a coding style aimed towards mission critical software. One suggestion would be to write your own allocator(s). Another suggestion is to use something like `jemalloc` which has statistics, but is much more unpredictable since it is geared towards performance.
---
What you want is a mocking library with spy capabilities. How this works for each framework is going to vary, but here is an example using Google:
```
static std::function<void*(size_t)> malloc_bridge;
struct malloc_mock {
malloc_mock() { malloc_bridge = std::bind(&malloc_mock::mock_, this, _1); }
MOCK_METHOD1(mock_, void*(size_t));
}
void* malloc_cheat(size_t size) {
return malloc_bridge(size);
}
#define malloc malloc_cheat
struct fixture {
void f() { malloc(...); }
};
struct CustomTest : ::testing::test {
malloc_mock mock_;
};
TEST_F(CustomTest, ShouldMallocXBytes) {
EXPECT_CALL(mock_, mock_(X))
.WillOnce(::testing::Return(static_cast<void*>(0)));
Fixture fix;
fix.f();
}
#undef malloc
```
**WARNING:** Code hasn't been touched by compiler hands. But you get the idea. | 4,084 |
7,076,254 | I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g.
```
x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...}
```
Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a particular configuration of lists and dictionaries? e.g.
```
{'a':[1.056,2.346,[1.111,10.000],...}
```
I'm thinking something like
`pformat(x,round=3)` or maybe
```
pformat(x,conversions={'float':lambda x: "%.3g" % x})
```
except I don't think they have this kind of functionality. Permanently rounding the underlying data is of course not an option. | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/768552/"
] | This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone.
```
import collections
import numbers
def pformat(thing, formatfunc):
if isinstance(thing, dict):
return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems())
if isinstance(thing, collections.Container):
return type(thing)(pformat(value, formatfunc) for value in thing)
if isinstance(thing, numbers.Number):
return formatfunc(thing)
return thing
def formatfloat(thing):
return "%.3g" % float(thing)
x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}
print pformat(x, formatfloat)
```
If you want to try and convert everything to a float, you can do
```
try:
return formatfunc(thing)
except:
return thing
```
instead of the last three lines of the function. | ```
>>> b = []
>>> x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]]}
>>> for i in x.get('a'):
if type(i) == type([]):
for y in i:
print("%0.3f"%(float(y)))
else:
print("%0.3f"%(float(i)))
1.056
2.346
1.111
10.000
```
The problem Here is we don't have flatten method in python, since I know it is only 2 level list nesting I have used `for loop`. | 4,087 |
49,883,687 | How to close a file if it is already open?
```
import xlwings as xw
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
```
Using try:except: but need a way to close the file so it can be opened, or find the file and work with it?
I get this error if it's already open:
```
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
Traceback (most recent call last):
File "<ipython-input-34-85b6fd35627b>", line 1, in <module>
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
File "C:\Users\ReDimLearning\AppData\Local\Continuum\anaconda2\lib\site-packages\xlwings\main.py", line 480, in __init__
impl = app.books.open(fullname).impl
File "C:\Users\ReDimLearning\AppData\Local\Continuum\anaconda2\lib\site-packages\xlwings\main.py", line 2751, in open
"Cannot open two workbooks named '%s', even if they are saved in different locations." % name
ValueError: Cannot open two workbooks named 'metrics - auto.xlsx', even if they are saved in different locations.
``` | 2018/04/17 | [
"https://Stackoverflow.com/questions/49883687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3664733/"
] | You can check the workbook collection with
```
import xlwings as xw
xw.books
```
and check if your fullname is already open using something like:
```
if myworkbook in [i.fullname for i in xw.books]:
...
``` | I have no experience with the xlwings package, but looking at the [source code](https://github.com/ZoomerAnalytics/xlwings/blob/master/xlwings/main.py) for `Book.__init__`, it looks like it automatically looks for any instances of the work book that are already open. If there is only one, then it returns it. If there is more than one instance of the work book open, it will raise an error. If there aren't already any open instances, then it will "connect" to it. So, it looks like you don't have to worry about closing the file.
This lines up with the [documentation](http://docs.xlwings.org/en/stable/connect_to_workbook.html#python-to-excel) which says:
>
> The easiest way to connect to a book is offered by xw.Book: it looks
> for the book in all app instances and returns an error, should the
> same book be open in multiple instances.
>
>
>
However, after connecting to a workbook, if you really want to close it, there is a [Book.close](http://docs.xlwings.org/en/stable/api.html#xlwings.Book.close) method which:
>
> Closes the book without saving it.
>
>
> | 4,090 |
35,692,537 | I want to scan some websites and would like to get all the java script files names and content.I tried python requests with BeautifulSoup but wasn't able to get the scripts details and contents.am I missing something ?
I have been trying lot of methods to find but I felt like stumbling in the dark.
This is the code I am trying
```
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.marunadanmalayali.com/")
soup = BeautifulSoup(r.content)
``` | 2016/02/29 | [
"https://Stackoverflow.com/questions/35692537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5478079/"
] | You can get all the linked JavaScript code use the below code:
```
l = [i.get('src') for i in soup.find_all('script') if i.get('src')]
```
* `soup.find_all('script')` returns a list of all the `<script>` tags in the page.
* A [*list comprehension*](https://stackoverflow.com/questions/34835951/) is used here to loop over all the elements in the list which returned by `soup.find_all('script')`.
* `i` is a *dict like* object, use `.get('src')` to check if it has `src` attribute. If not, ignore it. Otherwise, put it into a list (which's called `l` in the example).
The output, in this case looks like below:
```
['http://adserver.adtech.de/addyn/3.0/1602/5506153/0/6490/ADTECH;loc=700;target=_blank;grp=[group]',
'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js',
'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js',
'http://js.genieessp.com/t/057/794/a1057794.js',
'http://ib.adnxs.com/ttj?id=5620689&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]',
'http://ib.adnxs.com/ttj?id=5531763',
'http://advs.adgorithms.com/ttj?id=3279193&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]',
'http://xp2.zedo.com/jsc/xp2/fo.js',
'http://www.marunadanmalayali.com/js/mnmads.js',
'http://www.marunadanmalayali.com/js/jquery-2.1.0.min.js',
'http://www.marunadanmalayali.com/js/jquery.hoverIntent.minified.js',
'http://www.marunadanmalayali.com/js/jquery.dcmegamenu.1.3.3.js',
'http://www.marunadanmalayali.com/js/jquery.cookie.js',
'http://www.marunadanmalayali.com/js/swanalekha-ml.js',
'http://www.marunadanmalayali.com/js/marunadan.js?r=1875',
'http://www.marunadanmalayali.com/js/taboola_home.js',
'http://d8.zedo.com/jsc/d8/fo.js']
```
---
My code missed some links because they're not in the HTML source actually.
You can see them in the console:
[](https://i.stack.imgur.com/qyvEG.png)
But they're not in the source:
[](https://i.stack.imgur.com/Puvhe.png)
Usually, that's because these links were generated by JavaScript. And the `requests` module doesn't run any JavaScript in the page like *a real browser* - it only send a request to get the HTML source.
If you also need them, you have to use another module to run the JavaScript in that page, and you can see these links then. For that, I'd suggest use [**selenium**](http://selenium-python.readthedocs.org/) - which runs *a real browser* so it can runs JavaScript in the page.
For example (make sure that you have already installed selenium and a web driver for it):
```
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome() # use Chrome driver for example
driver.get('http://www.marunadanmalayali.com/')
soup = BeautifulSoup(driver.page_source, "html.parser")
l = [i.get('src') for i in soup.find_all('script') if i.get('src')]
__import__('pprint').pprint(l)
``` | You can use a select with `script[src]` which will only find script tags with a src, you don't need to call .get multiple times:
```
import requests
from bs4 import BeautifulSoup
r = requests.get("http://www.marunadanmalayali.com/")
soup = BeautifulSoup(r.content)
src = [sc["src"] for sc in soup.select("script[src]")]
```
You can also specify `src=True` with find\_all to do the same:
```
src = [sc["src"] for sc in soup.find_all("script",src=True)]
```
Which will both give you the same output:
```
['http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js', 'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js', 'http://js.genieessp.com/t/052/954/a1052954.js', '//s3-ap-northeast-1.amazonaws.com/tms-t/marunadanmalayali-7219.js', 'http://advs.adgorithms.com/ttj?id=3279193&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]', 'http://www.marunadanmalayali.com/js/mnmcombined1.min.js', 'http://www.marunadanmalayali.com/js/mnmcombined2.min.js']
```
Also if you use selenium, you can use it with [*PhantomJs*](http://phantomjs.org/) for headless browsing, you don't need beautufulSoup at all if you use selenium, you can use the same css selector directly in selenium:
```
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get('http://www.marunadanmalayali.com/')
src = [sc.get_attribute("src") for sc in driver.find_elements_by_css_selector("script[src]")]
print(src)
```
Which gives you all the links:
```
u'https://pixel.yabidos.com/fltiu.js?qid=836373f5137373f5131353&cid=511&p=165&s=http%3a%2f%2fwww.marunadanmalayali.com%2f&x=admeta&nci=&adtg=96331&nai=', u'http://gum.criteo.com/sync?c=72&r=2&j=TRC.getRTUS', u'http://b.scorecardresearch.com/beacon.js', u'http://cdn.taboola.com/libtrc/impl.201-1-RELEASE.js', u'http://p165.atemda.com/JSAdservingMP.ashx?pc=1&pbId=165&clk=&exm=&jsv=1.84&tsv=2.26&cts=1459160775430&arp=0&fl=0&vitp=0&vit=&jscb=&url=&fp=0;400;300;20&oid=&exr=&mraid=&apid=&apbndl=&mpp=0&uid=&cb=54613943&pId0=64056124&rank0=1&gid0=64056124:1c59ac&pp0=&clk0=[External%20click-tracking%20goes%20here%20(NOT%20URL-encoded)]&rpos0=0&ecpm0=&ntv0=&ntl0=&adsid0=', u'http://cdn.taboola.com/libtrc/marunadanaalayali-network/loader.js', u'http://s.atemda.com/Admeta.js', u'http://www.google-analytics.com/analytics.js', u'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js', u'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js', u'http://js.genieessp.com/t/052/954/a1052954.js', u'http://s3-ap-northeast-1.amazonaws.com/tms-t/marunadanmalayali-7219.js', u'http://d8.zedo.com/jsc/d8/fo.js', u'http://z1.zedo.com/asw/fm/1185/7219/9/fm.js?c=7219&a=0&f=&n=1185&r=1&d=9&adm=&q=&$=&s=1936&l=%5BINSERT_CLICK_TRACKER_MACRO%5D&ct=&z=0.025054786819964647&tt=0&tz=0&pu=http%3A%2F%2Fwww.marunadanmalayali.com%2F&ru=&pi=1459160768626&ce=UTF-8&zpu=www.marunadanmalayali.com____1_&tpu=', u'http://cas.criteo.com/delivery/ajs.php?zoneid=308686&nodis=1&cb=38688817829&exclude=undefined&charset=UTF-8&loc=http%3A//www.marunadanmalayali.com/', u'http://ads.pubmatic.com/AdServer/js/showad.js', u'http://showads.pubmatic.com/AdServer/AdServerServlet?pubId=135167&siteId=135548&adId=600924&kadwidth=300&kadheight=250&SAVersion=2&js=1&kdntuid=1&pageURL=http%3A%2F%2Fwww.marunadanmalayali.com%2F&inIframe=0&kadpageurl=marunadanmalayali.com&operId=3&kltstamp=2016-3-28%2011%3A26%3A13&timezone=1&screenResolution=1024x768&ranreq=0.8869257988408208&pmUniAdId=0&adVisibility=2&adPosition=999x664', u'http://d8.zedo.com/jsc/d8/fo.js', u'http://z1.zedo.com/asw/fm/1185/7213/9/fm.js?c=7213&a=0&f=&n=1185&r=1&d=9&adm=&q=&$=&s=1948&l=%5BINSERT_CLICK_TRACKER_MACRO%5D&ct=&z=0.08655649935826659&tt=0&tz=0&pu=http%3A%2F%2Fwww.marunadanmalayali.com%2F&ru=&pi=1459160768626&ce=UTF-8&zpu=www.marunadanmalayali.com____1_&tpu=', u'http://advs.adgorithms.com/ttj?id=3279193&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]', u'http://ib.adnxs.com/ttj?ttjb=1&bdc=1459160761&bdh=ZllBLkzcj2dGDVPeS0Sw_OTWjgQ.&tpuids=eyJ0cHVpZHMiOlt7InByb3ZpZGVyIjoiY3JpdGVvIiwidXNlcl9pZCI6Il9KRC1PUmhLX3hLczd1cUJhbjlwLU1KQ2VZbDQ2VVUxIn1dfQ==&view_iv=0&view_pos=664,2096&view_ws=400,300&view_vs=3&bdref=http%3A%2F%2Fwww.marunadanmalayali.com%2F&bdtop=true&bdifs=0&bstk=http%3A%2F%2Fwww.marunadanmalayali.com%2F&&id=3279193&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]', u'http://www.marunadanmalayali.com/js/mnmcombined1.min.js', u'http://www.marunadanmalayali.com/js/mnmcombined2.min.js', u'http://pixel.yabidos.com/iftfl.js?ver=1.4.2&qid=836373f5137373f5131353&cid=511&p=165&s=http%3a%2f%2fwww.marunadanmalayali.com%2f&x=admeta&adtg=96331&nci=&nai=&nsi=&cstm1=&cstm2=&cstm3=&kqt=&xc=&test=&od1=&od2=&co=0&tps=34&rnd=3m17uji8ftbf']
``` | 4,091 |
71,443,087 | i'm struggling to debug my python code with regex in PyCharm.
The idea:
I want to find any case of 'here we are',
which can go with or without 'attention',
and the word 'attention' can be separated by whitespace, dot, comma, exclamation mark.
I expect this expression should do the job
```
r'(attention.{0,2})?here we are'
```
Online services like <https://regex101.com/> and <https://pythex.org/> confirm my expression is correct – and i'm getting expected "attention! here we are"
However, if i run the below code in PyCharm I'm getting such (unexpected for me) result.
```
my_string_1 = 'attention! here we are!'
my_list = re.findall(r'(attention.{0,2})?here we are', my_string_1)
print(my_list)
>>> ['attention! ']
```
Could someone direct me to the reason why PyCharm's outcome is different? Thanks | 2022/03/11 | [
"https://Stackoverflow.com/questions/71443087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15769721/"
] | I would assume that you're using class components, so the solution I would provide is for that.
First step is to import ConnectedProps:
```
import { connect, ConnectedProps } from 'react-redux'
```
Next step is to define the objects that your state/reducer, so in a file that we can name `TsConnector.ts`, add something like:
```
interface UIState {
a: string,
b: string,
...your other props
}
interface State {
UI: UI,
...your other props
}
```
Then create your `mapState` and `mapDispatch` functions:
```
const mapState = (state: UIState ) => ({
UI: state.UI,
...your other props
})
const mapDispatch = {
... your dispatch action
}
```
And export:
```
export default tsconnector = connect(mapState, mapDispatch)
```
Then use this as you normally would an HOC component:
```
import { tsconnector } from '../components/TsConnector'
export var About =
tsconnector(mapStateToProps, mapDispatchToProps)(About_Class);
```
And that's it. | Have you tried `useDispatch` and `useSelector` in ts file to get redux state
```
import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector
``` | 4,092 |
3,878,195 | The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus. | 2010/10/07 | [
"https://Stackoverflow.com/questions/3878195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | You can look into [Twiggy](https://github.com/wearpants/twiggy), it's an early stage attempt to build a more pythonic alternative to the logging module. | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
from logging.config import dictConfig
logger = logging.getLogger(__name__)
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
"""
Initialize logging defaults for Project.
:param logfile_path: logfile used to the logfile
:type logfile_path: string
This function does:
- Assign INFO and DEBUG level to logger file handler and console handler
"""
dictConfig(DEFAULT_LOGGING)
default_formatter = logging.Formatter(
"[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
"%d/%m/%Y %H:%M:%S")
file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
file_handler.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(default_formatter)
console_handler.setFormatter(default_formatter)
logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(file_handler)
logging.root.addHandler(console_handler)
[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module
```
you can config logfile with console and file,I don't think desktop notication is a good idea,you can see the log information from console and logfiles | 4,093 |
64,913,140 | As per the [documentation](https://docs.python.org/3/reference/datamodel.html#object.__bool__), every class has a default `__bool__` that returns `true`.
Is there a way to "remove" this default behaviour so that it raises an error when used as bool (for instance in a expression like `if obj`?
And especially, is there a way to specify this with, for instance, mypy, so as to make static inspection aware of unwanted behaviours? | 2020/11/19 | [
"https://Stackoverflow.com/questions/64913140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444546/"
] | you can use Array map function on **option.selectedOption** too
just like:
```
{restaurant.map((option, marker) => (
<p key={marker.id}>
{option.selectedOption.map((optn, index) => (
<strong key={index}>
{optn.label + ', '}
</strong>
))}
</p>
))}
```
and show the label and value according to your requirement inside JSX | You should do that instead:
```
{restaurant.map((option, marker) => (
<p key={marker.id}>
<strong>
{option.selectedOption.reduce(labels, label, index => labels += `${index > 0 ? ', ' : ''}${label}`, '')}
</strong>
</p>
))}
```
The array function `reduce()` allow you to (as the name says) reduce and array into an single value.
More info [HERE](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce) | 4,099 |
13,455,143 | Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of `Func*` would only differ if an instance would shadow `z` with something like `self.z = None`.
What is the proper python way to access the class variable `z` using the syntax of `Func1` or `Func2`? | 2012/11/19 | [
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] | I would say that the proper way to get access to the variable is simply:
```
a_instance.z #instance variable 'z'
A.z #class variable 'z'
```
No need for `Func1` and `Func2` here.
---
As a side note, if you *must* write `Func2`, it seems like a `classmethod` might be appropriate:
```
@classmethod
def Func2(cls):
return cls.z
```
---
As a final note, which version you use within methods (`self.z` vs. `A.z` vs. `cls.z` with `classmethod`) really depends on how you want your API to behave. Do you want the user to be able to shadow `A.z` by setting an instance attribute `z`? If so, then use `self.z`. If you don't want that shadowing, you can use `A.z`. Does the method need `self`? If not, then it's probably a classmethod, etc. | I would usually use `self.z`, because in case there are subclasses with different values for `z` it will choose the "right" one. The only reason not to do that is if you know you will always want the `A` version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creating of mixin classes. | 4,100 |
64,996,663 | I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
for (int i = 0; i<BUF;i++){
if (str[i] == 'A')
count++;
}
}
printf("We had %d \'A\'s\n",count);
}
```
Running this using `time ./a.out` prints:
>
>
> ```
> We had 420538682 'A's
>
> real 0m31.267s
> user 0m28.590s
> sys 0m2.531s
>
> ```
>
>
I then used `time tr -cd A < my_huge_file.txt | wc -c` and got back:
>
>
> ```
> 420538233
>
> real 0m13.611s
> user 0m10.688s
> sys 0m3.297s
>
> ```
>
>
I also used python's count method `time count.py`:
```
c = 0
with open("my_huge_file.txt", 'r') as fp:
for line in fp:
c += line.count('A')
print(c)
```
>
>
> ```
> 420538233
>
> real 0m33.073s
> user 0m30.232s
> sys 0m2.650s
>
> ```
>
>
I am not sure how to investigate this discrepancy. tr and python's count are returning 420538233. The C function returns 420538682. | 2020/11/25 | [
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] | This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents have Java 11 pre-installed: [Microsoft-hosted agents](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml)
**Option 2:** Install the Java 11 JDK in your existing pipeline agent.
You can use the [Java Tool Installer](https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/tool/java-tool-installer?view=azure-devops) task to install any Java version on your existing pipeline. | Perhaps the JDK running in your pipeline is, say, version 8. In that case, the Java compiler that is executed doesn't understand what version 11 means. Perhaps your local environment is using Java 11 where this problem would therefore not happen. | 4,103 |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | It just means when the match is “” or an empty string, that it is included in the list of results. | If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it. | 4,106 |
62,684,468 | I'm working on an automated web scraper for a Restaurant website, but I'm having an issue. The said website uses Cloudflare's anti-bot security, which I would like to bypass, not the Under-Attack-Mode but a captcha test that only triggers when it detects a non-American IP or a bot. I'm trying to bypass it as Cloudflare's security doesn't trigger when I clear cookies, disable javascript or when I use an American proxy.
Knowing this, I tried using python's requests library as such:
```
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'}
response = requests.get("https://grimaldis.myguestaccount.com/guest/accountlogin", headers=headers).text
print(response)
```
But this ends up triggering Cloudflare, no matter the proxy I use.
**HOWEVER** when using urllib.request with the same headers as such:
```
import urllib.request
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'}
request = urllib.request.Request("https://grimaldis.myguestaccount.com/guest/accountlogin", headers=headers)
r = urllib.request.urlopen(request).read()
print(r.decode('utf-8'))
```
When run with the same American IP, this time it does not trigger Cloudflare's security, even though it uses the same headers and IP used with the requests library.
So I'm trying to figure out what exactly is triggering Cloudflare in the requests library that isn't in the urllib library.
While the typical answer would be "Just use urllib then", I'd like to figure out what exactly is different with requests, and how I could fix it, first off to understand how requests works and Cloudflare detects bots, but also so that I may apply any fix I can find to other httplibs (notably asynchronous ones)
**EDIT N°2: Progress so far:**
Thanks to @TuanGeek we can now bypass the Cloudflare block using requests as long as we connect directly to the host IP rather than the domain name (for some reason, the DNS redirection with requests triggers Cloudflare, but urllib doesn't):
```
import requests
from collections import OrderedDict
import socket
# grab the address using socket.getaddrinfo
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
headers = OrderedDict({
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
})
s = requests.Session()
s.headers = headers
response = s.get(f"https://{address}/guest/accountlogin", verify=False).text
```
To note: trying to access via HTTP (rather than HTTPS with the verify variable set to False) will trigger Cloudflare's block
Now this is great, but unfortunately, my final goal of making this work asynchronously with the httplib HTTPX still isn't met, as using the following code, the Cloudflare block is still triggered even though we're connecting directly through the Host IP, with proper headers, and with verifying set to False:
```
import trio
import httpx
import socket
from collections import OrderedDict
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
headers = OrderedDict({
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
})
async def asks_worker():
async with httpx.AsyncClient(headers=headers, verify=False) as s:
r = await s.get(f'https://{address}/guest/accountlogin')
print(r.text)
async def run_task():
async with trio.open_nursery() as nursery:
nursery.start_soon(asks_worker)
trio.run(run_task)
```
**EDIT N°1: For additional details, here's the raw HTTP request from urllib and requests**
REQUESTS:
```
send: b'GET /guest/nologin/account-balance HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: grimaldis.myguestaccount.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0\r\nConnection: close\r\n\r\n'
reply: 'HTTP/1.1 403 Forbidden\r\n'
header: Date: Thu, 02 Jul 2020 20:20:06 GMT
header: Content-Type: text/html; charset=UTF-8
header: Transfer-Encoding: chunked
header: Connection: close
header: CF-Chl-Bypass: 1
header: Set-Cookie: __cfduid=df8902e0b19c21b364f3bf33e0b1ce1981593721256; expires=Sat, 01-Aug-20 20:20:06 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0
header: Expires: Thu, 01 Jan 1970 00:00:01 GMT
header: X-Frame-Options: SAMEORIGIN
header: cf-request-id: 03b2c8d09300000ca181928200000001
header: Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
header: Set-Cookie: __cfduid=df8962e1b27c25b364f3bf66e8b1ce1981593723206; expires=Sat, 01-Aug-20 20:20:06 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Vary: Accept-Encoding
header: Server: cloudflare
header: CF-RAY: 5acb25c75c981ca1-EWR
```
URLLIB:
```
send: b'GET /guest/nologin/account-balance HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: grimaldis.myguestaccount.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0\r\nConnection: close\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Thu, 02 Jul 2020 20:20:01 GMT
header: Content-Type: text/html;charset=utf-8
header: Transfer-Encoding: chunked
header: Connection: close
header: Set-Cookie: __cfduid=db9de9687b6c22e6c12b33250a0ded3251292457801; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Expires: Thu, 2 Jul 2020 20:20:01 GMT
header: Cache-Control: no-cache, private, no-store
header: X-Powered-By: Undertow/1
header: Pragma: no-cache
header: X-Frame-Options: SAMEORIGIN
header: Content-Security-Policy: script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.google-analytics.com https://www.google-analytics.com/analytics.js https://use.typekit.net connect.facebook.net/ https://googleads.g.doubleclick.net/ app.pendo.io cdn.pendo.io pendo-static-6351154740266000.storage.googleapis.com pendo-io-static.storage.googleapis.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ https://www.google.com/recaptcha/api.js apis.google.com https://www.googletagmanager.com api.instagram.com https://app-rsrc.getbee.io/plugin/BeePlugin.js https://loader.getbee.io api.instagram.com https://bat.bing.com/bat.js https://www.googleadservices.com/pagead/conversion.js https://connect.facebook.net/en_US/fbevents.js https://connect.facebook.net/ https://fonts.googleapis.com/ https://ssl.gstatic.com/ https://tagmanager.google.com/;style-src 'unsafe-inline' *;img-src * data:;connect-src 'self' app.pendo.io api.feedback.us.pendo.io; frame-ancestors 'self' app.pendo.io pxsweb.com *.pxsweb.com;frame-src 'self' *.myguestaccount.com https://app.getbee.io/ *;
header: X-Lift-Version: Unknown Lift Version
header: CF-Cache-Status: DYNAMIC
header: cf-request-id: 01b2c5b1fa00002654a25485710000001
header: Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
header: Set-Cookie: __cfduid=db9de811004e591f9a12b66980a5dde331592650101; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Set-Cookie: __cfduid=db9de811004e591f9a12b66980a5dde331592650101; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Set-Cookie: __cfduid=db9de811004e591f9a12b66980a5dde331592650101; expires=Sat, 01-Aug-20 20:20:01 GMT; path=/; domain=.myguestaccount.com; HttpOnly; SameSite=Lax; Secure
header: Server: cloudflare
header: CF-RAY: 5acb58a62c5b5144-EWR
``` | 2020/07/01 | [
"https://Stackoverflow.com/questions/62684468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7032457/"
] | This really piqued my interests. The `requests` solution that I was able to get working.
Solution
--------
Finally narrow down the problem. When you use requests it uses urllib3 connection pool. There seems to be some inconsistency between a regular urllib3 connection and a connection pool. A working solution:
```py
import requests
from collections import OrderedDict
from requests import Session
import socket
# grab the address using socket.getaddrinfo
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
s = Session()
headers = OrderedDict({
'Accept-Encoding': 'gzip, deflate, br',
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'
})
s.headers = headers
response = s.get(f"https://{address}/guest/accountlogin", headers=headers, verify=False).text
print(response)
```
Technical Background
--------------------
So I ran both method through Burp Suite to compare the requests. Below are the raw dumps of the requests
### using requests
```
GET /guest/accountlogin HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Connection: close
Host: grimaldis.myguestaccount.com
Accept-Language: en-GB,en;q=0.5
Upgrade-Insecure-Requests: 1
dnt: 1
```
### using urllib
```
GET /guest/accountlogin HTTP/1.1
Host: grimaldis.myguestaccount.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Dnt: 1
```
**The difference is the ordering of the headers.** The difference in the `dnt` capitalization is not actually the problem.
So I was able to make a successful request with the following raw request:
```
GET /guest/accountlogin HTTP/1.1
Host: grimaldis.myguestaccount.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0
```
So the `Host` header has be sent above `User-Agent`. So if you want to continue to to use requests. Consider using a OrderedDict to ensure the ordering of the headers. | After some debugging, and thanks to the answers of @TuanGeek, we've found out the issue with the requests library seems to come from a DNS issue on requests' part when dealing with cloudflare, a simple fix to this issue is connecting directly to the host IP as such:
```
import requests
from collections import OrderedDict
from requests import Session
import socket
# grab the address using socket.getaddrinfo
answers = socket.getaddrinfo('grimaldis.myguestaccount.com', 443)
(family, type, proto, canonname, (address, port)) = answers[0]
s = Session()
headers = OrderedDict({
'Accept-Encoding': 'gzip, deflate, br',
'Host': "grimaldis.myguestaccount.com",
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'
})
s.headers = headers
response = s.get(f"https://{address}/guest/accountlogin", headers=headers, verify=False).text
print(response)
```
Now, this fix didn't work when working with the httplib HTTPX, However I've found where the issue stems from.
The issue comes from the h11 library (used by HTTPX to handle HTTP/1.1 requests), while urllib would automatically fix the letter case of headers, h11 took a different approach by lowercasing every header. While in theory this shouldn't cause any issues, as servers should handle headers in a case-insensitive manner (and in a lot of cases they do), the reality is that HTTP is Hard™️ and services such as Cloudflare don't respect RFC2616 and requires headers to be properly capitalized.
Discussions about capitalization have been going for a while over at h11:
<https://github.com/python-hyper/h11/issues/31>
And have "recently" started to pop up over on HTTPX's repo as well:
<https://github.com/encode/httpx/issues/538>
<https://github.com/encode/httpx/issues/728>
Now the unsatisfactory answer to the issue between Cloudflare and HTTPX is that until something is done over on h11's side (or until Cloudflare miraculously starts respecting RFC2616), not much can be changed to how HTTPX and Cloudflare handle header capitalization.
Either use a different HTTPLIB such as aiohttp or requests-futures, try forking and patching the header capitalization with h11 yourself, or wait and hope for the issue to be dealt with properly by the h11 team. | 4,111 |
52,608,420 | I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well.
The only problem is that my language uses curly brackets rather then : and indents.
So some times when I type return for example it highlights the return in red.
Is there any way I can disable error highlights?
Here is an Example:
[](https://i.stack.imgur.com/iIiS8.png) | 2018/10/02 | [
"https://Stackoverflow.com/questions/52608420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6516763/"
] | I'm surprised that someone is still using jQuery Mobile but I think I have most of the code you need.
Several years ago I wrote an article covering a complex jQuery Mobile authorization tutorial: <https://www.gajotres.net/complex-jquery-mobile-authorization-example/>
The main idea is to post your authorization information from jQM client:
```
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).on("mobileinit", function () {
$.mobile.hashListeningEnabled = false;
$.mobile.pushStateEnabled = false;
$.mobile.changePage.defaults.changeHash = false;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<a href="#login" class="ui-btn-left ui-btn ui-btn-inline ui-mini ui-corner-all ui-btn-icon-left ui-icon-delete" id="back-btn">Back</a>
<h3>Welcome Page</h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
```
Forward this information to server side PHP. Of course you will need to handle DB read/write; my example use some kind of ORM, for example Propel as it has a large number of available tutorials.
```
<?php
function authorize()
{
//normally this info would be pulled from a database.
//build JSON array
$status = array("status" => "success");
return $status;
}
$possible_params = array("authorization", "test");
$value = "An error has occurred";
if (isset($_POST["action"]) && in_array($_POST["action"], $possible_params))
{
switch ($_POST["action"])
{
case "authorization":
$value = authorize();
break;
}
}
//return JSON array
exit(json_encode($value));
?>
```
Get response back to jQuery Mobile and depending on a page type, open appropriate page using:
```
$.mobile.changePage("#second");
```
Here's a whole jQM example from my tutorial:
```
var userHandler = {
username : '',
status : ''
}
$(document).on('pagecontainershow', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'login') {
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
userHandler.username = $('#username').val();
// Send data to server through the Ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'auth.php',
data: {action : 'authorization', formData : $('#check-user').serialize()},
type: 'post',
async: 'true',
dataType: 'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show Ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide Ajax spinner
},
success: function (result) {
// Check if authorization process was successful
if(result.status == 'success') {
userHandler.status = result.status;
$.mobile.changePage("#second");
} else {
alert('Logon unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all necessary fields');
}
return false; // cancel original event to prevent form submitting
});
} else if(activePage.attr('id') === 'second') {
activePage.find('.ui-content').text('Wellcome ' + userHandler.username);
}
});
$(document).on('pagecontainerbeforechange', function (e, ui) {
var activePage = $(':mobile-pagecontainer').pagecontainer('getActivePage');
if(activePage.attr('id') === 'second') {
var to = ui.toPage;
if (typeof to === 'string') {
var u = $.mobile.path.parseUrl(to);
to = u.hash || '#' + u.pathname.substring(1);
if (to === '#login' && userHandler.status === 'success') {
alert('You cant open a login page while youre still logged on!');
e.preventDefault();
e.stopPropagation();
// remove active status on a button if a transition was triggered with a button
$('#back-btn').removeClass('ui-btn-active ui-shadow').css({'box-shadow':'0 0 0 #3388CC'});
}
}
}
});
```
Above tutorial is written in jQuery Mobile 1.4.5. While there's already a version 1.5 it is still an alpha version and there's a good chance we will never see a RC version of 1.5, so stick to 1.4.5.
Again you only need to write PHP DB handling implementation and that should not take you that much time if you stick to Propel ORM. | I'm not sure what your php file looks like as you have not provided the code...
But here is a mockup example of the front-end js and html.
Place js in between head tags.
```
<script type="text/javascript">
$(document).ready(function () {
$("#insert").click(function () {
var email = $("#email").val();
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
var password = $("#password").val();
if(password.length < 5){
alert("Please ensure password is longer than 5 characters");
return false;
}
var dataString =
"email=" + email
+ "&password=" + password
+ "&insert=";
$.ajax({
type: "POST",
url: "#yoururl...",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function () {
$("#insert").val('Connecting...');
},
success: function(data){
if(data=="teacher")
{
window.location='teacher.html'
}
else if(data=="student")
{
window.location='student.html'
}
else {
alert("Failed to login");
}
}
});
});
});
</script>
```
html:
```
<input id="email" type="text" class="form-control" name="email"
placeholder="Email">
<input id="password" type="password" class="form-control" name="password"
placeholder="Password">
<button type="submit" id="insert" value="Insert" class="btn btn-primary btn-
block" >Login</button>
```
Hope that helps. | 4,112 |
58,100,383 | I have been experimenting to create a docker image with python3.6 based on amazonlinux.
So far, I have not been very successful. I use
```
docker run -it amazonlinux
```
to start an interactive docker terminal. Inside the terminal, I run "yum install python36" and see the following error message. Note that I copied this step was from an old amazonlinux based Dockerfile. This Dockerfile used to work. So I suspend the error I see below is due to amazon updated their docker linux image
```
bash-4.2# yum install python36
Loaded plugins: ovl, priorities
amzn2-core | 2.4 kB 00:00:00
No package python36 available.
Error: Nothing to do
```
I have tried to add a python3.6 repo by following this post
<https://janikarhunen.fi/how-to-install-python-3-6-1-on-centos-7> however, it still gives the same error when I run
```
yum install python36u
```
Is there any way to add python3.6 to amazonlinux base layer? Thanks in advance. | 2019/09/25 | [
"https://Stackoverflow.com/questions/58100383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947254/"
] | You can check this [Dockerfile](https://github.com/RealSalmon/docker-amazonlinux-python/blob/master/Dockerfile) based on amazon Linux and having python version is `PYTHON_VERSION=3.6.4`.
Or you can work with your existing one like
```
ARG PYTHON_VERSION=3.6.4
ARG BOTO3_VERSION=1.6.3
ARG BOTOCORE_VERSION=1.9.3
ARG APPUSER=app
RUN yum -y update &&\
yum install -y shadow-utils findutils gcc sqlite-devel zlib-devel \
bzip2-devel openssl-devel readline-devel libffi-devel && \
groupadd ${APPUSER} && useradd ${APPUSER} -g ${APPUSER} && \
cd /usr/local/src && \
curl -O https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz && \
tar -xzf Python-${PYTHON_VERSION}.tgz && \
cd Python-${PYTHON_VERSION} && \
./configure --enable-optimizations && make && make altinstall && \
rm -rf /usr/local/src/Python-${PYTHON_VERSION}* && \
yum remove -y shadow-utils audit-libs libcap-ng && yum -y autoremove && \
yum clean all
```
But better to clone the repo and make your own image form that. | I too had similiar issue for docker.
yum install docker
Loaded plugins: ovl, priorities
amzn2-core | 3.7 kB 00:00:00
No package docker available.
Error: Nothing to do
instead yum I used amazon-linux-extras, it worked
amazon-linux-extras install docker
================================== | 4,113 |
53,296,469 | below is the python code
```
def load_scan(path):
print(path)
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
slices.sort(key = lambda x: int(x.InstanceNumber))
try:
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
for s in slices:
s.SliceThickness = slice_thickness
return slices
patient = load_scan(filepath)
```
i downloaded the sample dicom files from [link](https://wiki.cancerimagingarchive.net/display/Public/LIDC-IDRI)
any help would be great... how to read dicom files and then process them. | 2018/11/14 | [
"https://Stackoverflow.com/questions/53296469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207817/"
] | Find where filereader.py is. You can see the directory from the traceback itself.
Replace `raise StopIteration` with `return` and you are set to go.
Your filereader.py directory will look like this : `/usr/local/lib/python3.7/site-packages/dicom/filereader.py` | I believe dicom is no longer supported, Use [pydicom](https://pypi.org/project/pydicom/) instead of dicom. | 4,115 |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(element)
```
EDIT: This code works but feels very unclean. I feel like python has a better way to do this:
```
counter = 0
while counter < 3:
if counter >= len(my_list):
break
do_stuff(my_list[counter])
counter += 1
``` | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | You could use `itertools.islice`:
```
for element in itertools.islice(my_list, 0, 3):
do_stuff(element)
```
Of course, if it actually *is* a list, then you could just use a regular slice:
```
for element in my_list[:3]:
do_stuff(element)
```
Regular slices on normal sequences are "forgiving" in that if you ask for more elements than are there, no exception will be raised. | ```
for element in my_list[:3]:
do_stuff(element)
``` | 4,116 |
69,979,902 | I am doing this assignment for a python course but I am nowhere near the solution.
Let's say if I enter x = 4, this is what I am supposed to get:
```
"pyramid(0) =>" [ ]
"pyramid(1) =>" [ [1] ]
"pyramid(2) =>" [ [1], [1, 1] ]
"pyramid(3) =>" [ [1], [1, 1], [1, 1, 1] ]
```
I believe the logic is similar when making triangle's right side, right?
this is my code, but I am missing something, hope you guys could point me to the right direction and the task's logic.
Thank you!
```
x = 4
list1 = []
line = 0
while line < x:
one = line + 1
while one > 0:
list1.append(1)
one -= 1
line += 1
print(list1)
``` | 2021/11/15 | [
"https://Stackoverflow.com/questions/69979902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572613/"
] | You can do:
```
def pyramid(n):
result = []
for i in range(n):
result.append([1] * (i+1))
return result
>>> pyramid(0)
[]
>>> pyramid(1)
[[1]]
>>> pyramid(2)
[[1], [1, 1]]
``` | I tried to come up with words to guide you to this solution, but it just wasn't possible. You need a 'for' loop to count to 4, and you need `[1]*i` to create a list with a certain number of 1s.
```
x = 4
list1 = []
print("pyramid(0) =>", list1)
for i in range(x):
list1.append( [1] * i )
print("pyramid(%d) =>" % (i+1), list1)
``` | 4,121 |
44,311,287 | I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import time,sys
from datetime import datetime
from time import sleep
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
ssh_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_pre.connect("192.168.0.1",22, "admin", "admin")
output=""
ssh = ssh_pre.invoke_shell()
sys.stdout=open("ssh_session_dump.txt","w")
print("Script Start Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
model="XV4-17034"
ssh.send("more off\n")
if ssh.recv_ready():
output = ssh.recv(1000)
ssh.send("show system-info\n")
sleep(5)
output = ssh.recv(5000)
output=output.decode('utf-8')
lines=output.split("\n")
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
print("Test Case 1.1 - PASS - Model is an " + model)
else:
print("Test Case 1.1 - FAIL - Model is not an " + model)
ssh.send( "quit\n" )
ssh.close()
datetime = datetime.now()
print("")
print("Script End Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
print("")
sys.stdout.close()
``` | 2017/06/01 | [
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] | If this were my project, I would convert the code to a function and then create a keyword library that includes that function.
For example, you could create a file named CustomLibrary.py with a function defined like this:
```
def verify_model(model):
prompt = "#"
datetime = datetime.now()
ssh_pre = paramiko.SSHClient()
...
for item in lines:
if "Model:" in item:
line=item.split()
if line[1]==model+',':
return True
else:
raise Exception("Model was %s, expected %s" % (line[1], model))
...
```
Then, you could create a robot test like this:
```
*** Settings ***
Library CustomLibrary
*** Test cases ***
Verify model is Foo
verify model foo
```
Of course, it's a tiny bit more complicated than that. For example, you would probably need to change the logic in the function to guarantee that you close the connection before returning. Overall, though, that's the general approach: create one or more functions, import them as a library, and then call the functions from a robot test. | To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:
```
from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.
class CustomLibrary(object):
def __init__(self):
self.selenium_lib = BuiltIn().get_library_instance('ExtendedSelenium2Library')
# This is where you initialize any other global variables you might want to use in the code.
# I import BuiltIn and Extended Selenium2 Library to gain access to their keywords.
def run_my_code(self):
# Place the rest of your code here
```
I've used this a lot in my testing. In order to call it, you need something similar to this:
```
*** Settings ***
Library ExtendedSelenium2Library
Library CustomLibrary
*** Test Cases ***
Test My Code
Run My Code
```
This will run whatever code you place in the Python file. Robot Framework does not directly implement Python, as far as I know, but it is written in Python. So, as long as you feed it Python in a form that it can recognize, it'll run it just like any other keyword from BuiltIn or Selenium2Library.
Please note that ExtendedSelenium2Library is exactly the same as Selenium2Library except that it includes code to deal with Angular websites. Same keywords, so I just use it as a strict upgrade. If you want to use the old Selenium2Library, just swap out all instances of the text "ExtendedSelenium2Library" for "Selenium2Library".
Please note that in order to use any keywords from BuiltIn or ExtendedSelenium2Library you will need to use the syntax `BuiltIn().the_keyword_name(arg1, arg2, *args)` or `selenium_lib().the_keyword_name(arg1, arg2, *args)`, respectively. | 4,123 |
46,418,397 | This may appear like a very trivial question but I have just started learning python classes and objects. I have a code like below.
```
class Point(object):
def __init__(self,x,y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return '('+str(self.x)+','+str(self.y)+')'
def main():
p1 = Point(pt1,pt2)
p2 = Point(pt3,pt4)
p3 = Point(pt5,pt6)
p4 = Point(pt7,pt8)
parray = [p1,p2,p3,p4]
print " Points are", p1,p2,p3,p4
print "parray",parray
```
I m getting the below Output :
Points are (4.0,2.0) (4.0,8.0) (4.0,-1.0) (100.0,1.0)
parray - intersection.Point object at 0x7ff09f00a550, intersection.Point object at 0x7ff09f00a410, intersection.Point object at 0x7ff09f00a590
My question is why are the addresses of objects assigned to array while I get the values while printing the objects?
Can someone suggest a way to get the values returned by class in array in main function? | 2017/09/26 | [
"https://Stackoverflow.com/questions/46418397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629294/"
] | I would use Repeat to add one element and implement the interpolation as a new lambda layer. I don't think there's an existing layer for this in keras. | Surprisingly there is no existing layer/function in keras that does such an interpolation of a tensor (as pointed out by xtof54). So, I implemented it using a lambda layer, and it worked fine.
```
def resize_like(input_tensor, ref_tensor): # resizes input tensor wrt. ref_tensor
H, W = ref_tensor.get_shape()[1], ref_tensor.get_shape()[2]
return tf.image.resize_nearest_neighbor(input_tensor, [H.value, W.value])
```
The problem, in the first place, was due to the use of a tensor directly from tensorflow in a Keras layer, as a few additional attributes (required for a keras tensor) that are missing. In addition, though Lambda layer is quite easy to use, it would be really convenient if keras allows the use of tensors (if possible) from tensorflow directly in keras layers, in the future. | 4,126 |
66,742,855 | I am working in selenium with python.
I used the code that worked, one hour ago, but now it returns me that
```
no such element: Unable to lacate element:...
```
The same code worked maximum one hour ago.
Where is the problem? I checked the source code, but it still the same
Here is my code:
```
import selenium
from selenium import webdriver
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
PATH="C:\Program Files (x86)\chromedriver"
driver=webdriver.Chrome(PATH)
driver.get("https://moitane.ge/shop/5-gudvili/43-axali-xorci-da-xorcproduqti")
time.sleep(3)
#el = driver.find_element(By.XPATH, "//div[@class='style__ShopProductSubCategoryChip-sc-1bc3ssb-2 iKSeHs']")
el = driver.find_element(By.XPATH, "//li[@class='style__CategoryItem-sc-8ncu0g-2 tZtCz']//span[text()='ახალი ხილი']")
time.sleep(3)
el.click()
time.sleep(5)
ell = driver.find_element(By.XPATH, "//*[@id='main-layout']/div[5]/div[4]/div/div[1]/div/div/div/div[1]/div")
```
It gives me error:
```
NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='main-layout']/div[5]/div[4]/div/div[1]/div/div/div/div[1]/div"}
(Session info: chrome=89.0.4389.90)
```
Here is copied element:
`'<div class="style__ProductItemWrapper-nvyr2y-0 cbyRwl product-item-wrapper"><img class="style__ProductItemImage-nvyr2y-2 gfMqx product-image" src="https://static.moitane.ge/Moitane_files/093c2492-ccf3-4515-adcf-2f610a09e473_Thumb.jpeg" style="width: 166px; height: 132.8px; cursor: pointer;"><p class="style__ProductItemText-nvyr2y-3 ebZGDv" style="cursor: pointer; height: 40px;">ბანანი (წონის) (იმპ) </p><div style="display: flex; margin-top: auto; width: 100%; align-items: flex-start;"><span class="style__ProductItemDesc-nvyr2y-4 cIkCnK" style="margin-left: auto;">1 კგ</span></div><div class="style__ProductItemActionsWrapper-nvyr2y-5 kQtpVm" style="cursor: pointer; position: relative;"><span class="style__ProductItemPrice-nvyr2y-6 hLsuWS"><span>4.10 ₾</span> </span><div style="position: absolute; top: 0px; right: 0px; height: 100%; width: 50%;"></div><span class="style__ProductItemActionButton-nvyr2y-7 bieLnj"><i class="icon-plus" style="color: rgb(146, 146, 157);"></i></span></div></div>`' | 2021/03/22 | [
"https://Stackoverflow.com/questions/66742855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15446325/"
] | You could also use a capture group without a global flag to match for only a single match, and match all lines that do not start with 10 hyphens using a negative lookahead.
```
^(?:(?!----------).*\n)+(?=----------$)
```
[regex demo](https://regex101.com/r/h0BlCk/1)
Or you can match as least as possible lines, until you encounter a line that starts with 10 hyphens.
```
^(?:.*\n)+?(?=----------$)
```
[Regex demo](https://regex101.com/r/UNXrcr/1) | You may try matching on the following pattern, with DOT ALL mode enabled:
```regex
^.*?(?=----------|$)
```
[Demo
----](https://regex101.com/r/mvZxBD/1)
This will match all content up to, but including, the first set of dashes. Note that for inputs not having any dash separators, it would return all content.
If your regex engine does not support DOT ALL mode, then use this version:
```regex
^[\S\s]*?(?=----------|$)
``` | 4,127 |
64,812,794 | The following code appears when I am running a cell on Google Colab:
```
NameError Traceback (most recent call last)
<ipython-input-36-5f325bc0550d in <module>()
4
5 TAGGER_PATH = "crf_nlu.tagger" # path to the tagger- it will save/access the model from here
----> 6 ct = CRFTagger(feature_func=get_features) # initialize tagger with get_features function
7
8 print("training tagger...")
/usr/local/lib/python3.6/dist-packages/nltk/tag/crf.py in __init__(self, feature_func, verbose, training_opt)
81
82 self._model_file = ''
---> 83 self._tagger = pycrfsuite.Tagger()
84
85 if feature_func is None:
NameError: name 'pycrfsuite' is not defined
```
This is the code from the cell:
```
# Train the CRF BIO-tag tagger
import pycrfsuite
TAGGER_PATH = "crf_nlu.tagger" # path to the tagger- it will save/access the model from here
ct = CRFTagger(feature_func=get_features) # initialize tagger with get_features function
print("training tagger...")
ct.train(training_data, TAGGER_PATH)
print("done")
```
What causes this issue?
I have an import for the *CRFTagger* which is:
>
> from nltk.tag import CRFTagger
>
>
> | 2020/11/12 | [
"https://Stackoverflow.com/questions/64812794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14597269/"
] | I just sorted it out. For the google colab, I had to add the following line:
>
> pip install sklearn-pycrfsuite
>
>
> | Use:
>
> pip install python-crfsuite
>
>
>
Scikit-crfsuite provides API similar to scikit-learn library. | 4,128 |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You can execute your file by using this:
```
python /Users/luca/Documents/python/gameover.py
```
You can also run the file by moving to the path of the file you want to run and typing:
```
python gameover.py
``` | Let's say your script is called `my_script.py` and you have put it in your Downloads folder.
There are many ways of installing Python, but [Homebrew](https://brew.sh/) is the easiest.
0. Open [Terminal.app](https://en.wikipedia.org/wiki/Terminal_(macOS)) (press ⌘+Space and type "Terminal" and press the [Enter key](https://en.wikipedia.org/wiki/Enter_key))
1. Install Homebrew (by pasting the following text into Terminal.app and pressing the [Enter key](https://en.wikipedia.org/wiki/Enter_key))
```
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
2. Install Python using Homebrew
```
brew install python
```
3. [`cd`](https://en.wikipedia.org/wiki/Cd_(command)) into the directory that contains your Python script (as an example I'm using the Downloads (`Downloads`) folder in your home ([`~`](https://en.wikipedia.org/wiki/Tilde#Directories_and_URLs)) folder):
```
cd ~/Downloads
```
4. Run the script using the `python3` executable
```
python3 my_script.py
```
You can also skip step 3 and give `python3` an [absolute path](https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths) instead
```
python3 ~/Downloads/my_script.py
```
---
Instead of typing out that whole thing (`~/Downloads/my_script.py`), you can find the `.py` file in Finder.app and just drag it into the Terminal.app window which should type out the absolute path for you.
If you have spaces or certain other symbols somewhere in your filename you need to enclose the file name in quotes:
```
python3 "~/Downloads/some directory with spaces/and a filename with a | character.py"
``` | 4,129 |
42,165,925 | I have .txt file that has 6 lines on it.
```
Line 1 name
Line 2 eamil address
line 4 phone number
line 5 sensor name
line 6 link .
```
I want to read those 6 lines in python and forward an email to the email address listed in the second line. I have a script that does this . But I don't know how to do this from .txt file .
Thanks. | 2017/02/10 | [
"https://Stackoverflow.com/questions/42165925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449247/"
] | ```
with open("filename", "r") as f:
for l in f:
// do your processing, maybe keep track of how many lines you see since you need to do something different on each line
``` | Have a look at this question: [How do I read a text file into a string variable in Python](https://stackoverflow.com/q/8369219/2519977)
It shows you how to read a file line per line into an array.
So you can do:
```
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
```
`data[1]` would then be the email address.
Please do proper research before asking. | 4,139 |
65,912,670 | I have .csv file with only 2 columns. ("left" and "right")
The file size is less than 200 MB
I use the following code on **dev server** and it works as expected:
```
import pandas as pd
df = pd.read_csv('en_bigram.csv')
st = df[df["right"] == "some_text"]["left"]
st[st.str.startswith("My")].to_list()
```
"pandas" module is not installed on **production server**. I will like to know if
*I should install pandas*
or
*I should rewrite the code in pure python*
Is there any overhead (like memory/ cpu) in using pandas in production?
Can the 4 lines pandas code written using python's built in modules like csv in 4 or 5 lines? | 2021/01/27 | [
"https://Stackoverflow.com/questions/65912670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | I ran the following experiments on my machine (Intel 9th Gen i7) with a test data file of ~535 MB:
### Pandas version
```py
# import measurement dependencies
import time
import psutil
p = psutil.Process()
start = time.process_time()
import pandas as pd
df = pd.read_csv('test.csv')
st = df[df["right"] == "some_text"]["left"]
res = st[st.str.startswith("My")].to_list()
print(time.process_time() - start)
print(p.memory_percent())
```
### Pure Python Version
```py
# import measurement dependencies
import time
import psutil
p = psutil.Process()
start = time.process_time()
import csv
with open('test.csv', 'r') as f:
r = csv.reader(f)
headers = next(r, None)
left = headers.index("left")
right = headers.index("right")
res = [line for line in r if line[right] == "some_text" and line[left].startswith('My')]
print(time.process_time() - start)
print(p.memory_percent())
```
Please let me know if there are any efficiencies I am missing with the Python version of the code (or pandas, for that matter), but after several trials, the results were far enough for me to be convinced they are statistically significant:
| | Process Time (lower is better) | Memory (lower is better) |
| --- | --- | --- |
| Pandas | ~11s | 4.5% |
| Python | ~14s | 3.1% |
Unless there is some major issue with how I wrote the Python version, it seems to me that Pandas does seem to be more efficient in CPU time, but less efficient in memory.
While the `pandas` library is more memory than the `csv` module, by about a factor of 4, both were significantly less than 50 MB of memory. | >
> Is there any overhead (like memory/ cpu) in using pandas in production? Can the 4 lines pandas code written using python's built in modules like csv in 4 or 5 lines?
>
>
>
I'm going to say go with pandas. Once you start slicing and dicing large datasets, numpy arrays are much more efficient than python lists. | 4,141 |
67,172,207 | I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
similar = [words for words in x if words in y ]
print(similar)
```
**Output**
```
['person']
```
**But I want**
```
['there','person']
```
Does anyone know the simplest way of implementing this? | 2021/04/20 | [
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] | Check out this code use `any function` along with `map` to map containing conditon.
```
x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)
```
**OUTPUT:**
```
['there', 'person']
``` | Just compare the strings without any comma:
```py
similar = [words for words in x if words.replace(',', '') in y ]
```
**Output**:
```py
>>similar
['there,', 'person']
``` | 4,142 |
24,807,434 | I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules from that subpackage with absolute imports. I get this error `AttributeError: 'module' object has no attribute 'subpkg'`.
Example
=======
**Structure**:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two_longname.py
└── tst.py
```
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import One
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two_longname as two
class One(two.Two):
pass
```
**pkg/subpkg/two\_longname.py**:
```
class Two:
pass
```
**pkg/tst.py**:
```
from pkg.subpkg import One
print(One)
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest2/pkg/tst.py", line 1, in <module>
from pkg.subpkg import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/__init__.py", line 1, in <module>
from pkg.subpkg.one import One
File "/home/and/dev/test/python/imptest2/pkg/subpkg/one.py", line 1, in <module>
import pkg.subpkg.two_longname as two
AttributeError: 'module' object has no attribute 'subpkg'
```
Workarounds
-----------
There are changes that make it work:
1. Empty `pkg/subpkg/__init__.py` and importing directly from `pkg.subpkg.one`.
I don't consider this as an option because AFAIK "lifting" things to the package level is ok. Here is quote from [an article](http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html):
>
> One common thing to do in your `__init__.py` is to import selected
> Classes, functions, etc into the package level so they can be
> conveniently imported from the package.
>
>
>
2. Changing `import as` to `from import` in `one.py`:
```
from pkg.subpkg import two_longname
class One(two_longname.Two):
pass
```
The only con here is that I can't create a short alias for module. I got that idea from @begueradj's answer.
It is also possible to use a relative import in `one.py` to fix the problem. But I think it's just a variation of workaround #2.
Questions
=========
1. Can someone explain what is actually going on here? Why a combination of imports in `__init__.py` and usage of `import as` leads to such problems?
2. Are there any better workarounds?
---
Original example
================
This is my original example. It's not very realistic but I'm not deleting it so @begueradj's answer still makes sense.
**pkg/**init**.py** is empty.
**pkg/subpkg/**init**.py**:
```
from pkg.subpkg.one import ONE
```
**pkg/subpkg/one.py**:
```
import pkg.subpkg.two
ONE = pkg.subpkg.two.TWO
```
**pkg/subpkg/two.py**:
```
TWO = 2
```
**pkg/tst.py**:
```
from pkg.subpkg import ONE
```
**Output**:
```
$ python3.4 -m pkg.tst
Traceback (most recent call last):
File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.4/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/and/dev/test/python/imptest/pkg/tst.py", line 1, in <module>
from pkg.subpkg import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/__init__.py", line 2, in <module>
from pkg.subpkg.one import ONE
File "/home/and/dev/test/python/imptest/pkg/subpkg/one.py", line 6, in <module>
ONE = pkg.subpkg.two.TWO
AttributeError: 'module' object has no attribute 'subpkg'
```
Initially I had this in **one.py**:
```
import pkg.subpkg.two as two
ONE = two.TWO
```
In that case I get error on import (just like in my original project which uses `import as` too). | 2014/07/17 | [
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] | You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that the following 2 are "effectively" the same:
1. `import foo.bar.bazaar as baz`
2. `from foo.bar import bazaar as baz`
The statement is not quite true in **Python versions up to and including 3.6.x** as evidenced by the corner case you met, namely if the required modules already exist in `sys.modules` but are yet uninitialized. The `import ... as` requires that the module `foo.bar` is injected in `foo` namespace as the attribute `bar`, in addition to being in `sys.modules`, whereas the `from ... import ... as` looks for `foo.bar` in `sys.modules`.
(Do note also that `import foo.bar` only ensures that the module `foo.bar` is in `sys.modules` and accessible as `foo.bar`, but might not be fully initialized yet.)
Changing the code as follows did the trick for me:
```
# import pkg.subpkg.two_longname as two
from pkg.subpkg import two_longname as two
```
And code runs perfectly on both Python 2 and Python 3.
Also, in `one.py` you cannot do `from pkg import subpkg`, for the same reason.
---
To demonstrate this bug further, fix your `one.py` as above, and add the following code in `tst.py`:
```
import pkg
import pkg.subpkg.two_longname as two
del pkg.subpkg
from pkg.subpkg import two_longname as two
import pkg.subpkg.two_longname as two
```
Only the last line crashes, because `from ... import` consults the `sys.modules` for `pkg.subpkg` and finds it there, whereas `import ... as` consults `sys.modules` for `pkg` and tries to find `subpkg` as an attribute in the `pkg` module. As we just had deleted that attribute, the last line fails with `AttributeError: 'module' object has no attribute 'subpkg'`.
---
As the `import foo.bar as baz` syntax is a bit obscure and adds more corner cases, and I have rarely if ever seen it being used, I would recommend avoiding it completely and favouring `from .. import ... as`. | Your project structure regarding the way you call modules, must be like this:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two.py
tst.py
```
Define your **two.py** like this:
```
class TWO:
def functionTwo(self):
print("2")
```
Define your **one.py** like this :
```
from pkg.subpkg import two
class ONE:
def functionOne(self):
print("1")
self.T=two.TWO()
print("Calling TWO from ONE: ")
self.T.functionTwo()
```
Define your **test.py** like this
```
from pkg.subpkg import one
class TEST:
def functionTest(self):
O=one.ONE()
O.functionOne()
if __name__=='__main__':
T=TEST()
T.functionTest()
```
When you execute, you will get this:
```
1
Calling TWO from ONE:
2
```
Hope this helps. | 4,145 |
73,404,980 | I need to include a directory containing a python script and binaries that need to be executed by the script based on the parsed arguments in the JavaFX application.
The project is modular and built using Maven (although the modular part is not such an important piece of information).
When built using the maven run configuration, application works properly but for the purpose of creating a runtime image I stumble upon the problem of not having the script executed when I run the generated launcher .bat script in the "bin" folder of the "target".
For the purpose of generating the runtime, I have put the script directory in the project "resources" folder. The script is executed from the Java code using the Java Runtime.
Let's say the code looks like this:
```
pyPath = Paths.get("src/main/resources/script/main.py").toAbsolutePath().toString();
command = "python"+pyPath+args;
runtime = Runtime.getRuntime();
process = runtime.exec(command);
```
And ***pom.xml*** file looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>gui</artifactId>
<version>1.0-SNAPSHOT</version>
<name>gui</name>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.8.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>18</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>18</version>
</dependency>
<dependency>
<groupId>org.controlsfx</groupId>
<artifactId>controlsfx</artifactId>
<version>11.1.1</version>
</dependency>
<dependency>
<groupId>com.dlsc.formsfx</groupId>
<artifactId>formsfx-core</artifactId>
<version>11.3.2</version>
<exclusions>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.kordamp.ikonli</groupId>
<artifactId>ikonli-javafx</artifactId>
<version>12.3.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jfoenix</groupId>
<artifactId>jfoenix</artifactId>
<version>9.0.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.panteleyev</groupId>
<artifactId>jpackage-maven-plugin</artifactId>
<version>1.5.2</version>
<configuration>
<name>gui</name>
<appVersion>1.0.0</appVersion>
<vendor>1234</vendor>
<destination>target/dist</destination>
<module>com.example.gui/com.example.gui.Application</module>
<runtimeImage>target/example-gui</runtimeImage>
<winDirChooser>true</winDirChooser>
<winPerUserInstall>true</winPerUserInstall>
<winShortcut>true</winShortcut>
<winMenuGroup>Applications</winMenuGroup>
<icon>${project.basedir}/main/resources/img/icon.ico</icon>
<javaOptions>
<option>-Dfile.encoding=UTF-8</option>
</javaOptions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>18</source>
<target>18</target>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.8</version>
<executions>
<execution>
<id>default-cli</id>
<configuration>
<mainClass>com.example.gui/com.example.gui.Application</mainClass>
<launcher>gui-launcher</launcher>
<jlinkZipName>gui</jlinkZipName>
<jlinkImageName>gui</jlinkImageName>
<jlinkVerbose>true</jlinkVerbose>
<noManPages>true</noManPages>
<stripDebug>true</stripDebug>
<noHeaderFiles>true</noHeaderFiles>
<options>
<option>--add-opens</option><option>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.base/com.sun.javafx.binding=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED</option>
<option>--add-opens</option><option>javafx.base/com.sun.javafx.event=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.controls/com.sun.javafx.scene.control.behavior=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.base/com.sun.javafx.binding=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.graphics/com.sun.javafx.stage=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.graphics/com.sun.javafx.scene=ALL-UNNAMED</option>
<option>--add-exports</option><option>javafx.base/com.sun.javafx.event=ALL-UNNAMED</option>
</options>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
\***Note: additional options for the javafx-maven-plugin are added for the jfoenix package compatibility**
Also **module-info.java**
```
module com.example.gui {
requires javafx.controls;
requires javafx.fxml;
requires org.controlsfx.controls;
requires com.dlsc.formsfx;
requires org.kordamp.ikonli.javafx;
requires com.jfoenix;
opens com.example.gui to javafx.fxml;
exports com.example.gui;
}
```
Now the question is how do I include the script in the application runtime image, have it executed when I call the generated .bat for the application and finally packed using the jpackage? | 2022/08/18 | [
"https://Stackoverflow.com/questions/73404980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19794251/"
] | Problems
========
The `src/main/resources` directory only exists in your project sources. It does not exist in the build output, and it definitely does not exist in your deployment location. In other words, using:
```java
var pyPath = Paths.get("src/main/resources/script/main.py").toAbsolutePath().toString();
```
Will only work when your working directory is your project directory. It's also reading the "wrong" `main.py` resource, as the "correct" one will be in your `target` directory. Additionally, resources are **not** files. You must access resources using the resource-lookup API. For example:
```java
var pyPath = getClass().getResource("/script/main.py").toString();
```
And note `src/main/resources` is not included in the resource name.
Executing the Script
--------------------
But even after you correctly access the resource you still have a problem. Your script is a resource, which means it will be embedded in a JAR file or custom run-time image when deployed. I strongly doubt Python will know how to read and execute such a resource. This means you need to find a way to make the Python script a regular file on the host computer.
---
Potential Solutions
===================
I can think of at least three approaches that may solve the problems described above. As I only have Windows, I can't promise the below examples will work on other platforms, or otherwise be easily translated for other platforms.
My examples don't include JavaFX, as I don't believe that's necessary to demonstrate how to include a Python script that is executed at runtime.
Here are some common aspects between all solutions.
**module-info.java:**
```java
module com.example {}
```
**main.py:**
```python
print("Hello from Python!")
```
1. Extract the Script at Runtime
--------------------------------
One approach is to extract the Python script to a known location on the host computer at runtime. This is likely the most versatile solution, as it doesn't depend much on the way you deploy your application (jar, jlink, jpackage, etc.).
This example extracts the script to a temporary file, but you can use another location, such as an application-specific directory under the user's home directory. You can also code it to extract only if not already extracted, or only once per application instance.
I think this is the solution I would use, at least to start with.
**Project structure:**
```none
| pom.xml
|
\---src
\---main
+---java
| | module-info.java
| |
| \---com
| \---example
| \---app
| Main.java
|
\---resources
\---scripts
main.py
```
**Main.java:**
```java
package com.example.app;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
Path target = Files.createTempDirectory("sample-1.0").resolve("main.py");
try {
// extract resource to temp file
try (InputStream in = Main.class.getResourceAsStream("/scripts/main.py")) {
Files.copy(in, target);
}
String executable = "python";
String script = target.toString();
System.out.printf("COMMAND: %s %s%n", executable, script); // log command
new ProcessBuilder(executable, script).inheritIO().start().waitFor();
} finally {
// cleanup for demo
Files.deleteIfExists(target);
Files.deleteIfExists(target.getParent());
}
}
}
```
**pom.xml:**
```xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>sample</artifactId>
<version>1.0</version>
<name>sample</name>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>18</maven.compiler.release>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<archive>
<manifest>
<mainClass>com.example.app.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jlink-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>default-cli</id>
<phase>package</phase>
<goals>
<goal>jlink</goal>
</goals>
</execution>
</executions>
<configuration>
<classifier>win</classifier>
</configuration>
</plugin>
<plugin>
<groupId>org.panteleyev</groupId>
<artifactId>jpackage-maven-plugin</artifactId>
<version>1.5.2</version>
<executions>
<execution>
<id>default-cli</id>
<phase>package</phase>
<goals>
<goal>jpackage</goal>
</goals>
</execution>
</executions>
<configuration>
<type>APP_IMAGE</type>
<runtimeImage>${project.build.directory}/maven-jlink/classifiers/win</runtimeImage>
<module>com.example/com.example.app.Main</module>
<destination>${project.build.directory}/image</destination>
<winConsole>true</winConsole>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
Build the project with:
```none
mvn package
```
And then execute the built application image:
```none
> .\target\image\sample\sample.exe
COMMAND: python C:\Users\***\AppData\Local\Temp\sample-1.015076039373849618085\main.py
Hello from Python!
```
2. Place the Script in the "Application Directory"
--------------------------------------------------
*Disclaimer: I don't know if doing this is a smart or even supported approach.*
This solution makes use of `--input` to place the script in the "application directory" of the application image. You can then get a reference to this directory by setting a system property via `--java-options` and `$APPDIR`. Note I tried to get this to work with the class-path, so as to not need the `$APPDIR` system property, but everything I tried resulted in `Class#getResource(String)` returning `null`.
The application directory is the `app` directory shown in [this documentation](https://docs.oracle.com/en/java/javase/18/jpackage/packaging-overview.html#GUID-DAE6A497-6E6F-4895-90CA-3C71AF052271).
As this solution places the Python script with the rest of the application image, which means it's placed in the installation location, you may be more likely to run into file permission issues.
Given the way I coded `Main.java`, this demo *must* be executed only after packaging with `jpackage`. I suspect there's a more robust way to implement this solution.
**Project structure:**
```none
| pom.xml
|
+---lib
| \---scripts
| main.py
|
\---src
\---main
\---java
| module-info.java
|
\---com
\---example
\---app
Main.java
```
**Main.java:**
```java
package com.example.app;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
String executable = "python";
String script = Path.of(System.getProperty("app.dir"), "scripts", "main.py").toString();
System.out.printf("COMMAND: %s %s%n", executable, script); // log command
new ProcessBuilder(executable, script).inheritIO().start().waitFor();
}
}
```
**pom.xml:**
(this is only the `<configuration>` of the `org.panteleyev:jpackage-maven-plugin` plugin, as everything else in the POM is unchanged from the first solution)
```xml
<configuration>
<type>APP_IMAGE</type>
<runtimeImage>${project.build.directory}/maven-jlink/classifiers/win</runtimeImage>
<input>lib</input>
<javaOptions>
<javaOption>-Dapp.dir=$APPDIR</javaOption>
</javaOptions>
<module>com.example/com.example.app.Main</module>
<destination>${project.build.directory}/image</destination>
<winConsole>true</winConsole>
</configuration>
```
Build the project with:
```none
mvn package
```
And then execute the built application image:
```none
> .\target\image\sample\sample.exe
COMMAND: python C:\Users\***\Desktop\sample\target\image\sample\app\scripts\main.py
Hello from Python!
```
3. Add the Script as Additional "App Content"
---------------------------------------------
*Disclaimer: Same as the disclaimer for the second solution.*
This would make use of the `--app-content` argument when invoking `jpackage`. Unfortunately, I could not figure out how to configure this using Maven, at least not with the `org.panteleyev:jpackage-maven-plugin` plugin. But essentially this solution would have been the same as the second solution above, but with `--input` removed and `--app-content lib/scripts` added. And a slight change to how the script `Path` is resolved in code.
The `--app-content` argument seems to put whatever directories/files are specified in the root of the generated application image. I'm not sure of a nice convenient way to get this directory, as the application image structure is slightly different depending on the platform. And as far as I can tell, there's no equivalent `$APPDIR` for the image's root directory. | I managed to create the artifacts using the [Java Packager](https://github.com/fvarrui/JavaPackager) plugin for Maven which made the deployment a much easier task. | 4,148 |
19,795,357 | I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? Does python have a shell like this? I would rather do this than switch over to maintaining batch code on both Linux and Windows.
```
#!/bin/bash
#run scripts to generate and manipulate data
for ((i=1; i<=3 ; i++))
do
randfuncgen.py -k 12 > randomvalues_$i.fitdata
probe.py -k 12 < randomvalues_$i.fitdata > randomvalues_$i.walshdata
std.py -m s < randomvalue_$i.walshdata > randomvalues_separate_std_$i.walshdata
std.py -m a < randomvalue_$i.walshdata > randomvalues_all_std_$i.walshdata
done
``` | 2013/11/05 | [
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] | Don't think you can work around using `require`, but you can specifically check for `MODULE_NOT_FOUND` errors:
```
function moduleExists(mod) {
try {
require(mod);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
return false;
throw e;
};
return true;
}
``` | I'm showing with the "swig" module. There might be better ways, but this works for me.
```
var swig;
try {
swig = require('swig');
} catch (err) {
console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
console.log(" [ OK ]\t Module: swig");
}
``` | 4,149 |
55,602,574 | I am attempting to programmatically put data into a locally running DynamoDB Container by triggering a Python lambda expression.
I'm trying to follow the template provided here: <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.03.html>
I am using the amazon/dynamodb-local you can download here: <https://hub.docker.com/r/amazon/dynamodb-local>
Using Ubuntu 18.04.2 LTS to run the container and lambda server
AWS Sam CLI to run my Lambda api
Docker Version 18.09.4
Python 3.6 (You can see this in sam logs below)
Startup command for python lambda is just "sam local start-api"
First my Lambda Code
```
import json
import boto3
def lambda_handler(event, context):
print("before grabbing dynamodb")
# dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000",region_name='us-west-2',AWS_ACCESS_KEY_ID='RANDOM',AWS_SECRET_ACCESS_KEY='RANDOM')
dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")
table = dynamodb.Table('ContactRequests')
try:
response = table.put_item(
Item={
'id': "1234",
'name': "test user",
'email': "testEmail@gmail.com"
}
)
print("response: " + str(response))
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world"
}),
}
```
I know that I should have this table ContactRequests available at localhost:8000, because I can run this script to view my docker container dynamodb tables
I have tested this with a variety of values in the boto.resource call to include the access keys, region names, and secret keys, with no improvement to result
```
dev@ubuntu:~/Projects$ aws dynamodb list-tables --endpoint-url http://localhost:8000
{
"TableNames": [
"ContactRequests"
]
}
```
I am also able to successfully hit the localhost:8000/shell that dynamodb offers
Unfortunately while running, if I hit the endpoint that triggers this method, I get a timeout that logs like so
```
Fetching lambci/lambda:python3.6 Docker container image......
2019-04-09 15:52:08 Mounting /home/dev/Projects/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro inside runtime container
2019-04-09 15:52:12 Function 'HelloWorldFunction' timed out after 3 seconds
2019-04-09 15:52:13 Function returned an invalid response (must include one of: body, headers or statusCode in the response object). Response received:
2019-04-09 15:52:13 127.0.0.1 - - [09/Apr/2019 15:52:13] "GET /hello HTTP/1.1" 502 -
```
Notice that none of my print methods are being triggered, if I remove the call to table.put, then the print methods are successfully called.
I've seen similar questions on Stack Overflow such as this [lambda python dynamodb write gets timeout error](https://stackoverflow.com/questions/44034289/lambda-python-dynamodb-write-gets-timeout-error) that state that the problem is I am using a local db, but shouldn't I still be able to write to a local db with boto3, if I point it to my locally running dynamodb instance? | 2019/04/09 | [
"https://Stackoverflow.com/questions/55602574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740463/"
] | As per [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) suggests, the `monthIndex` would start at 0, rather than 1. So you need to manually subtract 1.
```
data.forEach((item) => {
item.date.pop()
item.date[1]--
item.date = new Date(...item.date).toLocaleString('en-US')
});
``` | The month is represented by a value from 0 to 11, 4 is the fifth month, it corresponds to May, you just need to decrease it by 1. | 4,152 |
60,654,425 | I am making a lot of plots and saving them to a file, it all works, but during the compilation I get the following message:
```
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
fig = self.plt.figure(figsize=self.figsize)
```
So I think I could improve the code by closing the figures, I googled it and found that I should use `fig.close()`. However I get the following error `'Figure' object has no attribute 'close'`. How should I make it work?
This is the loop in which I create plots:
```
for i in years:
ax = newdf.plot.barh(y=str(i), rot=0)
fig = ax.get_figure()
fig.savefig('C:\\Users\\rysza\\Desktop\\python data analysis\\zajecia3\\figure'+str(i)+'.jpeg',bbox_inches='tight')
fig.close()
``` | 2020/03/12 | [
"https://Stackoverflow.com/questions/60654425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11085398/"
] | Replace `fig.close()` with `plt.close(fig)`, [`close`](https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html) is a function defined directly in the module. | Try this, matplotlib.pyplot.close(fig) , for more information refer this website
<https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html> | 4,153 |
14,082,909 | I'm creating a simple script for blender and i need a little help with get some data from file i've created before via python.
That file got structure like below:
```
name first morph
values -1.0000 1.0000
data 35 0.026703 0.115768 -0.068769
data 36 -0.049349 0.015188 -0.029470
data 37 -0.042880 -0.045805 -0.039931
data 38 0.000000 0.115775 -0.068780
name second morph
values -0.6000 1.2000
data 03 0.037259 -0.046251 -0.020062
data 04 -0.010330 -0.046106 -0.019890
…
```
etc more 2k lines ;p
What i need is to create a loop that read for me those data line by line and put values into three different arrays: names[] values[] and data[] depending on first word of file line.
```
Manualy it should be like that:
names.append('first morph')
values.append( (-1.0000,1.0000))
data.append((35, 0.026703, 0.115768, -0.068769))
data.append((36, -0.049349, 0.015188, -0.029470))
data.append((37, -0.042880, -0.045805, -0.039931))
data.append((38, 0.000000, 0.115775, -0.068780))
names.append('second morph')
values.append( (-0.6000,1.2000))
…
```
I dont know why my atempts of creating that kind of 'for line in file:' loop creating more errors than complete data, i dont know why is going out of range, or not getting proper data
Please help how to automate that process instead of writing manualy each line since i already exported needed parameters into a file. | 2012/12/29 | [
"https://Stackoverflow.com/questions/14082909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1936580/"
] | ```
names = []
values = []
data = []
with open('yourfile') as lines:
for line in lines:
first, rest = line.split(' ', 1)
if first == 'name':
names.append(rest)
elif first == 'values':
floats = map(float, rest.split())
values.append(tuple(floats))
elif first == 'data':
int_str, floats_str = rest.split(' ', 1)
floats = map(float, floats_str.split())
data.append( (int(int_str),) + tuple(floats) )
```
Why do you need it like this? How will you know where the next name starts in your data and values lists? | Here is a simple python "for line in" solution... you can just call `processed.py`...
```
fp = open("data1.txt", "r")
data = fp.readlines()
fp1 = open("processed.py", "w")
fp1.write("names = []\nvalues=[]\ndata=[]\n")
for line in data:
s = ""
if "name" in line:
s = "names.append('" + line[5:].strip() + "')"
elif "values" in line:
s = "values.append((" + ", ".join(line[7:].strip().split(" ")) + "))"
elif "data" in line:
s = "data.append((" + ", ".join(line[5:].strip().split(" ")) + "))"
fp1.write(s + "\n");
fp1.close()
fp.close()
``` | 4,154 |
33,936,017 | I learn how to remove items from a list while iterating from [here](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) by:
```
somelist = [x for x in somelist if determine(x)]
```
Further, how do I remove a specific index from a list while iterating? For instance,
```
lists = list() # a list of lists
for idx, line in enumerate(lists):
if idx > 0:
cur_val = line[0] # value of current line
prev_val = lists[idx-1][0] # value of previous line
if prev_val == cur_val :
del lists[idex-1] # IndexError: list index out of range
``` | 2015/11/26 | [
"https://Stackoverflow.com/questions/33936017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067748/"
] | Basically your attempt is not supported according to any documentation. In general you should not modify a container while iterating unless the documentation explicitly says that you can. It doesn't help if it "seems to work" since you then just exploiting some behavior in the version of the implementation you're using, but that behavior can change without prior notice (breaking your program).
What you need to do is making the modification separate from the iteration. Using list comprehension is one way to achieve this, but basically you're doing the same thing.
There's a few variants, either you make a copy of the data and iterate through that and modify the original. Or you make a copy before iterating the original and modify the copy and then updates the original. There's also the variant where you build the copy during iteration and then update the original.
In addition your example is flawed because you don't take into account that modification affects the proper index in the modified `list`. For example if you have the list `[1, 1, 2, 2, 3, 3]`, then when you've removed the duplicates `1`s and `2`s and detect duplicate `3`s you have the list `[1, 2, 3, 3]`, but when you find the duplicate `3`s you find these at index `4` and `5`, but after the deletion they are at index `2` and `3` instead.
```
lists = list() # a list of lists
cur = 0 # index in the modified list
for idx, line in list(enumerate(lists)): # make a copy of the original
if idx > 0:
cur_val = line[0] # value of current line
prev_val = lists[idx-1][0] # value of previous line
if prev_val == cur_val:
del lists[cur-1] # IndexError: list index out of range
else:
cur += 1
else:
cur += 1
```
The solution where you modify a copy instead is basically the same, but the solution where you build the copy during iteration is a bit different.
```
lists = list() # a list of lists
tmp = []
for idx, line in enumerate(lists): # make a copy of the original
if idx > 0:
cur_val = line[0] # value of current line
prev_val = lists[idx-1][0] # value of previous line
if prev_val != cur_val:
tmp.append(line)
else:
tmp.append( line )
lists[:] = tmp
```
The last line is where the origin is updated, otherwise the loop works by appending those elements that are to be kept to `tmp` (instead of copying all and then remove those that's not to be kept). | You can produce the same thing using list comprehension:
```
somelist = [i for idx, i in enumerate(lists) if i[0] != lists[idx][0]]
``` | 4,155 |
13,033,820 | I have a question about while loops in python.
I want to make a program that performs a while loop in a certain time.I want to add the extra feature that while the program us running,a certain variable can be changed by pressing a random key.
```
from time import sleep
import time
i=0
a=0
while i<10:
i=i+1
i=i+a
a=a+1
time.sleep(1)
print i
```
I want to do it that the variable a can be reset to 0 by pressing any key.The loop should continue unchanged if no button is pressed.What command should i add?
Thanks
Edit: I tried:
```
import pygame
from pygame.locals import *
import time
i=0
a=0
pygame.init()
while i<10:
pygame.event.get()
i=i+a
print i
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
i=0
i=i+1
time.sleep(1)
pygame.quit()
```
But now nothing happens when I press a button.What did i miss? | 2012/10/23 | [
"https://Stackoverflow.com/questions/13033820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714419/"
] | This might be happening because you render the *header*, *menu* and *body* inside a `<table>`. At least the *body* seems to be missing the row and cell tags (`<tr><td>...</td></tr>`). Therefore there are no rows and cells in your table which can lead to all sorts of rendering problems.
It would probably help if you didn't render into a table and use CSS for layout purposes instead. | This looks to be nothing to do with the MVC side of what you are doing - that looks perfectly fine.
The issue will be with your HTML. I would suggest having a look at the site using one of the browser developer tools (e.g. in Chrome or IE open your site and press F12) - you can use the features of these to examine how the visual elements on your page relate to the HTML. These tools are invaluable as an MVC programmer.
Using tables to control the layout of a web-page is discouraged in favour of using css for layout. You can find some basic css layout templates via Google to get started. | 4,156 |
59,407,592 | Below code has a call to a method called **lago**.
```
#!/usr/bin/env python
#
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#
import sys
class InstallTest():
"""Ru Ovirt System Tests"""
def run_command_checking_exit_code(command):
""" Runs a command"""
print("Command is " + str(command))
print(command.read())
print(command.close())
def lago():
"""run the conductor profiles required to install OLVM """
Log.test_objective('TODO')
run_command_checking_exit_code('ls -al')
"""
yum_list = ["epel-release", "centos-release-qemu-ev", "python-devel", "libvirt", "libvirt-devel", "libguestfs-tools", "libguestfs-devel", "gcc", "libffi-devel", "openssl-devel", "qemu-kvm-ev"]
for yum in yum_list
ret, msg, tup = self.client.run('/qa/conductor/tests/' + OSSE_OLV_VERSION + '/installer/installerfactory.py -s ' + OSSE_OLV_ENGINE_HOST + ' -t OS_OL7U6_X86_64_PVHVM_30GB -c 10.1.0.10 -o ' + self.log_jobdir_cc +'/vm_install_ol7.6', timeout=1000000)
if ret:
self.tc_fail('Creation of OLV Engine VM failed')
ret, msg, tup = self.client.run('/qa/conductor/tests/' + OSSE_OLV_VERSION + '/installer/installerfactory.py -s ' + OSSE_OLV_ENGINE_HOST +' -p ovirt-engine -c 10.1.0.10 -o ' + self.log_jobdir_cc + '/engine_deploy', timeout=1000000)
if ret:
self.tc_fail('Install of OLV Engine Host failed')
self.tc_pass('OLV Engine Host installed')
"""
def main():
lago()
main()
```
However, it is shown to not exist in the output
```
Traceback (most recent call last):
File "C:/Users/rafranci/Downloads/ovirt_st_setup.py", line 20, in <module>
class InstallTest():
File "C:/Users/rafranci/Downloads/ovirt_st_setup.py", line 65, in InstallTest
main()
File "C:/Users/rafranci/Downloads/ovirt_st_setup.py", line 63, in main
lago()
NameError: name 'lago' is not defined
```
As far as I can see, there is no reason for this - ideas? | 2019/12/19 | [
"https://Stackoverflow.com/questions/59407592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12342391/"
] | Try this :
```js
var value1="4111111111111111"
var pattern = new RegExp('^4[0-9]{12}(?:[0-9]{3})?$}');
var result=pattern.test(value1);
console.log(result);
```
This will return either `True` or `False` | If you pattern is somthimg like that: `4111111111111111` or `4111111111111111`
then use this code:
```
const str="^4[0-9]{12}([0-9]{3})?$";
'4111111111111'.match(str)
'4111111111111111'.match(str)
``` | 4,157 |
56,750,400 | Is there any library implementation for the `label2idx()` function in python?
I wish to extract superpixels from the label representation to the format exactly returned by the `label2idx()` function.
label2idx function: <https://in.mathworks.com/help/images/ref/label2idx.html> | 2019/06/25 | [
"https://Stackoverflow.com/questions/56750400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9215748/"
] | Given an array of labels `label_arr` containing all labels from `1` to `max(label_arr)`, you can do:
```
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
for i in range(1, np.max(label_arr) + 1)]
```
---
If you want to relax the requirement of all labels being contained you can add a simple `if`, i.e.:
```
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
if i in label_arr else np.array([], dtype=int)
for i in range(1, np.max(label_arr) + 1)]
```
---
Just to replicate the example in the MATLAB docs:
```
import numpy as np
import scipy as sp
import scipy.ndimage
struct_arr = np.array(
[[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 0]])
label_arr, num_labels = sp.ndimage.label(struct_arr)
# label_arr:
# [[1 1 1 0 0 0 0 0]
# [1 1 1 0 2 2 0 0]
# [1 1 1 0 2 2 0 0]
# [1 1 1 0 0 0 0 0]
# [1 1 1 0 0 0 3 0]
# [1 1 1 0 0 0 3 0]
# [1 1 1 0 0 3 3 0]
# [1 1 1 0 0 0 0 0]]
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
for i in range(1, np.max(label_arr) + 1)]
pixel_idxs = label2idx(label_arr)
for pixel_idx in pixel_idxs:
print(pixel_idx)
# [ 0 1 2 8 9 10 16 17 18 24 25 26 32 33 34 40 41 42 48 49 50 56 57 58]
# [12 13 20 21]
# [38 46 53 54]
```
Note, however that you do not get the very same results because of the differences between MATLAB and NumPy, notably:
* MATLAB: FORTRAN-style matrix indexing and 1-based indexing
* Python+NumPy: C-style matrix indexing and 0-based indexing
and if you want to get the very same numbers you get in MATLAB you may use this instead (note the extra `.T` and the `+ 1`):
```
def label2idx_MATLAB(label_arr):
return [
np.where(label_arr.T.ravel() == i)[0] + 1
for i in range(1, np.max(label_arr) + 1)]
``` | MATLAB's [`label2idx`](https://www.mathworks.com/help/images/ref/label2idx.html) outputs the flattened indices (column-major ordered) given the labeled image.
We can use `scikit-image's` built-in [`regionprops`](https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops) to get those indices from the labeled image. `Scikit-image` also provides for us a built-in to get the labeled image, so it all works out with that same package. The implementation would look something like this -
```
from skimage.measure import label,regionprops
def label2idx(L):
# Get region-properties for all labels
props = regionprops(L)
# Get XY coordinates/indices for each label
indices = [p.coords for p in props]
# Get flattened-indices for each label, similar to MATLAB version
# Note that this is row-major ordered.
flattened_indices = [np.ravel_multi_index(idx.T,L.shape) for idx in indices]
return indices, flattened_indices
```
Sample run -
```
# Input array
In [62]: a
Out[62]:
array([[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 0, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 0, 0, 0, 0]])
# Get labeled image
In [63]: L = label(a)
In [64]: idx,flat_idx = label2idx(L)
In [65]: flat_idx
Out[65]:
[array([ 0, 1, 2, 8, 9, 10, 16, 17, 18, 24, 25, 26, 32, 33, 34, 40, 41,
42, 48, 49, 50, 56, 57, 58]),
array([12, 13, 20, 21]),
array([38, 46, 53, 54])]
```
If you need the indices in column-major order like in MATLAB, simply transpose the image and then feed in -
```
In [5]: idx,flat_idx = label2idx(L.T)
In [6]: flat_idx
Out[6]:
[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23]),
array([33, 34, 41, 42]),
array([46, 52, 53, 54])]
```
Note that the indexing still starts from `0`, unlike in MATLAB where it's from `1`.
**Alternative to getting labeled image with SciPy**
SciPy also has a built-in to get labeled-image : [`scipy.ndimage.label`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.label.html) -
```
from scipy.ndimage import label
L = label(a)[0]
``` | 4,158 |
37,662,732 | I'm looking for an XPATH to extract 'sets' as separate sequences. It has to be interpreted by python `lxml` (which is a wrapper around `libxml2`).
For example, given the following:
```
<root>
<sub1>
<sub2>
<Container>
<item>1 - My laptop has exploded again</item>
<item>2 - This is an issue which needs to be fixed.</item>
</Container>
</sub2>
<sub2>
<Container>
<item>3 - It's still not working</item>
<item>4 - do we have a working IT department or what?</item>
</Container>
</sub2>
<sub2>
<Container>
<item>5 - Never mind - I got my 8 year old niece to fix it</item>
</Container>
</sub2>
</sub1>
</root>
```
I want to be able to 'isolate' each group or sequence, e.g. sequence 1 being:
```
1 - My laptop has exploded again
2 - This is an issue which needs to be fixed.
```
Second sequence:
```
3 - It's still not working
4 - do we have a working IT department or what?
```
Third sequence:
```
5 - Never mind - I got my 8 year old niece to fix it
```
Where 'sequence' would be, translated in pseudocode/python:
```
seq1 = ['1 - My laptop has exploded again', '2 - This is an issue which needs to be fixed.']
seq2 = ['3 - It's still not working', '4 - do we have a working IT department or what?']
seq 3 = ['5 - Never mind - I got my 8 year old niece to fix it']
```
From some preliminary research it seems like [sequences can't be nested](https://stackoverflow.com/questions/32732003/in-xpath-how-can-i-select-groups-of-following-sibling-nodes-before-and-after-an) but I'm wondering if there's some black magic doable with [these operators](http://zvon.org/comp/r/tut-XPath_1.html#Pages~List_of_XPaths). | 2016/06/06 | [
"https://Stackoverflow.com/questions/37662732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204634/"
] | 1. Evaluate this XPath expression:
`count(/*/*/*)`
This finds the number of `<sub2>` elements (equivalent and more readable, but longer, is:
```
count(/*/sub1/sub2))
```
2. For each `$n` in 1 to `count(/*/*/*)` evaluate the following XPath expression:
`/*/*/*[$n]/*/item/text()`
Again, this is equivalent to the longer and more readable:
```
/*/sub1/sub2[$n]/Container/item/text()
```
Before evaluating the above expressions replace `$n` with the actual value of `$n` (for example using the `format()` method for strings.
For the provided XML document `$n` is 3, therefore the actual XPath expressions that are evaluated are:
```
/*/*/*[1]/*/item/text()
```
,
```
/*/*/*[2]/*/item/text()
```
,
```
/*/*/*[3]/*/item/text()
```
And they produce the following results each:
A collection (language - dependent -- array, sequence, collection, `IEnumerable<string>`, ... etc.):
```
"1 - My laptop has exploded again", "2 - This is an issue which needs to be fixed."
```
,
```
"3 - It's still not working", "4 - do we have a working IT department or what?"
```
,
```
"5 - Never mind - I got my 8 year old niece to fix it"
``` | ```
from lxml import etree
doc=etree.parse("data.xml");
v = doc.findall('sub1/sub2/Container')
finalResult = list()
for vv in v:
sequence = list()
for item in vv.findall('item'):
sequence.append(item.text)
finalResult.append(sequence)
print finalResult
```
And this is the result:
```
[['1 - My laptop has exploded again', '2 - This is an issue which needs to be fixed.'], ["3 - It's still not working", '4 - do we have a working IT department or what?'], ['5 - Never mind - I got my 8 year old niece to fix it']]
```
### Note
I assumed that the data is in a file named 'data.xml' in the same directory as the script that contains the above code. | 4,159 |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined>
Exception ignored in: <generator object cursor_iter at 0x0460C140>
Traceback (most recent call last):
File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
```
It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly?
FYI, all other DB functionalities work fine | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.html#locale.getpreferredencoding):
>
> Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.
>
>
>
[Here](https://stackoverflow.com/a/34345136/645146) I found "hacky" but working method to overwrite these settings:
In file `settings.py` of your django project add these lines:
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
``` | Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.
[djangoproject.com](https://code.djangoproject.com/ticket/32439)
the settings box looks like this. Enable the check and restart your system
[](https://i.stack.imgur.com/dv0tU.png) | 4,160 |
56,460,723 | I am working with Django and currently try to move my local dev. to Docker. I managed to run my web server. However, what I didn't to yet was `npm install`. That's where I got stuck and I couldn't find documentation or good examples. Anyone who has done that before?
**Dockerfile**:
```
# Pull base image
FROM python:3.7
# Define environment variable
ENV PYTHONUNBUFFERED 1
RUN apt-get update && apt-get install -y \
# Language dependencies
gettext \
# In addition, when you clean up the apt cache by removing /var/lib/apt/lists
# it reduces the image size, since the apt cache is not stored in a layer.
&& rm -rf /var/lib/apt/lists/*
# Copy the current directory contents into the container at /app
COPY . /app
# Set the working directory to /app
WORKDIR /app
# Install Python dependencies
RUN pip install pipenv
RUN pipenv install --system --deploy --dev
COPY ./docker-entrypoint.sh /
RUN chmod +x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]
```
**docker-compose:**
```
version: '3'
services:
db:
image: postgres
ports:
- "5432:5432"
environment:
# Password will be required if connecting from a different host
- POSTGRES_PASSWORD=django
web:
build: .
env_file: .env
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
container_name: django
```
**docker-entrypoint.sh**
```
#!/bin/bash
# Apply database migrations
echo "Apply database migrations"
python manage.py migrate
# Run tests (In progress)
# echo "Running tests"
# pytest
# Start server
echo "Starting server"
python manage.py runserver 0.0.0.0:8000
``` | 2019/06/05 | [
"https://Stackoverflow.com/questions/56460723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10419791/"
] | It is simple, you should just follow this instruction:
```
npm install
//or
yarn install
```
This will install all node\_modules, when it is not found in the current directory, it will search for the **node\_modules** on directory up.
Hope this answers your question. | In the Dockerfile just add:
RUN npm install
This will look if there is a package.json in the current directory and if it does, it will install all dependencies. | 4,170 |
12,091,009 | I'm trying to get this [nodetime](http://nodetime.com/docs) running, but seems there's some prblems I can't figur out. I did exactly as the guide say, So i supposed to get following:
>
> After your start your application, a link of the form https://nodetime.com/[session\_id] will be printed to the console, where the session will be your unique id for accessing the profiler server
>
>
>
It end the console didn't display any session id link, only this:
`23 Aug 13:32:23 - Nodetime: profiler resumed for 180 seconds`
Maybe any of you guys has experienced same issue? Looking for fixes! Thanks, in advance!
Below is what i got after nodetime installation, i got some Python error, but still seems lika a successful installation...
```
npm WARN package.json application-name@0.0.1 No README.md file found!
npm WARN package.json jade@0.26.3 No README.md file found!
npm http GET http://registry.npmjs.org/nodetime
npm http 200 http://registry.npmjs.org/nodetime
npm http GET http://registry.npmjs.org/nodetime/-/nodetime-0.4.5.tgz
npm http 200 http://registry.npmjs.org/nodetime/-/nodetime-0.4.5.tgz
npm http GET http://registry.npmjs.org/request/2.10.0
npm http GET http://registry.npmjs.org/v8tools
npm http GET http://registry.npmjs.org/timekit
npm http 200 http://registry.npmjs.org/request/2.10.0
npm http GET http://registry.npmjs.org/request/-/request-2.10.0.tgz
npm http 200 http://registry.npmjs.org/v8tools
npm http GET http://registry.npmjs.org/v8tools/-/v8tools-0.1.1.tgz
npm http 200 http://registry.npmjs.org/timekit
npm http GET http://registry.npmjs.org/timekit/-/timekit-0.1.9.tgz
npm http 200 http://registry.npmjs.org/v8tools/-/v8tools-0.1.1.tgz
npm http 200 http://registry.npmjs.org/request/-/request-2.10.0.tgz
npm http 200 http://registry.npmjs.org/timekit/-/timekit-0.1.9.tgz
npm http GET http://registry.npmjs.org/bindings
npm http 200 http://registry.npmjs.org/bindings
> timekit@0.1.9 install C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\nod
e_modules\nodetime\node_modules\timekit
> node-gyp rebuild
> v8tools@0.1.1 install C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\nod
e_modules\nodetime\node_modules\v8tools
> node-gyp rebuild
C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\nodetime\node_
modules\timekit>node "C:\Program Files (x86)\nodejs\node_modules\npm\bin\node-gy
p-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\nodetime\node_
modules\v8tools>node "C:\Program Files (x86)\nodejs\node_modules\npm\bin\node-gy
p-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack at failNoPython (C:\Program Files (x86)\nodejs\node_modules\n
pm\node_modules\node-gyp\lib\configure.js:110:14)
gyp ERR! stack at C:\Program Files (x86)\nodejs\node_modules\npm\node_module
s\node-gyp\lib\configure.js:74:11
gyp ERR! stack at Object.oncomplete (fs.js:297:15)
gyp gypERR! System Windows_NT 6.1.7601
ERR! gyp configure errorERR!
command "node" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\node_module
s\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\n
odetime\node_modules\timekit
gypgyp ERR! node -v v0.8.5
gyp ERR! node-gyp -v v0.6.3
gyp ERR! not ok
ERR! stack Error: Can't find Python executable "python", you can set the PYTHON
env variable.
gyp ERR! stack at failNoPython (C:\Program Files (x86)\nodejs\node_modules\n
pm\node_modules\node-gyp\lib\configure.js:110:14)
gyp ERR! stack at C:\Program Files (x86)\nodejs\node_modules\npm\node_module
s\node-gyp\lib\configure.js:74:11
gyp ERR! stack at Object.oncomplete (fs.js:297:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "node" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\nod
e_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\TJIA\Desktop\Sommarjobb\Extrauppgifter\demo\node_modules\n
odetime\node_modules\v8tools
gyp ERR! node -v v0.8.5
gyp ERR! node-gyp -v v0.6.3
gyp ERR! not ok
npm WARN optional dep failed, continuing timekit@0.1.9
npm WARN optional dep failed, continuing v8tools@0.1.1
nodetime@0.4.5 node_modules\nodetime
+-- request@2.10.0
``` | 2012/08/23 | [
"https://Stackoverflow.com/questions/12091009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326868/"
] | No. You cannot embed an Apps Script web app in an external site. You can only do it on a Google Site. | Yes it is possible I have installed google comments and google follower on my tumblr blog. | 4,171 |
44,093,441 | In C++, how are the local class variables declared? I'm new to C++ but have some python experience. I'm wondering if C++ classes have a way of identifying their local variables, for example, in python your class' local variables are marked with a self. so they would be like:
```
self.variable_name
```
Does C++ have something similar to this for local variables or does it have something completely different? In pseudocode, I think the class' variables would look something like this:
```
class Code:
public:
<some code>
private:
int self.variable
double self.other_variable
<more code>
```
but then, I could be completely wrong. Thanks in advance. | 2017/05/21 | [
"https://Stackoverflow.com/questions/44093441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8034222/"
] | That's pretty close! Within the class, however, one would mention the class variables simply using their own name, therefore as `variable` as opposed to `class.variable`.
(Also, note that your functions need to have a semicolon following them, and by convention these functions tend to be defined under the class itself, or in separate files)
```
class Circle {
public:
Circle(double var, bool otherVar); //constructor
double getVariable(); //getter
void setVariable(double var); //setter
// you can put more functions here
private:
double variable;
bool otherVariable;
//you can put more functions here
};
Circle::Circle(double var, bool otherVar){
variable = var;
otherVariable = otherVar;
}
Circle::getVariable(){
return variable;
}
Circle::setVariable(double var){
variable = var
}
```
For a better look at this topic, please look at this [similar question/answer.](https://stackoverflow.com/questions/865922/how-to-write-a-simple-class-in-c), or as noted in a comment, consider reading a textbook on C++...
EDIT: I wrote this answer based on the question title of "identifying" variables, by noting that the problem was likely that code couldn't compile because `class.variable` is not how things are referred to in C++. However, I'm unsure if the question refers to initializing, declaring, etc. | When you read Effective C++ (written by Scott Meyers), member variables are init when ctor initializer. After ctor, all assignment is assignment, not init. You can write ctor like this.
```
Circle(double value, bool isTrueFalse, <More Variables>) : class.variable(value), class.othervariable(isTrueFalse), ..<More Variables> //this is init.
{
class.variable = value; //this is assignment. not init.
}
```
C++ init orders is up-side-down, not ctor initializer order.
```
private:
double class.variable; //First init;
bool class.variables;//Second init;
```
If you want local variables init, you pass value to ctor.
in C++. assignment and init is diffrent. class local members only init at ctor Initializer. init is faster than assignment. because init is just one call ctor, and end. but assignment is call ctor, and assignment Operator one more. you should to use ctor Initializer, for performece. | 4,172 |
63,147,540 | This is my first time using Python and I'm tasked with the following: print a list of cities from this JSON: <http://jsonplaceholder.typicode.com/users>
I'm trying to print out a list that should read:
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
etc.
This is the code I have so far:
```
import json
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)
print(users)
```
When I run `$python3 -i api.py` (file is named api.py) I'm able to print the list from the JSON file in my terminal. However I have been stuck trying to figure out how to print the cities only. I'm assuming it would look something like `users.address.city` but any attempt at figuring out the code has resulted in the following error: `AttributeError: 'list' object has no attribute 'address'`.
Any help you could provide would be greatly appreciated. Thanks! | 2020/07/29 | [
"https://Stackoverflow.com/questions/63147540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13488080/"
] | As `users` is a list, it should be:
```
print(users[0]['address']['city'])
```
This is how you can access nested properties in JSON response.
You can also loop over the users and print their city in the same format.
```
for user in users:
print(user['address']['city'])
``` | You can get city name with user['address']['city']
and use loop to get all city names
like this
```
for user in users:
print(user['address']['city'])
```
output :
```
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
Roscoeview
South Christy
Howemouth
Aliyaview
Bartholomebury
Lebsackbury
[Program finished]
``` | 4,173 |
7,196,148 | I know there is not much on stackoverflow on dojango, but I thought I'd ask anyway.
Dojango describes RegexField as follows:
```
class RegexField(DojoFieldMixin, fields.RegexField):
widget = widgets.ValidationTextInput
js_regex = None # we additionally have to define a custom javascript regexp, because the python one is not compatible to javascript
def __init__(self, js_regex=None, *args, **kwargs):
self.js_regex = js_regex
super(RegexField, self).__init__(*args, **kwargs)
```
And I am using it as so in my forms.py:
```
post_code = RegexField(js_regex = '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}')
# &
post_code = RegexField(attrs={'js_regex': '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}'})
```
Unfortunately these both give me:
```
TypeError: __init__() takes at least 2 arguments (1 given)
```
If I use the following:
```
post_code = RegexField(regex = '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}')
```
I get the following HTML:
```
<input name="post_code" required="true" promptMessage="" type="text" id="id_post_code" dojoType="dijit.form.ValidationTextBox" />
```
Can anyone tell me what I might be doing wrong? | 2011/08/25 | [
"https://Stackoverflow.com/questions/7196148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563247/"
] | After three days of beavering away I fould that you need to send `regex` and `js_regex`, though `regex` is not used:
```
post_code = RegexField(
regex='',
required = True,
widget=ValidationTextInput(
attrs={
'invalid': 'Post Code in incorrect format',
'regExp': '[A-Z]{1,2}\d[A-Z\d]? \d[ABD-HJLNP-UW-Z]{2}'
}
)
)
```
[Oh yeah! and you also need to declare the widget as a `ValidationTextInput`] | The error is related to `super().__init__` call. If `fields.RegexField` is standard Django `RegexField`, then it requires `regex` keyword argument, as documented. Since you don't pass it, you get `TypeError`. If it's supposed to be the same as `js_regex`, then pass it along in the super call.
```
def __init__(self, js_regex, *args, **kwargs):
self.js_regex = js_regex
super(RegexField, self).__init__(regex, *args, **kwargs)
``` | 4,175 |
46,327,700 | I have this `list` in `python` which can have `n` elements. Now what I am trying to do is show `4` elements from this `list` at a time with an added option 'next' to show next set of 4 elements. So if my list is something like this:
```
['room 11','room 22','room 33','room 44','room 55','room 65','room 77']
```
then display it to users like this:
```
1. Room Number : room 11
2. Room Number : room 22
3. Room Number : room 33
4. Room Number : room 44
5. Next
```
if user selects `1`(user selects the number corresponding to the room in the list) then print `Room selected: room 11` or if user selects `2` then print `Room selected: room 22`. If user selects `5` then show next set of 4 elements from the list(if less then 4 left than just show whats left).
I wrote this code which is only partial as I am having difficulty in implementing this functionality completely:
```
room_list_num = 0
room_list_slot = 0
def room_try():
room_list = ['room 11','room 22','room 33','room 44','room 55','room 66','room 77','room 88','room 99','room 110','room 111','room 112']
inner_list_str = ["%d. Room number: %s" % (i, x)
for i, x in enumerate(room_list, 1)]
global room_list_slot
while room_list_slot < len(room_list):
room_list_num = input('Following are the available rooms. Please select the corresponding number of the room you want: \n {}'.format( '\n '.join(inner_list_str[room_list_slot:(room_list_slot+4)])))
room_list_slot += 4
print('Room selected: '+ str(room_list[room_list_num]))
if __name__ == '__main__':
room_try()
```
The difficulty I am having in is to how to add the temporary value 'Next' with each set of 4 elements to display and then move into the list based on users response? | 2017/09/20 | [
"https://Stackoverflow.com/questions/46327700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966197/"
] | This will help you
```
room_list_num = 0
room_list_slot = 0
def room_try():
room_list = ['room 11','room 22','room 33','room 44','room 55','room 66','room 77','room 88','room 99','room 110','room 111','room 112']
inner_list_str = ["%d. Room number: %s" % ((i%4)+1, x)
for i, x in enumerate(room_list, 0)]
global room_list_slot
counter = 0
while counter*4 < len(room_list):
room_list_num = int(input('Following are the available rooms. Please select the corresponding number of the room you want: \n {}'.format( '\n '.join(inner_list_str[room_list_slot:(room_list_slot+4)]) + ['\n 5. Next\n','\n'][room_list_slot+4>=len(room_list)])))
room_list_slot += 4
if room_list_num == 5:
counter += 1
continue
break
print('Room selected: '+ str(room_list[counter*4+room_list_num-1]))
if __name__ == '__main__':
room_try()
``` | You can do something like this:
```
def room_try():
room_list_num = 0
room_list_slot = 0
room_list = ['room 11', 'room 22', 'room 33', 'room 44', 'room 55', 'room 66', 'room 77', 'room 88', 'room 99', 'room 110', 'room 111', 'room 112']
inner_list_str = ["%d. Room number: %s" % (i, x)
for i, x in enumerate(room_list, 1)]
while room_list_slot < len(room_list):
print('Following are the available rooms. Please select the corresponding number of the room you want: \n {}'.format(
'\n '.join(inner_list_str[room_list_slot:(room_list_slot + 4)])))
room_list_num = int(input(" {}. Next\n".format(room_list_slot + 5)))
if (room_list_slot + 5 != room_list_num):
print('Room selected: ' + str(room_list[room_list_num - 1]))
return
else:
room_list_slot += 4
print("You haven't choose any room.")
if __name__ == '__main__':
room_try()
``` | 4,176 |
53,823,349 | I have a set of values that I'd like to plot the gaussian kernel density estimation of, however there are two problems that I'm having:
1. I only have the values of bars not the values themselves
2. I am plotting onto a categorical axis
Here's the plot I've generated so far:
[](https://i.stack.imgur.com/xqBFD.png)
The order of the y axis is actually relevant since it is representative of the phylogeny of each bacterial species.
I'd like to add a gaussian kde overlay for each color, but so far I haven't been able to leverage seaborn or scipy to do this.
Here's the code for the above grouped bar plot using python and matplotlib:
```
enterN = len(color1_plotting_values)
fig, ax = plt.subplots(figsize=(20,30))
ind = np.arange(N) # the x locations for the groups
width = .5 # the width of the bars
p1 = ax.barh(Species_Ordering.Species.values, color1_plotting_values, width, label='Color1', log=True)
p2 = ax.barh(Species_Ordering.Species.values, color2_plotting_values, width, label='Color2', log=True)
for b in p2:
b.xy = (b.xy[0], b.xy[1]+width)
```
Thanks! | 2018/12/17 | [
"https://Stackoverflow.com/questions/53823349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5540779/"
] | How to plot a "KDE" starting from a histogram
=============================================
The protocol for kernel density estimation requires the underlying data. You could come up with a new method that uses the empirical pdf (ie the histogram) instead, but then it wouldn't be a KDE distribution.
Not all hope is lost, though. You can get a good approximation of a KDE distribution by first taking samples from the histogram, and then using KDE on those samples. Here's a complete working example:
```
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as sts
n = 100000
# generate some random multimodal histogram data
samples = np.concatenate([np.random.normal(np.random.randint(-8, 8), size=n)*np.random.uniform(.4, 2) for i in range(4)])
h,e = np.histogram(samples, bins=100, density=True)
x = np.linspace(e.min(), e.max())
# plot the histogram
plt.figure(figsize=(8,6))
plt.bar(e[:-1], h, width=np.diff(e), ec='k', align='edge', label='histogram')
# plot the real KDE
kde = sts.gaussian_kde(samples)
plt.plot(x, kde.pdf(x), c='C1', lw=8, label='KDE')
# resample the histogram and find the KDE.
resamples = np.random.choice((e[:-1] + e[1:])/2, size=n*5, p=h/h.sum())
rkde = sts.gaussian_kde(resamples)
# plot the KDE
plt.plot(x, rkde.pdf(x), '--', c='C3', lw=4, label='resampled KDE')
plt.title('n = %d' % n)
plt.legend()
plt.show()
```
Output:
[](https://i.stack.imgur.com/p6ZUY.png)
The red dashed line and the orange line nearly completely overlap in the plot, showing that the real KDE and the KDE calculated by resampling the histogram are in excellent agreement.
If your histograms are really noisy (like what you get if you set `n = 10` in the above code), you should be a bit cautious when using the resampled KDE for anything other than plotting purposes:
[](https://i.stack.imgur.com/OYN64.png)
Overall the agreement between the real and resampled KDEs is still good, but the deviations are noticeable.
Munge your categorial data into an appropriate form
===================================================
Since you haven't posted your actual data I can't give you detailed advice. I think your best bet will be to just number your categories in order, then use that number as the "x" value of each bar in the histogram. | I have stated my reservations to applying a KDE to OP's categorical data in my comments above. Basically, as the phylogenetic distance between species does not obey the triangle inequality, there cannot be a valid kernel that could be used for kernel density estimation. However, there are other density estimation methods that do not require the construction of a kernel. One such method is k-nearest neighbour [inverse distance weighting](https://en.wikipedia.org/wiki/Inverse_distance_weighting), which only requires non-negative distances which need not satisfy the triangle inequality (nor even need to be symmetric, I think). The following outlines this approach:
```
import numpy as np
#--------------------------------------------------------------------------------
# simulate data
total_classes = 10
sample_values = np.random.rand(total_classes)
distance_matrix = 100 * np.random.rand(total_classes, total_classes)
# Distances to the values itself are zero; hence remove diagonal.
distance_matrix -= np.diag(np.diag(distance_matrix))
# --------------------------------------------------------------------------------
# For each sample, compute an average based on the values of the k-nearest neighbors.
# Weigh each sample value by the inverse of the corresponding distance.
# Apply a regularizer to the distance matrix.
# This limits the influence of values with very small distances.
# In particular, this affects how the value of the sample itself (which has distance 0)
# is weighted w.r.t. other values.
regularizer = 1.
distance_matrix += regularizer
# Set number of neighbours to "interpolate" over.
k = 3
# Compute average based on sample value itself and k neighbouring values weighted by the inverse distance.
# The following assumes that the value of distance_matrix[ii, jj] corresponds to the distance from ii to jj.
for ii in range(total_classes):
# determine neighbours
indices = np.argsort(distance_matrix[ii, :])[:k+1] # +1 to include the value of the sample itself
# compute weights
distances = distance_matrix[ii, indices]
weights = 1. / distances
weights /= np.sum(weights) # weights need to sum to 1
# compute weighted average
values = sample_values[indices]
new_sample_values[ii] = np.sum(values * weights)
print(new_sample_values)
``` | 4,177 |
57,094,939 | I am wrote a serializer for the User model in Django with DRF:
the model:
```py
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.utils.translation import ugettext
class BaseModel(models.Model):
# all models should be inheritted from this model
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class User(AbstractBaseUser, BaseModel):
username = models.CharField(
ugettext('Username'), max_length=255,
db_index=True, unique=True
)
email = models.EmailField(
ugettext('Email'), max_length=255, db_index=True,
blank=True, null=True, unique=True
)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ('email', 'password',)
class Meta:
app_label = 'users'
```
the serializer:
```
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, user, validated_data):
user = super().update(user, validated_data)
user.set_password(validated_data['password'])
user.save()
return user
```
It works. But I probably do two calls instead of one on every create/update and the code looks a little bit weird(not DRY).
Is there an idiomatic way to do that?
```
$python -V
Python 3.7.3
Django==2.2.3
djangorestframework==3.10.1
``` | 2019/07/18 | [
"https://Stackoverflow.com/questions/57094939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907902/"
] | I hope this will solve the issue,
```
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
**return models.User.objects.create\_user(\*\*validated\_data)**
def update(self, user, validated_data):
**password = validated\_data.pop('password', None)
if password is not None:
user.set\_password(password)
for field, value in validated\_data.items():
setattr(user, field, value)
user.save()
return user**
```
The **`create_user()`** method uses the **`set_password()`** method to set the hashable password. | You can create your own user manager by overriding `BaseUserManager` and use `set_password()` method there. There is a full example in django's [documentation](https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#a-full-example). So your `models.py` will be:
```py
# models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class MyUserManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
class BaseModel(models.Model):
# all models should be inheritted from this model
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class User(AbstractBaseUser, BaseModel):
username = models.CharField(
ugettext('Username'), max_length=255,
db_index=True, unique=True
)
email = models.EmailField(
ugettext('Email'), max_length=255, db_index=True,
blank=True, null=True, unique=True
)
# don't forget to set your custom manager
objects = MyUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ('email', 'password',)
class Meta:
app_label = 'users'
```
Then, you can directly call `create_user()` in your serializer's `create()` method. You can also add a custom update method in your custom manager.
```py
# serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = models.User.objects.create_user(
username=validated_data['username'],
email=validated_data['email'],
password=validated_data['password']
)
return user
``` | 4,179 |
33,493,861 | I wrote script which create animation (movie) from fits files. One file has size 2.8 MB and the no. of files is 9000.
Here is code
```
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
import pyfits
import glob
import re
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
global numbers
numbers=re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
image_list=glob.glob('/kalib/*.fits')
image_list= sorted(image_list,key=numericalSort)
print image_list
fig = plt.figure("movie")
img = []
for i in range(0,len(image_list)):
hdulist = pyfits.open(image_list[i])
im = hdulist[0].data
img.append([plt.imshow(im,cmap=plt.cm.Greys_r)])
ani = animation.ArtistAnimation(fig,img, interval=20, blit=True,repeat_delay=0)
ani.save('movie.mp4', writer=writer)
```
I think that my problem is when I create array img[]...I have 8 GB RAM and when the RAM is full my operating system terminate python script.
My question is:
How I can read 9000 files and create animation? Is possible create some buffer or some parallel processing?
Any suggestion? | 2015/11/03 | [
"https://Stackoverflow.com/questions/33493861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2952470/"
] | I would recommend you to use `ffmpeg`. With the command `image2pipe` you don't have to load all the images into your RAM but rather one by one (i think) into a pipe.
In addition to that, `ffmpeg` allows you to manipulate the video (framerate, codec, format, etc...).
<https://ffmpeg.org/ffmpeg.html> | You might be better off creating your animation with FuncAnimation instead of ArtistAnimation, as explained in [ArtistAnimation vs FuncAnimation matplotlib animation matplotlib.animation](https://stackoverflow.com/questions/22158395/artistanimation-vs-funcanimation-matplotlib-animation-matplotlib-animation) FuncAnimation is more efficient in its memory usage. You might want to experiment with FuncAnimation's save\_count parameter as well, check out the API documentation for examples. | 4,180 |
50,438,762 | The code below is a basic square drawing using Turtle in python.
Running the code the first time works. But running the code again activates a Turtle window that is non-responsive and subsequently crashes every time.
The error message includes `raise Terminator` and `Terminator`
Restarting kernel in Spyder (Python 3.6 on a Dell Desktop) fixes the problem in that I can then run the code again successfully, but the root cause is a mystery?
[Link](https://stackoverflow.com/questions/48637723/python-drawing-in-turtle-window-says-not-responding) to another question that is similar but as yet unanswered.
Please +1 this question if you find it worthy of an answer!!
```
import turtle
bob = turtle.Turtle()
print(bob)
for i in range(4):
bob.fd(100)
bob.lt(90)
turtle.mainloop()
``` | 2018/05/20 | [
"https://Stackoverflow.com/questions/50438762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9655448/"
] | I realize this will seem wholly unsatisfactory, but I have found that creating the turtle with:
```
try:
tess = turtle.Turtle()
except:
tess = turtle.Turtle()
```
works (that is, eliminates the "working every other time" piece. I also start with
```
wn = turtle.Screen()
```
and end with
```
from sys import platform
if platform=='win32':
wn.exitonclick()
```
Without those parts, if I try to move the turtle graphics windows in Windows, things break. (running Spyder for Python 3.6 on a Windows machine)
edit: of course, OSX is perfectly happy without the exitonclick() command and unhappy with it so added platform specific version of ending "feature fix." The try...except part is still needed for OSX. | The module uses a class variable \_RUNNING which remains true between executions when running in spyder instead of running it as a self contained script. I have requested for the module to be updated.
Meanwhile, work around/working example beyond what DukeEgr93 has proposed
1)
```
import importlib
import turtle
importlib.reload(turtle)
bob = turtle.Turtle()
print(bob)
for i in range(4):
bob.fd(100)
bob.lt(90)
turtle.mainloop()
```
2.
```
import importlib
import turtle
turtle.TurtleScreen._RUNNING=True
bob = turtle.Turtle()
print(bob)
for i in range(4):
bob.fd(100)
bob.lt(90)
turtle.mainloop()
``` | 4,181 |
50,192,322 | this is my code the I am currently writing for a robot in my university project. This code works, however the loop will constantly print statements every second and I would like it to only print when I change the input condition (break the if condition), so it wouldn't keep on printing. Is there anyway to fix this? Thanks for the help in advance.
PS: this is in python 2.7 (I think)
```
try:
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
print ('moving backward with 25% speed')
# performing some actions
elif 0.25 < joystick.get_axis(1) <= 0.5:
print ('moving forward with 50% speed')
# performing some actions
elif 0.5 < joystick.get_axis(1) <= 0.75:
print ('moving backward with 75% speed')
# performing some actions
```
the while loop continues in the same fashion... | 2018/05/05 | [
"https://Stackoverflow.com/questions/50192322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9746251/"
] | Keep track of the last category - something like that.
```
previous_category = 0
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
if previous_category != 1:
print ('moving backward with 25% speed')
previous_category = 1
# performing some actions
elif 0.25 < joystick.get_axis(1) <= 0.5:
if previous_category != 2:
print ('moving forward with 50% speed')
previous_category = 2
# performing some actions
elif 0.5 < joystick.get_axis(1) <= 0.75:
if previous_category != 3:
print ('moving backward with 75% speed')
previous_category = 3
# performing some actions
```
If you're down for reformating your code a bit, I think this would be a better approach:
```
previous_category = 0
while True:
val = joystick.get_axis(1)
if 0.01 < val <= 0.25:
category = 1
#add 2 elif for the other categories, 2 and 3
if category == 1:
# performing some actions
elif category == 2:
# performing some actions
elif category == 3:
# performing some actions
#now that we've moved the object, we check if we need to print or not
if category != previous_category:
print_statement(category)
#and we update previous_category for the next round, which will just be the current category
previous_category = category
def print_statement(category):
#handle printing here based on type, this is more flexible
``` | You can accomplish this with a global integer that stores the last value printed. Something like this:
```
_last_count = None
def condprint(count):
global _last_count
if count != _last_count:
print('Waiting for joystick '+str(count))
_last_count = count
``` | 4,182 |
63,043,387 | I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index position in ID. So far I have this in a loop, but its very slow as my Data array is very large:
```
out = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out[i] = Values_Arr[ID_Arr==Data_Arr[I]]
```
is there a more pythonic way of doing this and avoiding this loop (doesn't have to use numpy)?
Actual data looks like:
```
Data_Arr = [ 852116 852116 852116 ... 1001816 1001816 1001816]
ID_Arr = [ 852116 852117 852118 ... 1001814 1001815 1001816]
Value_Arr = [1.5547194 1.5547196 1.5547197 ... 1.5536859 1.5536858 1.5536857]
```
shapes are:
```
Data_Arr = (4021165,)
ID_Arr = (149701,)
Value_Arr = (149701,)
``` | 2020/07/22 | [
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] | Since `ID_Arr` is sorted, we can directly use [`np.searchsorted`](https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html) and index `Value_Arr` with the result:
```
Value_Arr[np.searchsorted(ID_Arr, Data_Arr)]
array([0.1, 0.1, 0.1, 0.6, 0.6, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.8, 0.8,
0.2, 0.2, 0.2])
```
If `ID_Arr` isn't sorted (*note*: in case there may be out of bounds indices, we should remove them, see divakar's answer):
```
s_ind = ID_Arr.argsort()
ss = np.searchsorted(ID_Arr, Data_Arr, sorter=s_ind)
out = Value_Arr[s_ind[ss]]
```
---
Checking with the arrays suggested by alaniwi:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = array([2, 1, 3, 4, 5])
Value_Arr = np.array([0.6, 0.1, 0.3, 0.8, 0.2])
out_op = np.zeros_like(Data_Arr, dtype=np.float)
for i in range(len(Data_Arr)):
out_op[i] = Value_Arr[ID_Arr==Data_Arr[i]]
s_ind = ID_Arr.argsort()
ss = np.searchsorted(ID_Arr, Data_Arr, sorter=s_ind)
out_answer = Value_Arr[s_ind[ss]]
np.array_equal(out_op, out_answer)
#True
``` | Looks like you want:
```
out = Value_Arr[ID_Arr[Data_Arr - 1] - 1]
```
Note that the `- 1` are due to the fact that Python/Numpy is `0`-based index. | 4,183 |
33,761,993 | Here's what I'm doing, I'm web crawling for my personal use on a website to copy the text and put the chapters of a book on text format and then transform it with another program to pdf automatically to put it in my cloud. Everything is fine until this happens: special characters are not copying correctly, for example the accent is showed as: \xe2\x80\x99 on the text file and the - is showed as \xe2\x80\x93. I used this (Python 3):
```
for text in soup.find_all('p'):
texta = text.text
f.write(str(str(texta).encode("utf-8")))
f.write('\n')
```
Because since I had a bug when reading those characters and it just stopped my program, I encoded everything to utf-8 and retransform everything to string with python's method str()
I will post the whole code if anyone has a better solution to my problem, here's the part that crawl the website from page 1 to max\_pages, you can modify it on line 21 to get more or less chapters of the book:
```
import requests
from bs4 import BeautifulSoup
def crawl_ATG(max_pages):
page = 1
while page <= max_pages:
x= page
url = 'http://www.wuxiaworld.com/atg-index/atg-chapter-' + str(x) + "/"
source = requests.get(url)
chapter = source.content
soup = BeautifulSoup(chapter.decode('utf-8', 'ignore'), 'html.parser')
f = open('atg_chapter' + str(x) + '.txt', 'w+')
for text in soup.find_all('p'):
texta = text.text
f.write(str(str(texta).encode("utf-8")))
f.write('\n')
f.close
page +=1
crawl_ATG(10)
```
I will do the clean up of the first useless lines that are copied later when I get a solution to this problem. Thank you | 2015/11/17 | [
"https://Stackoverflow.com/questions/33761993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] | The easiest way to fix this problem that I found is adding `encoding= "utf-8"` in the open function:
```
with open('file.txt','w',encoding='utf-8') as file :
file.write('ñoño')
``` | The only error I can spot is,
```
str(texta).encode("utf-8")
```
In it, you are forcing a conversion to str and encoding it. It should be replaced with,
```
texta.encode("utf-8")
```
**EDIT:**
The error stems in the server not giving the correct encoding for the page. So `requests` assumes a `'ISO-8859-1'`. As noted in this [bug](https://github.com/kennethreitz/requests/issues/1604), it is a deliberate decision.
Luckily, `chardet` library correctly detects the `'utf-8'` encoding, so you can do:
```
source.encoding = source.apparent_encoding
chapter = source.text
```
And there won't be any need to manually decode the text in `chapter`, since `requests` uses it to decode the `content` for you. | 4,186 |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. J.
CA600802 JB March 20, 1978 9:02 PM
205 4 164
210 4 164
214 4 164
642 4 164
1 5 164
</pre>
</html>
``` | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw) | Quazi, this calls out for a regex, specifically `<pre>(.+?)(?:\d+\s+){3}` with the DOTALL flag enabled.
You can find out about how to use regex in Python at <http://docs.python.org/library/re.html> and if you do a lot of this sort of string extraction, you'll be very glad you did. Going over my provided regex piece-by-piece:
`<pre>` just directly matches the pre tag
`(.+?)` matches and captures any characters
`(?:\d+\s+){3}` matches against some numbers followed by some whitespace, three times in a row | 4,188 |
61,511,948 | I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = f'https://rubyrealms.com/user/{input}/'
async with aiohttp.request("GET", url, headers=HEADERS) as response:
if response.status == 200:
print("Site is working!")
content = await response.text()
soup = BeautifulSoup(content, "html.parser")
page = requests.get(url)
tree = html.fromstring(page.content)
stuff = tree.xpath('/html/body/div[4]/div/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p')
print(stuff)
else:
print(f"The request was invalid\nStatus code: {response.status}")
```
The website I am looking for is "https://rubyrealms.com/user/{input}/" where input is given while running h!rubyinfo USERNAME changing the link to <https://rubyrealms.com/user/username/>.
On the website what I want to get is their BIO which has an XPATH of
>
> `"//*[@id="content-wrap"]/div[3]/div[3]/div/div[2]/div[1]/div[2]/div/p"`
>
>
>
where the element is:
```
<p class="margin-none font-color">
Hey! My name is KOMKO190, you maybe know me from the forums or discord. I am a programmer, I know a bit of JavaScript, small portion of C++, Python and html/css. Mostly python. My user ID is 7364. ||| 5th owner of Space Helmet :) </p>
```
Any help on how I would **scrape** that? The only response my bot gives is "[]" | 2020/04/29 | [
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] | *How about the following, using .select() method*
```
from bs4 import BeautifulSoup
html = '<p class="margin-none font-color">Hey! My name is KOMKO190 :) </p>'
soup = BeautifulSoup(html, features="lxml")
element = soup.select('p.margin-none')[0]
print(element.text)
```
*Prints out*
>
>
> ```
> Hey! My name is KOMKO190 :)
>
> ```
>
> | ```
from bs4 import BeautifulSoup as bs
url = 'https://rubyrealms.com/user/username/'
session = requests.Session()
request = session.get(url=url)
if request.status_code == 200:
soup = bs(request.text, 'lxml')
print(soup.find('p', class_='margin-none font-color').text)
else:
print(request.status_code)
```
You need install
```
pip install lxml
pip install beautifulsoup4
``` | 4,193 |
48,136,092 | I installed the python module tabula-py which is apparently based on the Java version of tabula. When I try to run it I get an error saying that the wrong version of Java is installed, but when I check in system perferences on MacOS it says I've got the latest version (Version 8 update 151). On the github page it mentions that java has to be added to PATH, so I tried doing this from these instructions <http://www.baeldung.com/java-home-on-windows-7-8-10-mac-os-x-linux>, but it still says I've got version 1.6 installed.
```
java version "1.6.0_65"
Java(TM) SE Runtime Environment (build 1.6.0_65-b14-468-11M4833)
```
Any help would be appreciated to get the plugin working.
This is the error:
```
Exception in thread "main" java.lang.UnsupportedClassVersionError: technology/tabula/CommandLineApp : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
``` | 2018/01/07 | [
"https://Stackoverflow.com/questions/48136092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6670570/"
] | This answer on the github issues page fixed the problem. <https://github.com/chezou/tabula-py/issues/54>
```
sudo mv /usr/bin/java /usr/bin/java-1.6
sudo ln -s /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
``` | Probably You installed java in mutiple locations.
Typ in terminal
$ wich java
To check where is this java 6 located. Then maybe You will fiund out how to uninstall it from this location. | 4,196 |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
desired output:
```
11
12
25
32
64
```
May I know where I'm making mistake? | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
```
I would recommend using i and j instead of element and compare\_index.
Look at line 9. Why does that fix it? | Your algorithm is almost correct but
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake.
It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
element_list[element], element_list[mindex] = element_list[mindex], element_list[element]
for element in range(len(element_list)):
print(element_list[element])
selection_sort(my_list)
``` | 4,197 |
8,733,807 | >
> **Possible Duplicate:**
>
> [Is there a java equivalent of the python eval function?](https://stackoverflow.com/questions/7143343/is-there-a-java-equivalent-of-the-python-eval-function)
>
>
>
There is a String, something like `String str = "if a[0]=1 & a[1]=2"`. How to use this string in a real IF THEN expression? E.g.:
```
for (Integer[] a : myNumbers) {
if a[0]=1 & a[1]=2 { // Here I'd like to use the expression from str
//...
}
}
``` | 2012/01/04 | [
"https://Stackoverflow.com/questions/8733807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089623/"
] | Java isn't a scripting language that supports dynamic evaluation (although it does support script execution). I would challenge you to check to see if what you're attempting to do is being done in the right way within Java.
There are two common ways you can approach this, listed below. However they have a significant performance impact when it comes to the runtime of your application.
---
**Script Execution**
You could fire up a ScriptEngine, build a ScriptContext, execute the fragment in Javascript or some other language, and then read the result of the evaluation.
* <http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/>
---
**Parsing**
You could build a lexical parser that analyses the string and converts that into the operations you want to perform. In Java I would recommend you look at JFlex.
* <http://www.javaworld.com/javaworld/jw-01-1997/jw-01-indepth.html>
* <http://en.wikipedia.org/wiki/Lexical_analysis>
* <http://jflex.de/> | I don't think you can do what you're asking.
Also your java doesn't seem to make much sense. Something like this would make more sense:
```
for (Integer a : myNumbers) {
if (a.equals(Integer.valueOf(1))){
//...
}
}
```
You can however say:
```
if("hello".equals("world")){
//...
}
```
And you can build a string:
```
String str = "if "+a[0]+"=1 & "+a[1]+"=2"
```
And you can put that together and say:
```
String str = "if "+a[0]+"=1 & "+a[1]+"=2"
if(str.equals("if 1=1 & 2=2")){
//...
}
```
But I think you're probably just trying to do something the wrong way | 4,202 |
70,461,539 | I have created a list of dictionaries of named tuples, keyed with an event type.
```
[{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}]
```
What would be the most pythonic method to return/print results that only contain "approved=1", or "reviewed=1" and "approved=0"? | 2021/12/23 | [
"https://Stackoverflow.com/questions/70461539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713151/"
] | Also you can trigger a link by JavaScript.
```
<button
onclick="window.location(this.getAttribute('data-link'))"
data-link="/hello">go to hello</button>
``` | One way could be to use an anchor tag instead of the button and make it look like a button.
HTML:
```html
<div class="buttons">
<a class="btn custom-btn position-bottom-right"> Add to cart</a>
</div>
```
CSS:
```css
.custom-btn {
border: medium dashed green;
}
```
Alternatively, you could do:
```
<button class="btn custom-btn position-bottom-right" onclick="location.href='yourlink.com';"> Add to Cart </button>
``` | 4,203 |
72,335,222 | EDIT2:
------
A minimal demonstration is:
```
code = """\
a=1
def f1():
print(a)
print(f1.__closure__)
f1()
"""
def foo():
exec(code)
foo()
```
Which gives:
```
None
Traceback (most recent call last):
File "D:/workfiles/test_eval_rec.py", line 221, in <module>
foo()
File "D:/workfiles//test_eval_rec.py", line 219, in foo
exec(code)
File "<string>", line 5, in <module>
File "<string>", line 3, in f1
NameError: name 'a' is not defined
```
It can be seen that the `__closure__` attribute of function defined inside code str passed to `exec()` is `None`, making calling the function fails.
Why does this happen and how can I define a function successfully?
---
I find several questions that may be related.
1. [Closure lost during callback defined in exec()](https://stackoverflow.com/q/28950735/9758790)
2. [Using exec() with recursive functions](https://stackoverflow.com/q/871887/9758790)
3. [Why exec() works differently when invoked inside of function and how to avoid it](https://stackoverflow.com/q/55763182/9758790)
4. [Why are closures broken within exec?](https://stackoverflow.com/q/2749655/9758790)
5. [NameError: name 'self' is not defined IN EXEC/EVAL](https://stackoverflow.com/q/44603993/9758790)
These questions are all related to "defining a function insdie exec()". I think the fourth question here is closest to the essence of these problems. The common cause of these problems is that **when defining a function in exec(), the `__closure__` attribute of the function object can not be set correctly and will always be None.** However, many existing answers to this question didn't realize this point.
**Why these questions are caused by wrong `__closure__`:**
When defining a function, `__closure__` attribute is set to a dict that contains all local symbols (at the place where the keyword `def` is used) that is used inside the newly defined funtion. When calling a function, local symbol tables will be retrived from the `__closure__` attribute. Since the `__closure__` is set to `None`, the local symbol tables can not be retrived as expected, making the function call fail.
**These answers work by making None a correct `__closure__` attribute:**
Existing solutions to the questions listed above solve these problems by getting the function definition rid of the usage of local symbol, i.e, they make the local symbols used(variable, function definition) global by passing globals() as locals of `exec` or by using keyword `global` explicitly in the code string.
**Why existing solution unsatisfying:**
These solutions I think is just an escape of the core problem of setting `__closure__` correctly when define a functioni inside `exec()`. And as symbols used in the function definition is made global, these solutions will produce redundant global symbol which I don't want.
---
Original Questions:
-------------------
***(You May ignore this session, I have figured something out, and what I currently want to ask is described as the session EDIT2. The original question can be viewed as a sepecial case of the question described in session EDIT2)***
original title of this question is: Wrapping class function to new function with exec() raise NameError that ‘self’ is not defined
I want to wrap an existing member function to a new class function. However, exec() function failed with a NameError that ‘self’ is not defined.
I did some experiment with the following codes. I called globals() and locals() in the execed string, it seems that the locals() is different in the function definition scope when exec() is executed. **"self" is in the locals() when in exec(), however, in the function definition scope inside the exec(), "self" is not in the locals().**
```
class test_wrapper_function():
def __init__(self):
# first wrapper
def temp_func():
print("locals() inside the function definition without exec:")
print(locals())
return self.func()
print("locals() outside the function definition without exec:")
print(locals())
self.wrappered_func1 = temp_func
# third wrapper using eval
define_function_str = '''def temp_func():
print("locals() inside the function definition:")
print(locals())
print("globals() inside the function definition:")
print(globals())
return self.func()
print("locals() outside the function definition:")
print(locals())
print("globals() outside the function definition:")
print(globals())
self.wrappered_func2 = temp_func'''
exec(define_function_str)
# call locals() here, it will contains temp_func
def func(self):
print("hi!")
t = test_wrapper_function()
print("**********************************************")
t.wrappered_func1()
t.wrappered_func2()
```
I have read this [link](https://stackoverflow.com/q/37152671/9758790). *In the exec()*, memeber function, attribute of "self" can be accessed without problem, while *in the function difinition in the exec()*, "self" is not available any more. Why does this happen?
**Why I want to do this**:
I am building a PyQt program. I want to create several similar slots(). These slots can be generated by calling one member function with different arguments. I decided to generate these slots using exec() function of python. I also searched with the keyword "nested name scope in python exec", I found [this question](https://stackoverflow.com/q/44603993/9758790) may be related, but there is no useful answer.
To be more specific. I want to define a family of slots like `func_X` (X can be 'a', 'b', 'c'...), each do something like `self.do_something_on(X)`. Here, `do_something` is a member function of my QWidget. So I use a for loop to create these slots function. I used codes like this:
```
class MyWidget():
def __init__(self):
self.create_slots_family()
def do_something(self, character):
# in fact, this function is much more complex. Do some simplification.
print(character)
def create_slots_i(self, character):
# want to define a function like this:
# if character is 'C', define self.func_C such that self.func_C() works like self.do_something(C)
create_slot_command_str = "self.func_" + character + " = lambda:self.do_something('" + character + "')"
print(create_slot_command_str)
exec(create_slot_command_str)
def create_slots_family(self):
for c in ["A", "B", "C", "D"]:
self.create_slots_i(c)
my_widget = MyWidget()
my_widget.func_A()
```
Note that, as far as I know, the Qt slots should not accept any parameter, so I have to wrap `self.do_something(character)` to be a series function `self.func_A`, `self.func_C` and so on for all the possible characters.
So the above is what I want to do orignially.
EDIT1:
------
***(You May ignore this session, I have figured something out, and what I currently want to ask is described as the session EDIT2. This simplified version of original question can also be viewed as a sepecial case of the question described in session EDIT2)***
As @Mad Physicist suggested. I provide a simplified version here, deleting some codes used for experiments.
```
class test_wrapper_function():
def __init__(self):
define_function_str = '''\
def temp_func():
return self.func()
self.wrappered_func2 = temp_func'''
exec(define_function_str)
def func(self):
print("hi!")
t = test_wrapper_function()
t.wrappered_func2()
```
I expected this to print a "hi". However, I got the following exception:
```
Traceback (most recent call last):
File "D:/workfiles/test_eval_class4.py", line 12, in <module>
t.wrappered_func2()
File "<string>", line 2, in temp_func
NameError: name 'self' is not defined
``` | 2022/05/22 | [
"https://Stackoverflow.com/questions/72335222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9758790/"
] | **Using Exec**
You've already covered most of the problems and workarounds with `exec`, but I feel that there is still value in adding a summary.
The key issue is that `exec` only knows about `globals` and `locals`, but not about free variables and the non-local namespace. That is why the [docs](https://docs.python.org/3/library/functions.html#exec) say
>
> If exec gets two separate objects as *globals* and *locals*, the code will be executed as if it were embedded in a class definition.
>
>
>
There is no way to make it run as though it were in a method body. However, as you've already noted, you can make `exec` create a closure and use that instead of the internal namespace by adding a method body to your snippet. However, there are still a couple of subtle restrictions there.
Your example of what you are trying to do showcases the issues perfectly, so I will use a modified version of that. The goal is to make a method that binds to `self` and has a variable argument in the `exec` string.
```
class Test:
def create_slots_i(self, c):
create_slot_command_str = f"self.func_{c} = lambda: self.do_something('{c}')"
exec(create_slot_command_str)
def do_something(self, c):
print(f'I did {c}!')
```
There are different ways of getting `exec` to "see" variables: literals, globals, and internal closures.
1. **Literals**. This works robustly, but only for simple types that can be easily instantiated from a string. The usage of `c` above is a perfect example. This will not help you with a complex object like `self`:
```
>>> t = Test()
>>> t.create_slots_i('a')
>>> t.func_a()
...
NameError: name 'self' is not defined
```
This happens exactly because `exec` has no concept of free variables. Since `self` is passed to it via the default `locals()`, it does not bind the reference to a closure.
2. **globals**. You can pass in a name `self` to `exec` via `globals`. There are a couple of ways of doing this, each with its own issues. Remember that `globals` are accessed by a function through its [`__globals__` (look at the table under "Callable types")](https://docs.python.org/3/reference/datamodel.html) attribute. Normally `__globals__` refers to the `__dict__` of the module in which a function is defined. In `exec`, this is the case by default as well, since that's what `globals()` returns.
* **Add to `globals`**: You can create a global variable named `self`, which will make your problem go away, sort of:
```
>>> self = t
>>> t.func_a()
I did a!
```
But of course this is a house of cards that falls apart as soon as you delete, `self`, modify it, or try to run this on multiple instances:
```
>>> del self
>>> t.func_a()
...
NameError: name 'self' is not defined
```
* **Copy `globals`**. A much more versatile solution, on the surface of it, is to copy `globals()` when you run `exec` in `create_slots_i`:
```
def create_slots_i(self, c):
create_slot_command_str = f"self.func_{c} = lambda: self.do_something('{c}')"
g = globals().copy()
g['self'] = self
exec(create_slot_command_str, g)
```
This appears to work normally, and for a very limited set of cases, it actually does:
```
>>> t = Test()
>>> t.create_slots_i('a')
>>> t.func_a()
I did a!
```
But now, your function's `__globals__` attribute is no longer bound to the module you created it in. If it uses any other global values, especially ones that might change, you will not be able to see the changes. For limited functionality, this is OK, but in the general case, it can be a severe handicap.
3. **Internal Closures**. This is the solution you already hit upon, where you create a closure within the `exec` string to let it know that you have a free variable by artificial means. For example:
```
class Test:
def create_slots_i(self, c):
create_slot_command_str = f"""def make_func(self):
def func_{c}():
self.do_something('{c}')
return func_{c}
self.func_{c} = make_func(self)"""
g = globals().copy()
g['self'] = self
exec(create_slot_command_str, g)
def do_something(self, c):
print(f'I did {c}!')
```
This approach works completely:
```
>>> t = Test()
>>> t.create_slots_i('a')
>>> t.func_a()
I did a!
```
The only real drawbacks here are security, which is always a problem with `exec`, and the sheer awkwardness of this monstrosity.
**A Better Way**
Since you are already creating closures, there is really no need to use `exec` at all. In fact, the only thing you are really doing is creating methods so that `self.func_...` will bind the method for you, since you need a function with the signature of your slot and access to `self`. You can write a simple method that will generate functions that you can assign to your slots directly. The advantage of doing it this way is that (a) you avoid calling `exec` entirely, and (b) you don't need to have a bunch of similarly named auto-generated methods polluting your class namespace. The slot generator would look something like this:
```
def create_slots_i(self, c):
def slot_func():
self.do_something(c) # This is a real closure now
slot_func.__name__ = f'func_{c}'
return slot_func
```
Since you will not be referring to these function objects anywhere except your slots, `__name__` is the only way to get the "name" under which they were stored. That is the same thing that `def` does for you under the hood.
You can now assign slots directly:
```
some_widget.some_signal.connect(self.create_slots_i('a'))
```
**Note**
I originally had a more complex approach in mind for you, since I thought you cared about generating bound methods, instead of just setting `__name__`. In case you have a sufficiently complex scenario where it still applies, here is my original blurb:
A quick recap of the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html): when you bind a function with the dot operator, e.g., `t.func_a`, python looks at the class for descriptors with that name. If your class has a data descriptor (like `property`, but not functions), then that descriptor will shadow anything you may have placed in the instance `__dict__`. However, if you have a non-data descriptor (one a `__get__` method but without a `__set__` method, like a function object), then it will only be bound if an instance attribute does not shadow it. Once this decision has been made, actually invoking the descriptor protocol involves calling `type(t).func_a.__get__(t)`. That's how a bound method knows about `self`.
Now you can return a bound method from within your generator:
```
def create_slots_i(self, c):
def slot_func(self):
self.do_something(c) # This is a closure on `c`, but not on `self` until you bind it
slot_func.__name__ = f'func_{c}'
return slot_func.__get__(self)
``` | **Why this phenomena happen:**
Actually [the answer](https://stackoverflow.com/a/2749806/9758790) of the [question 4](https://stackoverflow.com/q/2749655/9758790) listed above can answer this question.
When call `exec()` on one code string, the code string is first compiled. I suppose that during compiling, the provided `globals` and `locals` is not considered. The symbol in the exec()ed code str is compiled to be in the globals. So the function defined in the code str will be considered using global variables, and thus `__closure__` is set to `None`.
Refer to [this answer](https://stackoverflow.com/a/29456463/9758790) for more information about what the func `exec` does.
---
**How to deal with this phenomena:**
*Imitating the solutions provided in the previous questions*, for the minimal demostration the question, it can also be modified this way to work:
```
a=1 # moving out of the variable 'code'
code = """\
def f1():
print(a)
print(f1.__closure__)
f1()
"""
def foo():
exec(code)
foo()
```
Although the `__closure__` is still `None`, the exception can be avoided because now only the global symbol is needed and `__closure__` should also be None if correctly set. You can read the part *The reason why the solutions work* in the question body for more information.
---
*This was originally added in [Revision 4](https://stackoverflow.com/revisions/72335222/4) of the question.* | 4,207 |
23,244,245 | I have developed an application which uses udisks version 1 to find and list details of connected USB drives. The details include device (/dev/sdb1...etc), mount point, and free space. However, I found that modern distros has udisks2 installed by default. Here is the little code found on the other SO thread:-
```
#!/usr/bin/python2.7
import dbus
bus = dbus.SystemBus()
ud_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2')
om = dbus.Interface(ud_manager_obj, 'org.freedesktop.DBus.ObjectManager')
for k,v in om.GetManagedObjects().iteritems():
drive_info = v.get('org.freedesktop.UDisks2.Drive', {})
if drive_info.get('ConnectionBus') == 'usb' and drive_info.get('Removable'):
if drive_info['MediaRemovable']:
print("Device Path: %s" % k)
```
It produces:-
`[sundar@arch ~]$ ./udisk2.py
Device Path: /org/freedesktop/UDisks2/drives/JetFlash_Transcend_8GB_GLFK4LYSFG3HZZ48`
The above result is fine but how can I connect `org.freedesktop.UDisks2.Block` and get properties of the devices?
<http://udisks.freedesktop.org/docs/latest/gdbus-org.freedesktop.UDisks2.Block.html> | 2014/04/23 | [
"https://Stackoverflow.com/questions/23244245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2221360/"
] | After lot of hit and trial, I could get what I wanted. Just posting it so that some one can benefit in the future. Here is the code:-
```
#!/usr/bin/python2.7
# coding: utf-8
import dbus
def get_usb():
devices = []
bus = dbus.SystemBus()
ud_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2')
om = dbus.Interface(ud_manager_obj, 'org.freedesktop.DBus.ObjectManager')
try:
for k,v in om.GetManagedObjects().iteritems():
drive_info = v.get('org.freedesktop.UDisks2.Block', {})
if drive_info.get('IdUsage') == "filesystem" and not drive_info.get('HintSystem') and not drive_info.get('ReadOnly'):
device = drive_info.get('Device')
device = bytearray(device).replace(b'\x00', b'').decode('utf-8')
devices.append(device)
except:
print "No device found..."
return devices
def usb_details(device):
bus = dbus.SystemBus()
bd = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/block_devices%s'%device[4:])
try:
device = bd.Get('org.freedesktop.UDisks2.Block', 'Device', dbus_interface='org.freedesktop.DBus.Properties')
device = bytearray(device).replace(b'\x00', b'').decode('utf-8')
print "printing " + device
label = bd.Get('org.freedesktop.UDisks2.Block', 'IdLabel', dbus_interface='org.freedesktop.DBus.Properties')
print 'Name od partition is %s'%label
uuid = bd.Get('org.freedesktop.UDisks2.Block', 'IdUUID', dbus_interface='org.freedesktop.DBus.Properties')
print 'UUID is %s'%uuid
size = bd.Get('org.freedesktop.UDisks2.Block', 'Size', dbus_interface='org.freedesktop.DBus.Properties')
print 'Size is %s'%uuid
file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties')
print 'Filesystem is %s'%file_system
except:
print "Error detecting USB details..."
```
The complete block device properties can be found here <http://udisks.freedesktop.org/docs/latest/gdbus-org.freedesktop.UDisks2.Block.html> | **Edit**
Note that the `Block` object does not have `ConnectionBus` or `Removable` properties. You will have to change the code to remove references to `Drive` object properties for the code to work.
**/Edit**
If you want to connect to `Block`, not `Drive`, then instead of
```
drive_info = v.get('org.freedesktop.UDisks2.Drive', {})
```
try
```
drive_info = v.get('org.freedesktop.UDisks2.Block', {})
```
Then you can iterate through `drive_info` and output it's properties. For example, to get the `Id` property, you could:
```
print("Id: %s" % drive_info['Id'])
```
I'm sure that there is a nice pythonic way to iterate through all the property key/value pairs and display the values, but I'll leave that to you. Key being `'Id'` and value being the string stored in `drive_info['Id']`. Good luck | 4,209 |
61,448,722 | I have a python function that outputs/prints the following:
```
['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net', 'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net', 'CN=intranet.something111.net, 'OU=PositiveSSL Multi-Domain, CN=something99.net', 'OU=Domain Control Validated, CN=intranet.something66.net',...etc]
```
I am trying to extract all the sub-domain names between "CN=" and the single quotation mark, using the split() method in python. I've tried `split('CN=', 1)[0]` but i can't get my head around on how to use it
what i want to print out:
```
['something1.net', 'something2.net', 'something4.net', 'intranet.something111.net', 'intranet.something66.net']
```
Any help would be gratefully appreciated :-)
Thanks, MJ | 2020/04/26 | [
"https://Stackoverflow.com/questions/61448722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3704597/"
] | The last single quote is indicating the end of the string, so it seems you just want everything after `CN=`. Assuming that's the case, you can just chop off the first three characters:
```
subdomains = [item[3:] for item in my_list if item.startswith('CN=')]
``` | Here is a more readable code that extracts the subdomains in more clean or better way;
@tzaman code didn't really give me subdomains.
```
myDirtyDomains = ['CN=*.something1.net', 'CN=*.something2.net', 'CN=*.something4.net',\
'CN=something6.net', 'CN=something8.net', 'CN=intranet.something89.net',\
'CN=intranet.something111.net', 'OU=PositiveSSL Multi-Domain', \
'CN=something99.net', 'OU=Domain Control Validated', 'CN=intranet.something66.net']
cleanSubDomainsList = []
for item in myDirtyDomains:
countDots = item.count(".")
if countDots == 2:
host = item.partition('CN=')[2]
subdomain = host.partition('.')[0]
cleanSubDomainsList.append(subdomain)
print(cleanSubDomainsList)
``` | 4,210 |
50,283,776 | I am writing a python script and i want to execute some code only if the python script is being run directly from terminal and not from any another script.
How to do this in Ubuntu without using any extra command line arguments .?
The answer in here **DOESN't WORK**:
[Determine if the program is called from a script in Python](https://stackoverflow.com/questions/29239698/python-determine-if-the-program-is-called-from-a-script)
Here's my directory structure
`home
|-testpython.py
|-script.sh`
### script.py contains
```
./testpython.py
```
when I run `./script.sh` i want one thing to happen .
when I run `./testpython.py` directly from terminal without calling the "script.sh" i want something else to happen .
how do i detect such a difference in the calling way . Getting the parent process name always returns "bash" itself . | 2018/05/11 | [
"https://Stackoverflow.com/questions/50283776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6665568/"
] | You should probably be using command-line arguments instead, but this *is* doable. Simply check if the current process is the process group leader:
```
$ sh -c 'echo shell $$; python3 -c "import os; print(os.getpid.__name__, os.getpid()); print(os.getpgid.__name__, os.getpgid(0)); print(os.getsid.__name__, os.getsid(0))"'
shell 17873
getpid 17874
getpgid 17873
getsid 17122
```
Here, `sh` is the process group leader, and `python3` is a process in that group because it is forked from `sh`.
Note that all processes in a pipeline are in the same process group and the leftmost is the leader. | I recommend using command-line arguments.
**script.sh**
```sh
./testpython.py --from-script
```
**testpython.py**
```
import sys
if "--from-script" in sys.argv:
# From script
else:
# Not from script
``` | 4,212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.