qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
22,385,108
On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`). However I can't seem to find the logical or (`or`). The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi...
2014/03/13
[ "https://Stackoverflow.com/questions/22385108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595865/" ]
It's not possible: ------------------ [This can explicitly be found in the docs](http://docs.python.org/2/reference/expressions.html#boolean-operations): > > The expression x or y first evaluates x; if x is true, its value is > returned; otherwise, y is evaluated and the resulting value is > returned. > > > It...
The reason you are getting `1` after executing `>>> 1 or 2` is because `1` is `true` so the expression has been satisfied. It might make more sense if you try executing `>>> 0 or 2`. It will return `2` because the first statement is `0` or `false` so the second statement gets evaluated. In this case `2` evaluates to ...
22,385,108
On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`). However I can't seem to find the logical or (`or`). The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi...
2014/03/13
[ "https://Stackoverflow.com/questions/22385108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595865/" ]
The closest thing to a built-in `or` function is [any](http://docs.python.org/2.7/library/functions.html#any): ``` >>> any((1, 2)) True ``` If you wanted to duplicate `or`'s functionality of returning non-boolean operands, you could use [next](http://docs.python.org/2.7/library/functions.html#next) with a filter: `...
It's not possible: ------------------ [This can explicitly be found in the docs](http://docs.python.org/2/reference/expressions.html#boolean-operations): > > The expression x or y first evaluates x; if x is true, its value is > returned; otherwise, y is evaluated and the resulting value is > returned. > > > It...
12,866,612
I need to get distribute version 0.6.28 running on Heroku. I updated my requirements.txt, but that seems to have no effect. I'm trying to install from a module from a tarball that required this later version of the distribute package. During deploy I only get this: ``` Running setup.py egg_info for package from...
2012/10/12
[ "https://Stackoverflow.com/questions/12866612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/591222/" ]
Ok, here's a solution that does work for the moment. Long-term fix I think is Heroku upgrading their version of distribute. 1. Fork the python buildpack: <https://github.com/heroku/heroku-buildpack-python/> 2. Add the requirements you need to the pack (I put them in bin/compile, just before the other pip install requi...
Try adding distribute with the specific version to your dependencies on a first push, then adding the required dependency. ``` cat requirements.txt ... distribute==0.6.28 ... git push heroku master ... cat requirements.txt ... your deps here ```
37,192,957
I have a numpy and a boolean array: ``` nparray = [ 12.66 12.75 12.01 13.51 13.67 ] bool = [ True False False True True ] ``` I would like to replace all the values in `nparray` by the same value divided by 3 where `bool` is False. I am a student, and I'm reasonably new to python indexing. Any advice or suggest...
2016/05/12
[ "https://Stackoverflow.com/questions/37192957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6141885/" ]
naming an array bool might not be the best idea. As ayhan did try renaming it to bl or something else. You can use numpy.where see the docs [here](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html) ``` nparray2 = np.where(bl == False, nparray/3, nparray) ```
Use [`boolean indexing`](http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays) with `~` as the negation operator: ``` arr = np.array([12.66, 12.75, 12.01, 13.51, 13.67 ]) bl = np.array([True, False, False, True ,True]) arr[~bl] = arr[~bl] / 3 array([ 12.66 , 4.25 ,...
37,192,957
I have a numpy and a boolean array: ``` nparray = [ 12.66 12.75 12.01 13.51 13.67 ] bool = [ True False False True True ] ``` I would like to replace all the values in `nparray` by the same value divided by 3 where `bool` is False. I am a student, and I'm reasonably new to python indexing. Any advice or suggest...
2016/05/12
[ "https://Stackoverflow.com/questions/37192957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6141885/" ]
Use [`boolean indexing`](http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays) with `~` as the negation operator: ``` arr = np.array([12.66, 12.75, 12.01, 13.51, 13.67 ]) bl = np.array([True, False, False, True ,True]) arr[~bl] = arr[~bl] / 3 array([ 12.66 , 4.25 ,...
With just python you can do it like this: ``` nparray = [12.66, 12.75, 12.01, 13.51, 13.67] bool = [True, False, False, True, True] map(lambda x, y: x if y else x/3.0, nparray, bool) ``` And the result is: ``` [12.66, 4.25, 4.003333333333333, 13.51, 13.67] ```
37,192,957
I have a numpy and a boolean array: ``` nparray = [ 12.66 12.75 12.01 13.51 13.67 ] bool = [ True False False True True ] ``` I would like to replace all the values in `nparray` by the same value divided by 3 where `bool` is False. I am a student, and I'm reasonably new to python indexing. Any advice or suggest...
2016/05/12
[ "https://Stackoverflow.com/questions/37192957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6141885/" ]
naming an array bool might not be the best idea. As ayhan did try renaming it to bl or something else. You can use numpy.where see the docs [here](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html) ``` nparray2 = np.where(bl == False, nparray/3, nparray) ```
With just python you can do it like this: ``` nparray = [12.66, 12.75, 12.01, 13.51, 13.67] bool = [True, False, False, True, True] map(lambda x, y: x if y else x/3.0, nparray, bool) ``` And the result is: ``` [12.66, 4.25, 4.003333333333333, 13.51, 13.67] ```
38,638,180
Running interpreter ``` >>> x = 5000 >>> y = 5000 >>> print(x is y) False ``` running the same in script using `python test.py` returns `True` What the heck?
2016/07/28
[ "https://Stackoverflow.com/questions/38638180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3337819/" ]
You need to use the [EnhancedPatternLayout](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/EnhancedPatternLayout.html) then you can use the `{GMT+0}` specifier as per documentation. If you instead you want to run your application in UTC timezone, you can add the following JVM parameter : ``` -Duser.ti...
``` log4j.appender.A1.layout=org.apache.log4j.EnhancedPatternLayout log4j.appender.A1.layout.ConversionPattern=[%d{ISO8601}{GMT}] %-4r [%t] %-5p %c %x - %m%n ```
64,926,963
I used the official docker image of flask. And installed the rpi.gpio library in the container ``` pip install rpi.gpio ``` It's succeeded: ``` root@e31ba5814e51:/app# pip install rpi.gpio Collecting rpi.gpio Downloading RPi.GPIO-0.7.0.tar.gz (30 kB) Building wheels for collected packages: rpi.gpio Building whe...
2020/11/20
[ "https://Stackoverflow.com/questions/64926963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12192583/" ]
You need to close the second file. You were missing the () at the end of `f2.close` so the close method actually won't have been executed. In the example below, I am using `with` which creates a context manager to automatically close the file. ``` with open('BestillingNr.txt', 'r') as f: bestillingNr = int(f.read...
after this line `f2.write(f'{str(bestillingNr)}')`, you should add flush command `f2.flush()` This code is work well: ``` f = open('BestillingNr.txt', 'r') bestillingNr = int(f.read()) f.close() bestillingNr += 1 f2 = open('BestillingNr.txt', 'w') f2.write(f'{str(bestillingNr)}') f2.flush() f2.close() ```
10,505,851
I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below. I want to find a way ...
2012/05/08
[ "https://Stackoverflow.com/questions/10505851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932278/" ]
It's called Inheritence. Consider the following code: ``` class Complex { public function complex() { /* Complex Function */ } public function simple() { /* Already simple function */ } } class SimplifiedComplex extends Complex { public function complex() { /* Simplify Here */ } } ``` The `simple()` met...
Depending on your use case, you might want to create a facade in front of some of the functionality in complex class by delegating (Option 1), and instead of providing support for the rest of the functionality in complex class, you provide means to access complex class directly (getComplexClass). This might make the d...
10,505,851
I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below. I want to find a way ...
2012/05/08
[ "https://Stackoverflow.com/questions/10505851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932278/" ]
It's called Inheritence. Consider the following code: ``` class Complex { public function complex() { /* Complex Function */ } public function simple() { /* Already simple function */ } } class SimplifiedComplex extends Complex { public function complex() { /* Simplify Here */ } } ``` The `simple()` met...
This is ugly in Java, but you can write a function that takes the name of the method you want to call, and a parameter list, and use reflection to find the appropriate method to call. This will be conceptually similar to how you'd do it in Python, except much uglier.
10,505,851
I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below. I want to find a way ...
2012/05/08
[ "https://Stackoverflow.com/questions/10505851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932278/" ]
I think you've already called it. I would go with Option 1. It provides the most flexibility given the rigidity of java. I prefer it because it favors composition over inheritance. Although this creates more code, I find designs like this generally are easier to modify in the long run. Inheritance should only be used...
Depending on your use case, you might want to create a facade in front of some of the functionality in complex class by delegating (Option 1), and instead of providing support for the rest of the functionality in complex class, you provide means to access complex class directly (getComplexClass). This might make the d...
10,505,851
I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below. I want to find a way ...
2012/05/08
[ "https://Stackoverflow.com/questions/10505851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/932278/" ]
I think you've already called it. I would go with Option 1. It provides the most flexibility given the rigidity of java. I prefer it because it favors composition over inheritance. Although this creates more code, I find designs like this generally are easier to modify in the long run. Inheritance should only be used...
This is ugly in Java, but you can write a function that takes the name of the method you want to call, and a parameter list, and use reflection to find the appropriate method to call. This will be conceptually similar to how you'd do it in Python, except much uglier.
26,747,308
I have a Python script, say `myscript.py`, that uses relative module imports, ie `from .. import module1`, where my project layout is as follows: ``` project + outer_module - __init__.py - module1.py + inner_module - __init__.py - myscript.py - myscript.sh ``` And I have a Bash script, say `...
2014/11/04
[ "https://Stackoverflow.com/questions/26747308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1884158/" ]
You want to create a custom filter. It can be done very easily. This filter will test the name of your friend against the search. If ``` app.filter('filterFriends', function() { return function(friends, search) { if (search === "") return friends; return friends.filter(function(friend) { ...
I think it would be easier to just do: ``` <tr ng-repeat="friend in friends" ng-show="([friend] | filter:search).length > 0"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> ``` Also this way the filter will apply to all the properties, not just name.
55,374,909
I am new in python so I'm trying to read a csv with 700 lines included a header, and get a list with the unique values of the first csv column. Sample CSV: ``` SKU;PRICE;SUPPLIER X100;100;ABC X100;120;ADD X101;110;ABV X102;100;ABC X102;105;ABV X100;119;ABG ``` I used the example here [How to create a list in Pyt...
2019/03/27
[ "https://Stackoverflow.com/questions/55374909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A solution using pandas. You'll need to call the `unique` method on the correct column, this will return a pandas series with the unique values in that column, then convert it to a list using the `tolist` method. An example on the `SKU` column below. ``` import pandas as pd df = pd.read_csv('final_csv.csv', sep=";...
A solution using neither `pandas` nor `csv` : ```py lines = open('file.csv', 'r').read().splitlines()[1:] col0 = [v.split(';')[0] for v in lines] uniques = filter(lambda x: col0.count(x) == 1, col0) ``` or, using `map` (but less readable) : ```py col0 = list(map(lambda line: line.split(';')[0], open('file.csv', ...
55,374,909
I am new in python so I'm trying to read a csv with 700 lines included a header, and get a list with the unique values of the first csv column. Sample CSV: ``` SKU;PRICE;SUPPLIER X100;100;ABC X100;120;ADD X101;110;ABV X102;100;ABC X102;105;ABV X100;119;ABG ``` I used the example here [How to create a list in Pyt...
2019/03/27
[ "https://Stackoverflow.com/questions/55374909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want the unique values of the first column, you could modify your code to use a `set` instead of a `list`. Maybe like this: ``` import collections import csv filename = 'final_csv.csv' sku_list = [] with open(filename, 'r', encoding='utf-8') as f: csv_reader = csv.reader(f, delimiter=";") for i, row i...
A solution using neither `pandas` nor `csv` : ```py lines = open('file.csv', 'r').read().splitlines()[1:] col0 = [v.split(';')[0] for v in lines] uniques = filter(lambda x: col0.count(x) == 1, col0) ``` or, using `map` (but less readable) : ```py col0 = list(map(lambda line: line.split(';')[0], open('file.csv', ...
42,854,598
If I reset the index of my pandas DataFrame with "inplace=True" (following [the documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html)) it returns a class 'NoneType'. If I reset the index with "inplace=False" it returns the DataFrame with the new index. Why? ``` print(typ...
2017/03/17
[ "https://Stackoverflow.com/questions/42854598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6421290/" ]
Ok, now I understand, thanks for the comments! So inplace=True should return None **and** make the change in the original object. It seemed that on listing the dataframe again, no changes were present. But of course I should not have **assigned the return value** to the dataframe, i.e. ``` testDataframe = testDatafr...
inplace=True is always changed in the original data\_frame. If you want a changed data\_frame then remove second parameter i.e `inplace = True` ``` new_data_frame = testDataframe.set_index(['Codering']) ``` Then ``` print(new_data_frame) ```
32,303,006
I need to compute the integral of the following function within ranges that start as low as `-150`: ``` import numpy as np from scipy.special import ndtr def my_func(x): return np.exp(x ** 2) * 2 * ndtr(x * np.sqrt(2)) ``` The problem is that this part of the function ``` np.exp(x ** 2) ``` tends toward infi...
2015/08/31
[ "https://Stackoverflow.com/questions/32303006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2623899/" ]
I think a combination of @askewchan's solution and [`scipy.special.log_ndtr`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.log_ndtr.html) will do the trick: ``` from scipy.special import log_ndtr _log2 = np.log(2) _sqrt2 = np.sqrt(2) def my_func(x): return np.exp(x ** 2) * 2 * ndtr(x * np.sq...
Not sure how helpful will this be, but here are a couple of thoughts that are too long for a comment. You need to calculate the integral of [![2 \cdot e^{x^2} \cdot f(\sqrt{2}x)](https://i.stack.imgur.com/Tt5t4.gif)](https://i.stack.imgur.com/Tt5t4.gif), which you [correctly identified](http://docs.scipy.org/doc/scipy...
32,303,006
I need to compute the integral of the following function within ranges that start as low as `-150`: ``` import numpy as np from scipy.special import ndtr def my_func(x): return np.exp(x ** 2) * 2 * ndtr(x * np.sqrt(2)) ``` The problem is that this part of the function ``` np.exp(x ** 2) ``` tends toward infi...
2015/08/31
[ "https://Stackoverflow.com/questions/32303006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2623899/" ]
There already is such a function: [`erfcx`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.erfcx.html). I think `erfcx(-x)` should give you the integrand you want (note that `1+erf(x)=erfc(-x)`).
Not sure how helpful will this be, but here are a couple of thoughts that are too long for a comment. You need to calculate the integral of [![2 \cdot e^{x^2} \cdot f(\sqrt{2}x)](https://i.stack.imgur.com/Tt5t4.gif)](https://i.stack.imgur.com/Tt5t4.gif), which you [correctly identified](http://docs.scipy.org/doc/scipy...
46,409,846
I am trying to implement `Kmeans` algorithm in python which will use `cosine distance` instead of euclidean distance as distance metric. I understand that using different distance function can be fatal and should done carefully. Using cosine distance as metric forces me to change the average function (the average in...
2017/09/25
[ "https://Stackoverflow.com/questions/46409846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8671126/" ]
So it turns out you can just normalise X to be of unit length and use K-means as normal. The reason being if X1 and X2 are unit vectors, looking at the following equation, the term inside the brackets in the last line is cosine distance. [![vect_dist](https://i.stack.imgur.com/7amCq.png)](https://i.stack.imgur.com/7amC...
Unfortunately no. Sklearn current implementation of k-means only uses Euclidean distances. The reason is K-means includes calculation to find the cluster center and assign a sample to the closest center, and Euclidean only have the meaning of the center among samples. If you want to use K-means with cosine distance...
46,409,846
I am trying to implement `Kmeans` algorithm in python which will use `cosine distance` instead of euclidean distance as distance metric. I understand that using different distance function can be fatal and should done carefully. Using cosine distance as metric forces me to change the average function (the average in...
2017/09/25
[ "https://Stackoverflow.com/questions/46409846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8671126/" ]
You can normalize your data and then use KMeans. ``` from sklearn import preprocessing from sklearn.cluster import KMeans kmeans = KMeans().fit(preprocessing.normalize(X)) ```
Unfortunately no. Sklearn current implementation of k-means only uses Euclidean distances. The reason is K-means includes calculation to find the cluster center and assign a sample to the closest center, and Euclidean only have the meaning of the center among samples. If you want to use K-means with cosine distance...
46,409,846
I am trying to implement `Kmeans` algorithm in python which will use `cosine distance` instead of euclidean distance as distance metric. I understand that using different distance function can be fatal and should done carefully. Using cosine distance as metric forces me to change the average function (the average in...
2017/09/25
[ "https://Stackoverflow.com/questions/46409846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8671126/" ]
So it turns out you can just normalise X to be of unit length and use K-means as normal. The reason being if X1 and X2 are unit vectors, looking at the following equation, the term inside the brackets in the last line is cosine distance. [![vect_dist](https://i.stack.imgur.com/7amCq.png)](https://i.stack.imgur.com/7amC...
You can normalize your data and then use KMeans. ``` from sklearn import preprocessing from sklearn.cluster import KMeans kmeans = KMeans().fit(preprocessing.normalize(X)) ```
73,326,374
I want to solve NP-hard combinatorial optimization problem using quantum optimization.In this regard, I am using "classiq" python library, which a high level API for making hardware compatible quantum circuits, with IBMQ backend. To use "classiq", you have to first do the authentication of your machine (according to t...
2022/08/11
[ "https://Stackoverflow.com/questions/73326374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17990100/" ]
Prepared statement escaped the parameters: ```java private final String insertSQL = "INSERT INTO demo2 (contract_nr, name, surname, address, tel, date_of_birth, license_nr, nationality, driver1, driver2, pickup_date, drop_date, renting_days, pickup_time, drop_time, price, included_km, effected_km, mail, type, valid, c...
The answer to this question is that we do not need `'` around `?` in insert sql. This is wrong: ``` private final String insertSQL = "INSERT INTO demo2 (contract_nr, name, surname, address, tel, date_of_birth, license_nr, nationality, driver1, driver2, pickup_date, drop_date, renting_days, pickup_time, drop_time, pri...
63,532,068
I have my python3 path under `/usr/bin`, any my pip path under `/.local/bin` of my local repository. With some pip modules installed, I can run my code successfully through `python3 mycode.py`. But I tried to run the shell script: ``` #!/usr/bin echo "starting now..." nohup python3 mycode.py > log.txt 2>&1 & echo $! ...
2020/08/22
[ "https://Stackoverflow.com/questions/63532068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9207332/" ]
Just use: ``` msgbox Range("B1:B19").SpecialCells(xlCellTypeBlanks).Address ```
This solution adapts your code. ``` Dim cell As Range Dim emptyStr As String emptyStr = "" For Each cell In Range("B1:B19") If IsEmpty(cell) Then _ emptyStr = emptyStr & cell.Address(0, 0) & ", " Next cell If emptyStr <> "" Then MsgBox Left(emptyStr, Len(emptyStr) - 2) ``` If the `cell` is empty, it st...
63,532,068
I have my python3 path under `/usr/bin`, any my pip path under `/.local/bin` of my local repository. With some pip modules installed, I can run my code successfully through `python3 mycode.py`. But I tried to run the shell script: ``` #!/usr/bin echo "starting now..." nohup python3 mycode.py > log.txt 2>&1 & echo $! ...
2020/08/22
[ "https://Stackoverflow.com/questions/63532068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9207332/" ]
Just use: ``` msgbox Range("B1:B19").SpecialCells(xlCellTypeBlanks).Address ```
Please try this code. ``` Sub ListEmptyCells() Dim Rng As Range Dim List As Variant Dim Txt As String Set Rng = Range("B1:B19") On Error Resume Next List = Rng.SpecialCells(xlCellTypeBlanks).Address(0, 0) If Err Then Txt = "There are no empty cells in" & vbCr & _ ...
63,532,068
I have my python3 path under `/usr/bin`, any my pip path under `/.local/bin` of my local repository. With some pip modules installed, I can run my code successfully through `python3 mycode.py`. But I tried to run the shell script: ``` #!/usr/bin echo "starting now..." nohup python3 mycode.py > log.txt 2>&1 & echo $! ...
2020/08/22
[ "https://Stackoverflow.com/questions/63532068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9207332/" ]
Just use: ``` msgbox Range("B1:B19").SpecialCells(xlCellTypeBlanks).Address ```
Find Blank Cells Using 'SpecialCells' ------------------------------------- * The 2nd Sub (`listBlanks`) is the main Sub. * The 1st Sub shows how to use the main Sub. * The 3rd Sub shows how `SpecialCells` works, which on one hand might be considered unreliable or on the other hand could be used to one's advantage. * ...
63,532,068
I have my python3 path under `/usr/bin`, any my pip path under `/.local/bin` of my local repository. With some pip modules installed, I can run my code successfully through `python3 mycode.py`. But I tried to run the shell script: ``` #!/usr/bin echo "starting now..." nohup python3 mycode.py > log.txt 2>&1 & echo $! ...
2020/08/22
[ "https://Stackoverflow.com/questions/63532068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9207332/" ]
Just use: ``` msgbox Range("B1:B19").SpecialCells(xlCellTypeBlanks).Address ```
**List blanks via dynamic arrays and spill range reference** Using the new dynamic array possibilities of **Microsoft 365** (writing e.g. to target `C1:C?` in section `b)`) ``` =$B$1:$B$19="" ``` and a so called ►**spill range** reference (as argument in the function `Textjoin()`, vers. 2019+ in section `c)`) ...
52,302,767
In my pc, how can i listen incoming connection as a DLNA server? On my TV there is the possibility for get media from a DLNA server, i would write a simple python script that grant access at TV to my files. The ends are: * LG webOS smartTV * macOS
2018/09/12
[ "https://Stackoverflow.com/questions/52302767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954551/" ]
One project I've found is Cohen3. Does not look as too much alive, but at least supports Python version 3: <https://github.com/opacam/Cohen3> There's also a Coherence project (it seems Cohen3 is somehow derived from it, not sure): <https://gitlab.digitalcourage.de/coherence>
There is already server app doing it [Serviio](http://serviio.org/) I already using this on windows 10 and raspberry pi 2 and 3 and it works well, easy to setup by web app and you'll save a time with making your own solution.
10,496,649
Continued from [How to use wxSpellCheckerDialog in Django?](https://stackoverflow.com/questions/10474971/how-to-use-wxspellcheckerdialog-python-django/10476811#comment13562681_10476811) I have added spell checking to Django application using pyenchant. It works correctly when first run. But when I call it again (or a...
2012/05/08
[ "https://Stackoverflow.com/questions/10496649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1110394/" ]
You don't need wxPython to use pyEnchant. And you certainly shouldn't be using wx stuff with django. wxPython is for desktop GUIs, while django is a web app framework. As "uhz" pointed out, you can't call wxPython methods outside the main thread that wxPython runs in unless you use its threadsafe methods, such as wx.Ca...
It seems you are trying to use wx controls from inside Django code, is that correct? If so you are doing a very weird thing :) When you write a GUI application with wxPython there is one main thread which can process Window messages - the main thread is defined as the one where wx.App was created. You are trying to do...
55,585,079
I tried running this code in TensorFlow 2.0 (alpha): ```py import tensorflow_hub as hub @tf.function def elmo(texts): elmo_module = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True) return elmo_module(texts, signature="default", as_dict=True) embeds = elmo(tf.constant(["the cat is on the mat", ...
2019/04/09
[ "https://Stackoverflow.com/questions/55585079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38626/" ]
In Tensorflow 2.0 you should be using `hub.load()` or `hub.KerasLayer()`. **[April 2019]** - For now only Tensorflow 2.0 modules are loadable via them. In the future many of 1.x Hub modules should be loadable as well. For the 2.x only modules you can see examples in the notebooks created for the modules [here](https:...
this function load will work with tensorflow 2 ``` embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder-large/3") ``` instead of ``` embed = hub.Module("https://tfhub.dev/google/universal-sentence-encoder-large/3") ``` [this is not accepted in tf2] use hub.load()
55,585,079
I tried running this code in TensorFlow 2.0 (alpha): ```py import tensorflow_hub as hub @tf.function def elmo(texts): elmo_module = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True) return elmo_module(texts, signature="default", as_dict=True) embeds = elmo(tf.constant(["the cat is on the mat", ...
2019/04/09
[ "https://Stackoverflow.com/questions/55585079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38626/" ]
In Tensorflow 2.0 you should be using `hub.load()` or `hub.KerasLayer()`. **[April 2019]** - For now only Tensorflow 2.0 modules are loadable via them. In the future many of 1.x Hub modules should be loadable as well. For the 2.x only modules you can see examples in the notebooks created for the modules [here](https:...
**January 2021** To use a model from TF Hub, including ELMO e.g., with tensorflow 2.x load and unpack a model locally: ``` cd ~/tfhub/elmo3 model_link='https://tfhub.dev/google/elmo/3' model_link=$model_link'?tf-hub-format=compressed' wget $model_link -O model tar xvzf model rm model ``` Then use `hub.load()`: ```...
16,138,090
What is the most efficient and portable way to generate a random random in `[0,1]` in Cython? One approach is to use `INT_MAX` and `rand()` from the C library: ``` from libc.stdlib cimport rand cdef extern from "limits.h": int INT_MAX cdef float randnum = rand() / float(INT_MAX) ``` Is it OK to use `INT_MAX` in ...
2013/04/22
[ "https://Stackoverflow.com/questions/16138090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The C standard says `rand` returns an `int` in the range 0 to RAND\_MAX inclusive, so dividing it by RAND\_MAX (from `stdlib.h`) is the proper way to normalise it. In practice, RAND\_MAX will almost always be equal to MAX\_INT, but don't rely on that. Because `rand` has been part of ISO C since C89, it's guaranteed to...
'c' stdlib rand() returns a number between 0 and RAND\_MAX which is generally 32767. Is there any reason not to use the python random() ? [Generate random integers between 0 and 9](https://stackoverflow.com/questions/3996904/python-generate-random-integers-between-0-and-9)
16,138,090
What is the most efficient and portable way to generate a random random in `[0,1]` in Cython? One approach is to use `INT_MAX` and `rand()` from the C library: ``` from libc.stdlib cimport rand cdef extern from "limits.h": int INT_MAX cdef float randnum = rand() / float(INT_MAX) ``` Is it OK to use `INT_MAX` in ...
2013/04/22
[ "https://Stackoverflow.com/questions/16138090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The C standard says `rand` returns an `int` in the range 0 to RAND\_MAX inclusive, so dividing it by RAND\_MAX (from `stdlib.h`) is the proper way to normalise it. In practice, RAND\_MAX will almost always be equal to MAX\_INT, but don't rely on that. Because `rand` has been part of ISO C since C89, it's guaranteed to...
I'm not sure if drand is a new addition but it seems to do exactly what you want while avoiding the costly division. ``` cdef extern from "stdlib.h": double drand48() void srand48(long int seedval) cdef extern from "time.h": long int time(int) # srand48(time(0)) srand48(100) # TODO: this is a seed to rep...
16,138,090
What is the most efficient and portable way to generate a random random in `[0,1]` in Cython? One approach is to use `INT_MAX` and `rand()` from the C library: ``` from libc.stdlib cimport rand cdef extern from "limits.h": int INT_MAX cdef float randnum = rand() / float(INT_MAX) ``` Is it OK to use `INT_MAX` in ...
2013/04/22
[ "https://Stackoverflow.com/questions/16138090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The C standard says `rand` returns an `int` in the range 0 to RAND\_MAX inclusive, so dividing it by RAND\_MAX (from `stdlib.h`) is the proper way to normalise it. In practice, RAND\_MAX will almost always be equal to MAX\_INT, but don't rely on that. Because `rand` has been part of ISO C since C89, it's guaranteed to...
All of the above answers are correct, but I'd like to add a note that took me way too long to catch. The C rand() function is NOT thread-safe. So if you are running cython in parallel without the gil, the standard C rand() function has a chance of causing enormous slowdowns while it tries to handle all of the kernel ca...
52,397,563
I've been pulling my hair out trying to figure this one out, hoping someone else has already encountered this and knows how to solve it :) I'm trying to build a very simple Flask endpoint that just needs to call a long running, blocking `php` script (think `while true {...}`). I've tried a few different methods to asy...
2018/09/19
[ "https://Stackoverflow.com/questions/52397563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407296/" ]
This kind of stuff is the actual and probably main use case for `Python Celery` (<https://docs.celeryproject.org/>). As a general rule, do not run long-running jobs that are CPU-bound in the `wsgi` process. It's tricky, it's inefficient, and most important thing, it's more complicated than setting up an *async* task in...
This approach works for me, it calls the timeout command (sleep 10s) in the command line and lets it work in the background. It returns the response immediately. ``` @app.route('/endpoint1') def endpoint1(): subprocess.Popen('timeout 10', shell=True) return 'success1' ``` However, not testing on WSGI server...
52,397,563
I've been pulling my hair out trying to figure this one out, hoping someone else has already encountered this and knows how to solve it :) I'm trying to build a very simple Flask endpoint that just needs to call a long running, blocking `php` script (think `while true {...}`). I've tried a few different methods to asy...
2018/09/19
[ "https://Stackoverflow.com/questions/52397563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407296/" ]
This kind of stuff is the actual and probably main use case for `Python Celery` (<https://docs.celeryproject.org/>). As a general rule, do not run long-running jobs that are CPU-bound in the `wsgi` process. It's tricky, it's inefficient, and most important thing, it's more complicated than setting up an *async* task in...
Would it be enough to use a background task? Then you only need to import `threading` e.g. ``` import threading import .... def endpoint(): """My endpoint.""" try: t = BackgroundTasks() t.start() except RuntimeError as exception: return f"An error occurred during endpoint: {excepti...
28,150,433
I'm trying to install Scrapy on windows 7. I'm following these instructions: <http://doc.scrapy.org/en/0.24/intro/install.html#intro-install> I’ve downloaded and installed python-2.7.5.msi for windows following this tutorial <https://adesquared.wordpress.com/2013/07/07/setting-up-python-and-easy_install-on-windows-7/...
2015/01/26
[ "https://Stackoverflow.com/questions/28150433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3640056/" ]
`ur` is python2 syntax you are trying to install an [incompatible](http://doc.scrapy.org/en/latest/faq.html#does-scrapy-work-with-python-3) package meant for python2 not python3: ``` _ajax_crawlable_re = re.compile(ur'<meta\s+name=["\']fragment["\']\s+content=["\']!["\']/?>') ^^ python...
Step By Step way to install scrapy on Windows 7 1. Install Python 2.7 from [Python Download link](https://www.python.org/downloads) (Be sure to install Python 2.7 only because currently scrapy is not available for Python3 in Windows) 2. During pyhton install there is checkbox available to add python path to system ...
28,150,433
I'm trying to install Scrapy on windows 7. I'm following these instructions: <http://doc.scrapy.org/en/0.24/intro/install.html#intro-install> I’ve downloaded and installed python-2.7.5.msi for windows following this tutorial <https://adesquared.wordpress.com/2013/07/07/setting-up-python-and-easy_install-on-windows-7/...
2015/01/26
[ "https://Stackoverflow.com/questions/28150433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3640056/" ]
`ur` is python2 syntax you are trying to install an [incompatible](http://doc.scrapy.org/en/latest/faq.html#does-scrapy-work-with-python-3) package meant for python2 not python3: ``` _ajax_crawlable_re = re.compile(ur'<meta\s+name=["\']fragment["\']\s+content=["\']!["\']/?>') ^^ python...
**How to install Scrapy 1.4 on Python 3.6 on Windows 8.1 Pro x64** ``` pip install virtualenv pip install virtualenvwrapper pip install virtualenvwrapper-win mkvirtualenv my_scrapy_project ``` I advice to use virtualenv. In my example I am using name *my\_scrapy\_project* for my virtual environment. If you want to g...
28,150,433
I'm trying to install Scrapy on windows 7. I'm following these instructions: <http://doc.scrapy.org/en/0.24/intro/install.html#intro-install> I’ve downloaded and installed python-2.7.5.msi for windows following this tutorial <https://adesquared.wordpress.com/2013/07/07/setting-up-python-and-easy_install-on-windows-7/...
2015/01/26
[ "https://Stackoverflow.com/questions/28150433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3640056/" ]
Scrapy doesn't work with Python 3 as mentioned in their [FAQ](http://doc.scrapy.org/en/latest/faq.html#faq-python-versions) you should install Python 2.7
Step By Step way to install scrapy on Windows 7 1. Install Python 2.7 from [Python Download link](https://www.python.org/downloads) (Be sure to install Python 2.7 only because currently scrapy is not available for Python3 in Windows) 2. During pyhton install there is checkbox available to add python path to system ...
28,150,433
I'm trying to install Scrapy on windows 7. I'm following these instructions: <http://doc.scrapy.org/en/0.24/intro/install.html#intro-install> I’ve downloaded and installed python-2.7.5.msi for windows following this tutorial <https://adesquared.wordpress.com/2013/07/07/setting-up-python-and-easy_install-on-windows-7/...
2015/01/26
[ "https://Stackoverflow.com/questions/28150433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3640056/" ]
Scrapy doesn't work with Python 3 as mentioned in their [FAQ](http://doc.scrapy.org/en/latest/faq.html#faq-python-versions) you should install Python 2.7
**How to install Scrapy 1.4 on Python 3.6 on Windows 8.1 Pro x64** ``` pip install virtualenv pip install virtualenvwrapper pip install virtualenvwrapper-win mkvirtualenv my_scrapy_project ``` I advice to use virtualenv. In my example I am using name *my\_scrapy\_project* for my virtual environment. If you want to g...
28,150,433
I'm trying to install Scrapy on windows 7. I'm following these instructions: <http://doc.scrapy.org/en/0.24/intro/install.html#intro-install> I’ve downloaded and installed python-2.7.5.msi for windows following this tutorial <https://adesquared.wordpress.com/2013/07/07/setting-up-python-and-easy_install-on-windows-7/...
2015/01/26
[ "https://Stackoverflow.com/questions/28150433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3640056/" ]
Step By Step way to install scrapy on Windows 7 1. Install Python 2.7 from [Python Download link](https://www.python.org/downloads) (Be sure to install Python 2.7 only because currently scrapy is not available for Python3 in Windows) 2. During pyhton install there is checkbox available to add python path to system ...
**How to install Scrapy 1.4 on Python 3.6 on Windows 8.1 Pro x64** ``` pip install virtualenv pip install virtualenvwrapper pip install virtualenvwrapper-win mkvirtualenv my_scrapy_project ``` I advice to use virtualenv. In my example I am using name *my\_scrapy\_project* for my virtual environment. If you want to g...
71,102,179
I have tried anything in the internet and nothing works. My code: ```py @bot.command() async def bug(ctx, bug): deleted_message_id = ctx.id await ctx.channel.send(str(deleted_message_id)) await ctx.send(ctx.author.mention+", you're bug report hs been reported!") ``` I use python version 3.10
2022/02/13
[ "https://Stackoverflow.com/questions/71102179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18196675/" ]
If you don't want to store the translation on the elements html themselves, you'll need to have an object mapping the values to the names to be output. Here's a minimalist example: ```js const numberNameMap = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five' }; const select = document.querySelector('se...
I've simplified your code to do exactly what you want. Try this ```js $(window).keydown(function(e) { if( [37, 38, 39, 40, 13].includes(e.which) ){ e.preventDefault(); let $col = $('.multiple li.selected'); let $row = $col.closest('.multiple'); let $nextCol = $col; ...
71,102,179
I have tried anything in the internet and nothing works. My code: ```py @bot.command() async def bug(ctx, bug): deleted_message_id = ctx.id await ctx.channel.send(str(deleted_message_id)) await ctx.send(ctx.author.mention+", you're bug report hs been reported!") ``` I use python version 3.10
2022/02/13
[ "https://Stackoverflow.com/questions/71102179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18196675/" ]
You mean like this? ```js var columns = 0; var rowButtons = 0; var $rows = $('.multiple'); var liSelected; var arrows = { left: 37, up: 38, right: 39, down: 40, enter: 13 }; $(window).keydown(function(e) { if (Object.values(arrows).indexOf(e.which) > -1) { e.preventDefault(); $...
I've simplified your code to do exactly what you want. Try this ```js $(window).keydown(function(e) { if( [37, 38, 39, 40, 13].includes(e.which) ){ e.preventDefault(); let $col = $('.multiple li.selected'); let $row = $col.closest('.multiple'); let $nextCol = $col; ...
19,721,027
After reading the [Software Carpentry](http://software-carpentry.org/) essay on [Handling Configuration Files](http://software-carpentry.org/v4/essays/config.html) I'm interested in their *Method #5: put parameters in a dynamically-loaded code module*. Basically I want the power to do calculations within my input files...
2013/11/01
[ "https://Stackoverflow.com/questions/19721027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2530083/" ]
"Never use eval or exec; they are evil". This is the only answer that works here, I think. There is no fully safe way to use exec/eval on an untrusted string string or file. The best you can do is to come up with your own language, and either interpret it yourself or turn it into safe Python code before handling it to...
If you are willing to use PyPy, then its [sandboxing feature](http://doc.pypy.org/en/latest/sandbox.html) is specifically designed for running untrusted code, so it may be useful in your case. Note that there are some issues with CPython interoperability mentioned that you may need to check. Additionally, there is a l...
69,607,117
I am trying to train a dl model with tf.keras. I have 67 classes of images inside the image directory like airports, bookstore, casino. And for each classes i have at least 100 images. The data is from [mit indoor scene](http://web.mit.edu/torralba/www/indoor.html) dataset But when I am trying to train the model, I am ...
2021/10/17
[ "https://Stackoverflow.com/questions/69607117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12195048/" ]
I think it might be a corrupted file. It is throwing an exception after a data integrity check in the `DecodeBMPv2` function (<https://github.com/tensorflow/tensorflow/blob/0b6b491d21d6a4eb5fbab1cca565bc1e94ca9543/tensorflow/core/kernels/image/decode_image_op.cc#L594>) If that's the issue and you want to find out whic...
This is in fact a **corrupted file problem**. However, the underlying issue is far more subtle. Here is an explanation of what is going on and how to circumvent this obstacle. I encountered the very same problem on the very same [MIT Indoor Scene Classification](https://www.kaggle.com/datasets/itsahmad/indoor-scenes-cv...
61,183,427
I am beginner of python and trying to insert percentage sign in the output. Below is the code that I've got. ``` print('accuracy :', accuracy_score(y_true, y_pred)*100) ``` when I run this code I got 50.0001 and I would like to have %sign at the end of the number so I tried to do as below ``` print('Macro average ...
2020/04/13
[ "https://Stackoverflow.com/questions/61183427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10267370/" ]
Use f strings: ``` print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n") ``` Or convert the value to string, and add (*concatenate*) the strings: ``` print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n") ``` See [the discuss...
The simple, "low-tech" way is to correct your (lack of) output expression. Convert the float to a string and concatenate. To make it easy to follow: ``` pct = precision_score(y_true, y_pred, average='macro')*100 print('Macro average precision : ' + str(pct) + "%\n") ``` This is inelegant, but easy to follow.
61,183,427
I am beginner of python and trying to insert percentage sign in the output. Below is the code that I've got. ``` print('accuracy :', accuracy_score(y_true, y_pred)*100) ``` when I run this code I got 50.0001 and I would like to have %sign at the end of the number so I tried to do as below ``` print('Macro average ...
2020/04/13
[ "https://Stackoverflow.com/questions/61183427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10267370/" ]
Use f strings: ``` print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n") ``` Or convert the value to string, and add (*concatenate*) the strings: ``` print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n") ``` See [the discuss...
You can try this: ``` print('accuracy: {:.2f}%'.format(100*accuracy_score(y_true, y_pred))) ```
61,183,427
I am beginner of python and trying to insert percentage sign in the output. Below is the code that I've got. ``` print('accuracy :', accuracy_score(y_true, y_pred)*100) ``` when I run this code I got 50.0001 and I would like to have %sign at the end of the number so I tried to do as below ``` print('Macro average ...
2020/04/13
[ "https://Stackoverflow.com/questions/61183427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10267370/" ]
Use f strings: ``` print(f"Macro average precision : {precision_score(y_true, y_pred, average='macro')*100}%\n") ``` Or convert the value to string, and add (*concatenate*) the strings: ``` print('Macro average precision : ' + str(precision_score(y_true, y_pred, average='macro')*100) + "%\n") ``` See [the discuss...
One of the ways to go about fixing this is by using string concatenation. You can add the percent symbol to your output from your function using a simple + operator. However, the output of your function needs to be cast to a string data type in order to be able to concatenate it with a string. To cast something to a st...
52,418,698
I have Spark and Airflow cluster, I want to send a spark job from Airflow container to Spark container. But I am new about Airflow and I don't know which configuration I need to perform. I copied `spark_submit_operator.py` under the plugins folder. ```py from airflow import DAG from airflow.contrib.operators.spark_su...
2018/09/20
[ "https://Stackoverflow.com/questions/52418698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4230665/" ]
If you use SparkSubmitOperator the connection to master will be set as "Yarn" by default regardless master which you set on your python code, however, you can override master by specifying conn\_id through its constructor with the condition you have already created the aforementioned `conn_id` at "Admin->Connection" me...
I guess you need to set master in extra options in your connections for this spark conn id (spark\_default).By default is yarn, so try{"master":"your-con"} Also does your airflow user has spark-submit in the classpath?, from logs looks like it doesnt.
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
> > Could i iterate through the string itself like so? > > > > ``` > for letter in s: > #compare stuff > > ``` > > How would I compare specific indexes in the string using the above method? > > > The pythonic way of doing these kind of comparisons without specifically referring to indexes would be: ``` for ...
Try this - i.e. go to len(s)-2 as you won't ever get a bob starting after that point ``` count = 0 s = "bobgetbob" for i in range(len(s) - 2): if s[i] == 'b' and s[i + 1] == 'o' and s[i + 2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
> > Could i iterate through the string itself like so? > > > > ``` > for letter in s: > #compare stuff > > ``` > > How would I compare specific indexes in the string using the above method? > > > The pythonic way of doing these kind of comparisons without specifically referring to indexes would be: ``` for ...
a generator expression and sum would be a better way to solve it: ``` print("number of bobs {}".format(sum(s[i:i+3] == "bob" for i in xrange(len(s)) ))) ``` You can also cheat a bit with indexing i.e `s[i+2:i+3]` will not throw an indexError : ``` count = 0 s = "bobgetbob" for i in range(0,len(s)): print(s[i+1:...
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
> > Could i iterate through the string itself like so? > > > > ``` > for letter in s: > #compare stuff > > ``` > > How would I compare specific indexes in the string using the above method? > > > The pythonic way of doing these kind of comparisons without specifically referring to indexes would be: ``` for ...
In general, that is the slow way to do it; you are better off delegating as much as possible to higher-performance object methods like `str.find`: ``` def how_many(needle, haystack): """ Given needle: str to search for haystack: str to search in Return the number of (possibly overlapping...
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
> > Could i iterate through the string itself like so? > > > > ``` > for letter in s: > #compare stuff > > ``` > > How would I compare specific indexes in the string using the above method? > > > The pythonic way of doing these kind of comparisons without specifically referring to indexes would be: ``` for ...
``` count = 0 for i in range(0,len(s)-2): if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
In general, that is the slow way to do it; you are better off delegating as much as possible to higher-performance object methods like `str.find`: ``` def how_many(needle, haystack): """ Given needle: str to search for haystack: str to search in Return the number of (possibly overlapping...
Try this - i.e. go to len(s)-2 as you won't ever get a bob starting after that point ``` count = 0 s = "bobgetbob" for i in range(len(s) - 2): if s[i] == 'b' and s[i + 1] == 'o' and s[i + 2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
Try this - i.e. go to len(s)-2 as you won't ever get a bob starting after that point ``` count = 0 s = "bobgetbob" for i in range(len(s) - 2): if s[i] == 'b' and s[i + 1] == 'o' and s[i + 2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
``` count = 0 for i in range(0,len(s)-2): if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
In general, that is the slow way to do it; you are better off delegating as much as possible to higher-performance object methods like `str.find`: ``` def how_many(needle, haystack): """ Given needle: str to search for haystack: str to search in Return the number of (possibly overlapping...
a generator expression and sum would be a better way to solve it: ``` print("number of bobs {}".format(sum(s[i:i+3] == "bob" for i in xrange(len(s)) ))) ``` You can also cheat a bit with indexing i.e `s[i+2:i+3]` will not throw an indexError : ``` count = 0 s = "bobgetbob" for i in range(0,len(s)): print(s[i+1:...
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
a generator expression and sum would be a better way to solve it: ``` print("number of bobs {}".format(sum(s[i:i+3] == "bob" for i in xrange(len(s)) ))) ``` You can also cheat a bit with indexing i.e `s[i+2:i+3]` will not throw an indexError : ``` count = 0 s = "bobgetbob" for i in range(0,len(s)): print(s[i+1:...
``` count = 0 for i in range(0,len(s)-2): if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
28,034,947
So i'm trying to do something like this ``` #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b') count++; } printf("Number of 'bobs' is: %d\n...
2015/01/19
[ "https://Stackoverflow.com/questions/28034947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123828/" ]
In general, that is the slow way to do it; you are better off delegating as much as possible to higher-performance object methods like `str.find`: ``` def how_many(needle, haystack): """ Given needle: str to search for haystack: str to search in Return the number of (possibly overlapping...
``` count = 0 for i in range(0,len(s)-2): if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b': count += 1 print "Number of 'bobs' is: %d" % count ```
11,464,750
useI am working on a python script to check if the url is working. The script will write the url and response code to a log file. To speed up the check, I am using threading and queue. The script works well if the number of url's to check is small but when increasing the number of url's to hundreds, some url's just wi...
2012/07/13
[ "https://Stackoverflow.com/questions/11464750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1516432/" ]
Python's threading module isn't really multithreaded because of the global interpreter lock, <http://wiki.python.org/moin/GlobalInterpreterLock> as such you should really use `multiprocessing` <http://docs.python.org/library/multiprocessing.html> if you really want to take advantage of multiple cores. Also you seem to...
At first glance this looks like a race condition, since many threads are trying to write to the log file at the same time. See [this question](https://stackoverflow.com/q/489861/520779) for some pointers on how to lock a file for writing (so only one thread can access it at a time).
13,350,427
I am learning to use javascript, ajax, python and django together. In my project, a user selects a language from a drop-down list. Then the selected is sent back to the server. Then the server sends the response back to the django template. This is done by javascript. In the django template, I need the response, for e...
2012/11/12
[ "https://Stackoverflow.com/questions/13350427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1165201/" ]
You could use jquery to send the ajax request and server could send the response with html content. For example, Server: When server receives the ajax request. This would return the html content i.e. a template which could be rendered to the client via ajax ``` def update_html_on_client(request): language = reque...
Because your templates are rendered on the server, your best bet is to simply reload the page (which re-renders the page with your newly selected language). An alternative to using ajax would be to store the language in a cookie, that way you don't have to maintain state on the client. Either way, the reload is still ...
66,889,445
I am trying to push my app to heroku, I am following the tutorial from udemy - everything goes smooth as explained. Once I am at the last step - doing `git push heroku master` I get the following error in the console: ``` (flaskdeploy) C:\Users\dmitr\Desktop\jose\FLASK_heroku>git push heroku master Enumerating objects...
2021/03/31
[ "https://Stackoverflow.com/questions/66889445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11803958/" ]
You could use [repr](https://docs.python.org/3/library/functions.html#repr) ```py print(repr(var)) ```
Maybe you want to use f-string ? ``` var = "textlol" print(f"\"{var}\"") ```
66,889,445
I am trying to push my app to heroku, I am following the tutorial from udemy - everything goes smooth as explained. Once I am at the last step - doing `git push heroku master` I get the following error in the console: ``` (flaskdeploy) C:\Users\dmitr\Desktop\jose\FLASK_heroku>git push heroku master Enumerating objects...
2021/03/31
[ "https://Stackoverflow.com/questions/66889445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11803958/" ]
You could use [repr](https://docs.python.org/3/library/functions.html#repr) ```py print(repr(var)) ```
It's easy as you see in below: ``` var = '"text"' print(var) ```
66,889,445
I am trying to push my app to heroku, I am following the tutorial from udemy - everything goes smooth as explained. Once I am at the last step - doing `git push heroku master` I get the following error in the console: ``` (flaskdeploy) C:\Users\dmitr\Desktop\jose\FLASK_heroku>git push heroku master Enumerating objects...
2021/03/31
[ "https://Stackoverflow.com/questions/66889445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11803958/" ]
You could use [repr](https://docs.python.org/3/library/functions.html#repr) ```py print(repr(var)) ```
You'll need to insert your string value into the string that is printed. There are a few ways to do this, take a look at [this answer on a similar question](https://stackoverflow.com/a/52155770/15469537). In your case, you want to print `"` around the string. As `"` is a special character, you'll need to insert a back...
66,889,445
I am trying to push my app to heroku, I am following the tutorial from udemy - everything goes smooth as explained. Once I am at the last step - doing `git push heroku master` I get the following error in the console: ``` (flaskdeploy) C:\Users\dmitr\Desktop\jose\FLASK_heroku>git push heroku master Enumerating objects...
2021/03/31
[ "https://Stackoverflow.com/questions/66889445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11803958/" ]
You could use [repr](https://docs.python.org/3/library/functions.html#repr) ```py print(repr(var)) ```
add the quotation marks when you print it. This way you don't have to change the variable. Example: ``` var = "text" print('"'+'text'+'"') ``` Output: "text"
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
For a `list` (call it `seq`) and a target row length (call it `rowsize`), you would do something like this: ``` split_into_rows = [seq[i: i + rowsize] for i in range(0, len(seq), rowsize)] ``` You could then use the writer's `writerows` method to write elements to the file: ``` writer.writerows(split_into_rows) ``...
I suggest using a temp array B. 1. Get the length of the original array A 2. Copy the first A.length/2 to array B 3. Add new line character to array B. 4. Append the rest of array A to B.
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
For a `list` (call it `seq`) and a target row length (call it `rowsize`), you would do something like this: ``` split_into_rows = [seq[i: i + rowsize] for i in range(0, len(seq), rowsize)] ``` You could then use the writer's `writerows` method to write elements to the file: ``` writer.writerows(split_into_rows) ``...
when dealing with lists in this manner, it's best to use the numpy module: ``` import numpy as np A = ["1", "2", "3", "4", "5", "6", "7", "8"] #now to convert your list into a 2-Dimensional numpy array A = np.array((A)).reshape((2,4)) result = open("newfile.csv",'wb') writer = csv.writer(result, dialect = 'excel') #yo...
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
For a `list` (call it `seq`) and a target row length (call it `rowsize`), you would do something like this: ``` split_into_rows = [seq[i: i + rowsize] for i in range(0, len(seq), rowsize)] ``` You could then use the writer's `writerows` method to write elements to the file: ``` writer.writerows(split_into_rows) ``...
This ``` import itertools l = ['a1','a2','b1','b2'] def toCSV(fname,l): with open(fname+'.csv','w') as f: f.write('\n'.join([','.join(list(g)) for k,g in itertools.groupby(l,key=lambda k: k[0])])) toCSV('mycsv',l) ``` Would yield ``` a1,a2 b1,b2 ``` It relies heavily on itertool's groupby function....
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
For a `list` (call it `seq`) and a target row length (call it `rowsize`), you would do something like this: ``` split_into_rows = [seq[i: i + rowsize] for i in range(0, len(seq), rowsize)] ``` You could then use the writer's `writerows` method to write elements to the file: ``` writer.writerows(split_into_rows) ``...
``` >>> import csv >>> A = ["1", "2", "3", "4", "5", "6", "7", "8"] >>> with open("newfile.csv",'wb') as f: w = csv.writer(f) w.writerows(zip(*[iter(A)]*4)) ```
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
I suggest using a temp array B. 1. Get the length of the original array A 2. Copy the first A.length/2 to array B 3. Add new line character to array B. 4. Append the rest of array A to B.
This ``` import itertools l = ['a1','a2','b1','b2'] def toCSV(fname,l): with open(fname+'.csv','w') as f: f.write('\n'.join([','.join(list(g)) for k,g in itertools.groupby(l,key=lambda k: k[0])])) toCSV('mycsv',l) ``` Would yield ``` a1,a2 b1,b2 ``` It relies heavily on itertool's groupby function....
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
when dealing with lists in this manner, it's best to use the numpy module: ``` import numpy as np A = ["1", "2", "3", "4", "5", "6", "7", "8"] #now to convert your list into a 2-Dimensional numpy array A = np.array((A)).reshape((2,4)) result = open("newfile.csv",'wb') writer = csv.writer(result, dialect = 'excel') #yo...
This ``` import itertools l = ['a1','a2','b1','b2'] def toCSV(fname,l): with open(fname+'.csv','w') as f: f.write('\n'.join([','.join(list(g)) for k,g in itertools.groupby(l,key=lambda k: k[0])])) toCSV('mycsv',l) ``` Would yield ``` a1,a2 b1,b2 ``` It relies heavily on itertool's groupby function....
16,206,224
I have a python list and I would like to export it to a csv file, but I don't want to store all the list in the same row. I would like to slice the list at a given point and start a new line. Something like this: ``` list = [x1,x2,x3,x4,y1,y2,y3,y4] ``` and I would like it to export it in this format ``` x1 x2 x3 ...
2013/04/25
[ "https://Stackoverflow.com/questions/16206224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956586/" ]
``` >>> import csv >>> A = ["1", "2", "3", "4", "5", "6", "7", "8"] >>> with open("newfile.csv",'wb') as f: w = csv.writer(f) w.writerows(zip(*[iter(A)]*4)) ```
This ``` import itertools l = ['a1','a2','b1','b2'] def toCSV(fname,l): with open(fname+'.csv','w') as f: f.write('\n'.join([','.join(list(g)) for k,g in itertools.groupby(l,key=lambda k: k[0])])) toCSV('mycsv',l) ``` Would yield ``` a1,a2 b1,b2 ``` It relies heavily on itertool's groupby function....
13,219,585
im teaching myself python and im abit confused ``` #!/usr/bin/python def Age(): age_ = int(input("How old are you? ")) def Name(): name_ = raw_input("What is your name? ") def Sex(): sex_ = raw_input("Are you a man(1) or a woman(2)? ") if sex_ == 1: man = 1 e...
2012/11/04
[ "https://Stackoverflow.com/questions/13219585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222298/" ]
Programming Lua has example on [non-preemptive multithreading](http://www.lua.org/pil/9.4.html) (using coroutines), which you can probably use almost directly. In my opinion coroutines will be a better solution for your use case. There is also [copas library](http://keplerproject.github.com/copas/index.html) that desc...
Lua Lanes creates an entirely new (but minimal) Lua state for each lane. Any upvalues or arguments passed are copied, not referenced; this means your allClients table is being copied, along with the sockets it contains. The error is occurring because the sockets are userdata, which Lua Lanes does not know how to copy ...
17,664,841
I have a set and dictionary and a value = 5 ``` v = s = {'a', 'b', 'c'} d = {'b':5 //<--new value} ``` If the key 'b' in dictionary d for example is in set s then I want to make that value equal to the new value when I return a dict comprehension or 0 if the key in set s is not in the dictionary d. So this is my cod...
2013/07/15
[ "https://Stackoverflow.com/questions/17664841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509483/" ]
The expanded form of what you're trying to achieve is ``` a = {} for k in v: a[k] = d[k] if k in d else 0 ``` where `d[k] if k in d else 0` is [the Python's version of ternary operator](https://docs.python.org/dev/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator). See? You need to drop `k:` fr...
You can't use a ternary `if` expression for a name:value pair, because a name:value pair isn't a value. You *can* use an `if` expression for the value or key separately, which seems to be exactly what you want here: ``` {k: (d[k] if k in v else 0) for k in v} ``` However, this is kind of silly. You're doing `for k ...
17,664,841
I have a set and dictionary and a value = 5 ``` v = s = {'a', 'b', 'c'} d = {'b':5 //<--new value} ``` If the key 'b' in dictionary d for example is in set s then I want to make that value equal to the new value when I return a dict comprehension or 0 if the key in set s is not in the dictionary d. So this is my cod...
2013/07/15
[ "https://Stackoverflow.com/questions/17664841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509483/" ]
The expanded form of what you're trying to achieve is ``` a = {} for k in v: a[k] = d[k] if k in d else 0 ``` where `d[k] if k in d else 0` is [the Python's version of ternary operator](https://docs.python.org/dev/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator). See? You need to drop `k:` fr...
``` In [82]: s = {'a', 'b', 'c'} In [83]: d = {'b':5 } In [85]: {key: d.get(key, 0) for key in s} Out[85]: {'a': 0, 'b': 5, 'c': 0} ```
17,664,841
I have a set and dictionary and a value = 5 ``` v = s = {'a', 'b', 'c'} d = {'b':5 //<--new value} ``` If the key 'b' in dictionary d for example is in set s then I want to make that value equal to the new value when I return a dict comprehension or 0 if the key in set s is not in the dictionary d. So this is my cod...
2013/07/15
[ "https://Stackoverflow.com/questions/17664841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509483/" ]
The expanded form of what you're trying to achieve is ``` a = {} for k in v: a[k] = d[k] if k in d else 0 ``` where `d[k] if k in d else 0` is [the Python's version of ternary operator](https://docs.python.org/dev/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator). See? You need to drop `k:` fr...
This should solve your problem: ``` >>> dict((k, d.get(k, 0)) for k in s) {'a': 0, 'c': 0, 'b': 5} ```
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
In c# 6.0 you can now do ``` string username = SomeUserObject?.Username; ``` username will be set to null if SomeUSerObject is null. If you want it to get the value "", you can do ``` string username = SomeUserObject?.Username ?? ""; ```
It is called null coalescing and is performed as follows: ``` string username = SomeUserObject.Username ?? "" ```
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
You can use ? : as others have suggested but you might want to consider the Null object pattern where you create a special static User `User.NotloggedIn` and use that instead of null everywhere. Then it becomes easy to always do `.Username`. Other benefits: you get / can generate different exceptions for the case (n...
It is called null coalescing and is performed as follows: ``` string username = SomeUserObject.Username ?? "" ```
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
You can use ? : as others have suggested but you might want to consider the Null object pattern where you create a special static User `User.NotloggedIn` and use that instead of null everywhere. Then it becomes easy to always do `.Username`. Other benefits: you get / can generate different exceptions for the case (n...
You're thinking of the ternary operator. ``` string username = SomeUserObject == null ? "" : SomeUserObject.Username; ``` See <http://msdn.microsoft.com/en-us/library/ty67wk28.aspx> for more details.
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
The closest you're going to get, I think, is: ``` string username = SomeUserObject == null ? null : SomeUserObject.Username; ```
This is probably as close as you are going to get: ``` string username = (SomeUserObject != null) ? SomeUserObject.Username : null; ```
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
The closest you're going to get, I think, is: ``` string username = SomeUserObject == null ? null : SomeUserObject.Username; ```
You're thinking of the ternary operator. ``` string username = SomeUserObject == null ? "" : SomeUserObject.Username; ``` See <http://msdn.microsoft.com/en-us/library/ty67wk28.aspx> for more details.
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
In c# 6.0 you can now do ``` string username = SomeUserObject?.Username; ``` username will be set to null if SomeUSerObject is null. If you want it to get the value "", you can do ``` string username = SomeUserObject?.Username ?? ""; ```
This is probably as close as you are going to get: ``` string username = (SomeUserObject != null) ? SomeUserObject.Username : null; ```
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
The closest you're going to get, I think, is: ``` string username = SomeUserObject == null ? null : SomeUserObject.Username; ```
It is called null coalescing and is performed as follows: ``` string username = SomeUserObject.Username ?? "" ```
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
The closest you're going to get, I think, is: ``` string username = SomeUserObject == null ? null : SomeUserObject.Username; ```
You can use ? : as others have suggested but you might want to consider the Null object pattern where you create a special static User `User.NotloggedIn` and use that instead of null everywhere. Then it becomes easy to always do `.Username`. Other benefits: you get / can generate different exceptions for the case (n...
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
This is probably as close as you are going to get: ``` string username = (SomeUserObject != null) ? SomeUserObject.Username : null; ```
You're thinking of the ternary operator. ``` string username = SomeUserObject == null ? "" : SomeUserObject.Username; ``` See <http://msdn.microsoft.com/en-us/library/ty67wk28.aspx> for more details.
2,616,190
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
2010/04/11
[ "https://Stackoverflow.com/questions/2616190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
Your syntax on the second is slightly off. ``` string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty; ```
This is probably as close as you are going to get: ``` string username = (SomeUserObject != null) ? SomeUserObject.Username : null; ```
70,279,160
trying to find out correct syntax to traverse through through the list to get all values and insert into oracle. edit: Below is the json structure : ``` [{ "publishTime" : "2021-11-02T20:18:36.223Z", "data" : { "DateTime" : "2021-11-01T15:10:17Z", "Name" : "x1", "frtb" : { "code" : "set1" },...
2021/12/08
[ "https://Stackoverflow.com/questions/70279160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17544527/" ]
Knative Serving does not support such a policy as of today. However, the community thinks that Kubernetes' Descheduler should work just fine, as is discussed in <https://github.com/knative/serving/issues/6176>.
Not kn specific but you could try adding `activeDeadlineSeconds` to the podSpec.
47,351,274
In summary, When provisioning my vagrant box using Ansible, I get thrown a mysterious error when trying to clone my bitbucket private repo using ssh. The error states that the "Host key verification failed". Yet if I vagrant ssh and then run the '*git clone*' command, the private repo is successfully cloned. This indi...
2017/11/17
[ "https://Stackoverflow.com/questions/47351274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4515324/" ]
Since you run the whole playbook with `become: true`, SSH key-forwarding (as well as troubleshooting) becomes irrelevant, because the user connecting to BitBucket from your play is `root`. Run the task connecting to BitBucket as `ubuntu` user: * either specifying `become: false` in the `Clone bitbucket repo` task), *...
This answer comes direct from techraf's helpful comments. * I changed the owner of the /var/www directory from 'www-data' to 'ubuntu' (the username I use to login via ssh). * I also added "become: false" above the git task. NOTE: I have since been dealing with the following issue so this answer does not fully resolve...
40,477,687
I'm getting `ImportError: No module named django` when trying to up my containers running `docker-compose up`. Here's my scenario: Dockerfile ``` FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ ``` docker-compose.yml ...
2016/11/08
[ "https://Stackoverflow.com/questions/40477687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2812350/" ]
Maybe what you want is to do this: ``` void printHandResults(struct Card (*hand)[]); ``` and this: ``` void printHandResults(struct Card (*hand)[]) { } ``` What you were doing was passing a pointer to an array of struct variables in the main, BUT, the function was set to receive **an array of pointers to struct ...
More easy way: ``` #define HAND_SIZE 5 typedef struct Cards{ char suit; char face; }card_t; void printHandResults( card_t*); int main(void) { card_t hand[HAND_SIZE]; card_t* p_hand = hand; ... printHandResults(p_hand); } void printHandResults( card_t *hand) { // Here you must play with pointer's ar...
40,477,687
I'm getting `ImportError: No module named django` when trying to up my containers running `docker-compose up`. Here's my scenario: Dockerfile ``` FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ ``` docker-compose.yml ...
2016/11/08
[ "https://Stackoverflow.com/questions/40477687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2812350/" ]
An array degrades into a raw pointer to the first array element. So you can do something more like this instead: ``` #define HAND_SIZE 5 struct Card { char suit; char face; }; void printHandResults(struct Card *hand); int main(void) { struct Card hand[HAND_SIZE]; ... printHandResults(hand); } v...
More easy way: ``` #define HAND_SIZE 5 typedef struct Cards{ char suit; char face; }card_t; void printHandResults( card_t*); int main(void) { card_t hand[HAND_SIZE]; card_t* p_hand = hand; ... printHandResults(p_hand); } void printHandResults( card_t *hand) { // Here you must play with pointer's ar...
57,498,262
It seems so basic, but I can't work out how to achieve the following... Consider the scenario where I have the following data: ```py all_columns = ['A','B','C','D'] first_columns = ['A','B'] second_columns = ['C','D'] new_columns = ['E','F'] values = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] df ...
2019/08/14
[ "https://Stackoverflow.com/questions/57498262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750173/" ]
An option is `pivot_longer` from the dev version of `tidyr` ``` library(tidyr) library(dplyr) library(tibble) nm1 <- sub("\\.?\\d+$", "", names(df)) names(df) <- paste0(nm1, ":", ave(seq_along(nm1), nm1, FUN = seq_along)) df %>% rownames_to_column('rn') %>% pivot_longer(-rn, names_to= c(".value", "Group"), n...
You may use base R's `reshape`. The trick is the nested `varying` and to `cbind` an `id` column. ``` reshape(cbind(id=1:nrow(DF), DF), varying=list(c(2, 4), c(3, 5)), direction="long", timevar="Group", v.names=c("Gene", "AVG_EXPR"), times=c("Group1", "Group2")) # id Group Gene AVG_EXPR #...
57,498,262
It seems so basic, but I can't work out how to achieve the following... Consider the scenario where I have the following data: ```py all_columns = ['A','B','C','D'] first_columns = ['A','B'] second_columns = ['C','D'] new_columns = ['E','F'] values = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] df ...
2019/08/14
[ "https://Stackoverflow.com/questions/57498262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750173/" ]
You can combine two `dplyr` calls with `bind_rows`. ```r df %>% select(gene=Group1,AVG_EXPR) %>% mutate(group='group 1') %>% bind_rows(.,df %>% select(gene=Group2,AVG_EXPR=AVG_EXPR.1) %>% mutate(group='group 2')) ```
You may use base R's `reshape`. The trick is the nested `varying` and to `cbind` an `id` column. ``` reshape(cbind(id=1:nrow(DF), DF), varying=list(c(2, 4), c(3, 5)), direction="long", timevar="Group", v.names=c("Gene", "AVG_EXPR"), times=c("Group1", "Group2")) # id Group Gene AVG_EXPR #...
67,080,686
So I need to enforce the type of a class variable, but more importantly, I need to enforce a list with its types. So if I have some code which looks like this: ``` class foo: def __init__(self, value: list[int]): self.value = value ``` Btw I'm using python version 3.9.4 So essentially my question is, ho...
2021/04/13
[ "https://Stackoverflow.com/questions/67080686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15017177/" ]
You can enable the system keyboard by configuring `OVRCameraRig` Oculus features. 1. From the Hierarchy view, select `OVRCameraRig` to open settings in the Inspector view. 2. Under `OVR Manager`, in the `Quest Features` section, select `Require System Keyboard`. [![enter image description here](https://i.stack.imgur....
What @Codemaker answered here is for Oculus Integration. For XR Interaction Toolkit, you can manually enable a keyboard instance, by doing the following. ``` private TouchScreenKeyboard keyboard; public void ShowKeyboard() { keyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default); } ``` Just add...
1,399,727
Assuming the text is typed at the same time in the same (Israeli) timezone, The following free text lines are equivalent: ``` Wed Sep 9 16:26:57 IDT 2009 2009-09-09 16:26:57 16:26:57 September 9th, 16:26:57 ``` Is there a python module that would convert all these text-dates to an (identical) `datetime.datetime` in...
2009/09/09
[ "https://Stackoverflow.com/questions/1399727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51197/" ]
The [python-dateutil](http://labix.org/python-dateutil) package sounds like it would be helpful. Your examples only use simple HH:MM timestamps with a (magically shortened) city identifier, but it seems able to handle more complicated formats like those earlier in the question, too.
You could you [`time.strptime`](http://docs.python.org/library/time.html#time.strptime) Like this : ``` time.strptime("2009-09-09 16:26:57", "%Y-%m-%d %H:%M:%S") ``` It will return a struct\_time value (more info on the python doc page).
1,399,727
Assuming the text is typed at the same time in the same (Israeli) timezone, The following free text lines are equivalent: ``` Wed Sep 9 16:26:57 IDT 2009 2009-09-09 16:26:57 16:26:57 September 9th, 16:26:57 ``` Is there a python module that would convert all these text-dates to an (identical) `datetime.datetime` in...
2009/09/09
[ "https://Stackoverflow.com/questions/1399727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51197/" ]
[parsedatetime](http://code.google.com/p/parsedatetime/) seems to be a very capable module for this specific task.
You could you [`time.strptime`](http://docs.python.org/library/time.html#time.strptime) Like this : ``` time.strptime("2009-09-09 16:26:57", "%Y-%m-%d %H:%M:%S") ``` It will return a struct\_time value (more info on the python doc page).
62,767,387
I'm a noob with python beautifoulsoup library and i'm trying to scrape data from a website's highcharts. i found that all the data i need is located in a script tag, however i dont know how to scrape them (please see the attached image) Is there a way to get the data from this script tag using python beautifulsoup? [sc...
2020/07/07
[ "https://Stackoverflow.com/questions/62767387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13881565/" ]
Check out this working sandbox: <https://codesandbox.io/s/confident-taussig-tg3my?file=/src/App.js> One thing to note is you shouldn't base keys off of linear sequences [or indexes] because that can mess up React's tracking. Instead, pass the index value from map into the IssueRow component to track order, and give ea...
This should be inside another `React.useEffect()`: ``` setTimeout(() => { createIssue(sampleIssue); }, 2000); ``` Otherwise, it will run every render in a loop. As a general rule of thumb there should be no side effects outside of useEffect.
62,767,387
I'm a noob with python beautifoulsoup library and i'm trying to scrape data from a website's highcharts. i found that all the data i need is located in a script tag, however i dont know how to scrape them (please see the attached image) Is there a way to get the data from this script tag using python beautifulsoup? [sc...
2020/07/07
[ "https://Stackoverflow.com/questions/62767387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13881565/" ]
Check out this working sandbox: <https://codesandbox.io/s/confident-taussig-tg3my?file=/src/App.js> One thing to note is you shouldn't base keys off of linear sequences [or indexes] because that can mess up React's tracking. Instead, pass the index value from map into the IssueRow component to track order, and give ea...
Functional component can look like this: ``` function IssueTable() { const [issue1, setIssues] = React.useState([]); const createIssue = React.useCallback( function createIssue(issue) { //passing callback to setIssues // so useCallback does not depend // on issue1 and does not have stale ...
63,438,737
I have an image in which text is lighter and not clearly visible, i want to enhance the text and lighten then background using python pil or cv2. Help is needed. I needed to print this image and hence it has ro be clearer. what i have done till now is below ``` from PIL import Image, ImageEnhance im = Image.open('t.j...
2020/08/16
[ "https://Stackoverflow.com/questions/63438737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Save first column in an array, too. Insert before your `END` section `{dates[FNR] = $1}` and replace both `$1` with `dates[n]`.
Could you please try following, have written on mobile so couldn't test it as of now, should work but. ``` awk ' { diff=$2-$3 a[$1]=(a[$1]!="" && a[$1]>diff?a[$1]:diff) } END{ for(i in a){ print i,a[i] } }' *.txt ```
63,438,737
I have an image in which text is lighter and not clearly visible, i want to enhance the text and lighten then background using python pil or cv2. Help is needed. I needed to print this image and hence it has ro be clearer. what i have done till now is below ``` from PIL import Image, ImageEnhance im = Image.open('t.j...
2020/08/16
[ "https://Stackoverflow.com/questions/63438737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Save first column in an array, too. Insert before your `END` section `{dates[FNR] = $1}` and replace both `$1` with `dates[n]`.
You may use Perl, which you'll find on any linux distribution. ``` perl -e ' $bad = -99999; while(<ARGV>){ chomp(@cols=split /\h+/); $diff = $cols[1]<0 || $cols[2]<0 ? $bad : $cols[1]-$cols[2]; $old = $result{$cols[0]} || $bad; $result{$cols[0]} = $old < $diff ? $diff : $old; ...
58,771,456
i am installing connector of Psycopg2 but i am unable install, how do i install that successfully? in using this command line to install: ``` pip install psycopg2 (test) C:\Users\Shree.Shree-PC\Desktop\projects\purchasepo>pip install psycopg2 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages...
2019/11/08
[ "https://Stackoverflow.com/questions/58771456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10123621/" ]
It was such a dump solution, it took me hours to find this: When I get the file from DocumentPicker I had to add the type of the file because DocumentPicker return an odd type called "success", when I changed it to 'image/jpeg' it worked :D its not a solution at all because I will need to find a way to know what type ...
you should try to modify the content-type to ``` fetch("http://192.168.0.3:8000/api/file", { method: "POST", headers:{ 'Content-Type': 'multipart/form-data', }, body: data }) ``` and for the form-url-urlencoded, the fetch is not supported. you have to push it by yourself.you ca...
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/2017082006590...
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
Sometimes texts have to be read more for the flavor of the idea rather than for the details. This is one of those cases. In the [linked page](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution), Examples 2.5, 2.6 and 2.7 should all use one method, `do_your_s...
The example from the web page seems to work as published. Did you create a `do_something` method for the superclass as well but not make it into a classmethod? Something like this will give you that error: ``` >>> class A(object): ... def do_something(cls): ... print cls ... # do_something = classmethod(...
1,817,183
I'm trying to learn the super() function in Python. I thought I had a grasp of it until I came over this example (2.6) and found myself stuck. [http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](https://web.archive.org/web/2017082006590...
2009/11/29
[ "https://Stackoverflow.com/questions/1817183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169854/" ]
The example from the web page seems to work as published. Did you create a `do_something` method for the superclass as well but not make it into a classmethod? Something like this will give you that error: ``` >>> class A(object): ... def do_something(cls): ... print cls ... # do_something = classmethod(...
I think I've understood the point now thanks to this beatiful site and lovely community. If you don't mind please correct me if I'm wrong on classmethods (which I am now trying to understand fully): ``` # EXAMPLE #1 >>> class A(object): ... def foo(cls): ... print cls ... foo = classmethod(foo) ....