qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
58,026,436
I am working on a bank statement, corresponding to the output dataframe and an ending balance corresponding to the output['balance'][0] I would like to calculate all balance values for the individual transactions as described below. It's a very straightforward calculation and yet it doesn't seem to be working - is ther...
2019/09/20
[ "https://Stackoverflow.com/questions/58026436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698202/" ]
I would need to have all of your code and be able to run it locally in order to diagnose the problem because your posting is devoid of details (I would need to see inside your `ManipulatePixel` function, as well as the code that calls `ProcessFrame`). but here's some general tips that apply in your case. * 2D arrays i...
Efficiency matters ( it is **not** true-**`[PARALLEL]`**, but may, yet need not, benefit from a *"just"*-`[CONCURRENT]` work The BEST, yet a rather hard way, if ultimate performance is a MUST : -------------------------------------------------------------------- in-line an assembly, optimised as per cache-line sizes ...
8,669
29,360,607
I was looking up how to create a function that removes duplicate characters from a string in python and found this on stack overflow: ``` from collections import OrderedDict def remove_duplicates (foo) : print " ".join(OrderedDict.fromkeys(foo)) ``` It works, but how? I've searched what OrderedDict...
2015/03/31
[ "https://Stackoverflow.com/questions/29360607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4728174/" ]
I will give it a shot: [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) are dictionaries that store keys in order they are added. Normal dictionaries don't. If you look at **doc** of `fromkeys`, you find: > > OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. > ...
By list comprehension ``` print ' '.join([character for index, character in enumerate(foo) if character not in foo[:index]]) ```
8,672
22,036,124
I declared a few global variables in a python file and would like to reset their values to None in a function. Is there a better/hack/pythonic way to declare all variables as global and assign them a value in one line? ``` doctype, content_type, framework, cms, server = (None,)*5 def reset(): doctype, content...
2014/02/26
[ "https://Stackoverflow.com/questions/22036124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2113279/" ]
Chain `=`, since you're assining immutable `None` to them: ``` doctype = content_type = framework = cms = server = None ``` If you wanna use the `reset` function, you have to declare them as `global` inside it: ``` def reset(): global doctype, content_type, framework, cms, server doctype = content_type = fr...
I would use **one** global mutable object in this case, `dict` for example: ``` conf = dict.fromkeys(['doctype', 'content_type', 'framework', 'cms', 'server']) def reset(): for k in conf: conf[k] = None ``` or class. This way you can incapsulate `reset` in class itself: ``` class Config(): doctype ...
8,673
50,878,885
I am new in machine learning area. i am trying to run python program on browser by converting trained model in tensorflow js. [this attention\_ocr](https://github.com/tensorflow/models/tree/master/research/attention_ocr/python) is related to OCR written in python. i have generated HDF5/H5 file and converted that in we...
2018/06/15
[ "https://Stackoverflow.com/questions/50878885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8367883/" ]
Lambda (native code) layers are not supported in TensorFlow.js. You will need to replace it with a custom layer. This is tricky. Here is an example custom layer: <https://github.com/tensorflow/tfjs-examples/tree/master/custom-layer>
You have to create a custom layer class as @BlessedKey stated above (<https://github.com/tensorflow/tfjs-examples/tree/master/custom-layer>). You also have to edit the model.json file. The model definition must be updated point to the new class you created for your custom layer instead of the Lambda class. Find the la...
8,675
66,988,750
**Summary**: I'm trying to use multiprocess and multiprocessing to parallelise work with the following attributes: * Shared datastructure * Multiple arguments passed to a function * Setting number of processes based on current system **Errors**: My approach works for a small amount of work but fails with the follow...
2021/04/07
[ "https://Stackoverflow.com/questions/66988750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7482692/" ]
The way to avoid changing the ulimit is to make sure that your process pool size does not increase beyond 1024. That's why 1000 works and 10000 fails. Here's an example of managing the processes with a Pool which will ensure you don't go above the ceiling of your ulimit value: ``` from multiprocessing import Pool de...
Check limit on number of file descriptors. I changed my ulimit to `4096` from `1024` and it worked. Check: ``` ulimit -n ``` For me it was `1024`, and I updated it to `4096` and it worked. ``` ulimit -n 4096 ```
8,676
5,014,261
I'm using win32com.client to write data to an excel file. This takes too much time (the code below simulates the amount of data I want to update excel with, and it takes ~2 seconds). Is there a way to update multiple cells (with different values) in one call rather than filling them one by one? or maybe using a differ...
2011/02/16
[ "https://Stackoverflow.com/questions/5014261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619303/" ]
A few suggestions: **ScreenUpdating off, manual calculation** Try the following: ``` xlsApp.ScreenUpdating = False xlsApp.Calculation = -4135 # manual try: # worksheet = ... for i in range(...): # finally: xlsApp.ScreenUpdating = True xlsApp.Calculation = -4105 # automatic ``` **Assign sev...
used the range suggestion of the other answer, I wrote this: ``` def writeLineToExcel(wsh,line): wsh.Range( "A1:"+chr(len(line)+96).upper()+"1").Value=line xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlDoc = xlApp.Workbooks.Open("test.xlsx") wsh = xlDoc.Sheets("Sheet1") writeLineToExcel(wsh,[1, 2, 3, ...
8,677
67,887,059
I am trying to create a python code that will read the subject of the most recent email in every folder of my outlook account. I am able to open my email account and loop through every folder in it, however I cannot open my most recent email. I looked at similar questions and tried using the `get.Last()` method. To u...
2021/06/08
[ "https://Stackoverflow.com/questions/67887059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16163886/" ]
`Workbooks.Open` does have a `notify` parameter to indicate to wait until the file can be opened for read/write. It presents an interface to the user, so if your application is unattended, that probably isn't a good solution. In that case, I would set up a timer to retry after a short time period. The `Thread.Sleep` so...
For anyone struggling with this problem in the future, I later came across scenarios when the accepted answer didn't quite work how I wanted it to. Here is what I came up with: ``` using System; using System.Threading; private void writeExcel() { string path = @"C:\Users\ed0510\Desktop\SomeExcel.xlsx"; if (I...
8,679
196,930
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() T...
2008/10/13
[ "https://Stackoverflow.com/questions/196930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18745/" ]
Python has the lovely 'platform' module to help you out. ``` >>> import platform >>> platform.win32_ver() ('XP', '5.1.2600', 'SP2', 'Multiprocessor Free') >>> platform.system() 'Windows' >>> platform.version() '5.1.2600' >>> platform.release() 'XP' ``` NOTE: As mentioned in the comments proper values may not be retu...
The simplest solution I found is this one: ``` import sys def isWindowsVista(): '''Return True iff current OS is Windows Vista.''' if sys.platform != "win32": return False import win32api VER_NT_WORKSTATION = 1 version = win32api.GetVersionEx(1) if not version or len(version) < 9: ...
8,680
63,621,597
I have a pandas dataframe where I need to conditionally update the value based on the first two letters. The pattern is simple and the code below works, but it doesn't feel pythonic. I need to extend this to other letters (at least 11-19/A-J) and, while I could just add additional rows, I'd really like to do this the r...
2020/08/27
[ "https://Stackoverflow.com/questions/63621597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12140123/" ]
As already noticed, the sponsored links are simply not at their position before some mouse event occurs. Once the mouse event occurs, the elements are added to the DOM, supposedly this is how Facebook avoids people crawling it too easily. So, if you have a quest to find the sponsored links, then you will need to do th...
The approach I took to solve this issue is as follows: ``` // using an IIFE ("Immediately-Invoked Function Expression"): (function() { 'use strict'; // using Arrow function syntax to define the callback function // supplied to the (later-created) mutation observer, with // two arguments (supplied automatically by...
8,688
4,936,594
I'm writing a chat program in Python that needs to connect to a server before user input from sys.stdin is accepted. If a connection cannot be made then the program exits. Running this from the shell, if a connection fails and input was sent while attempting to connect, the input is echoed to the shell after the progr...
2011/02/08
[ "https://Stackoverflow.com/questions/4936594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396241/" ]
Well, You should do something like that (pseudo-code): 1 - start a transaction 2 - post master record 3 - get the id inserted on master 4 - pass the master id to detail dataset 5 - post detail record 6 - If it worked, commit transaction. Otherwise, rollback transaction.
Just an side note: CTP of the new SQL Server codename 'Denali' will bring the feature of SEQUENCES, working much near of whar firebird generator works. So this task will become MUCH easier: When you get the command from gui to start an insert, get an ID from sequence Use it to fill the PK field of master record Post ...
8,690
62,673,374
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg). To do so, i'm using this line of code: ``` minio = Minio('myip', access_key='mykey', secret_key...
2020/07/01
[ "https://Stackoverflow.com/questions/62673374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13834756/" ]
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead. For example: ``` names = [img2.object_name for img2 in images] print(random.choice(names)) ```
``` minio = Minio('myip', access_key='mykey', secret_key='mykey', ) images = minio.list_objects('mybucket', recursive=True) names = [] for img2 in images: names.append(img2.object_name) print(random.choice([names])) ``` Try this, the problem may that your names was...
8,691
15,643,094
I'm a programming novice and only rarely use python so please bear with me as I try to explain what I am trying to do :) I have the following XML: ``` <?xml version = "1.0" encoding = "utf-8"?> <Patients> <Patient> <PatientCharacteristics> <patientCode>3</patientCode> ...
2013/03/26
[ "https://Stackoverflow.com/questions/15643094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/704003/" ]
You can iterate over all the "visit" tags directly under an element "element" like this: ``` for x in element.iter("visit"): ``` You can find the first direct child of element matching a certain tag with: ``` element.find( "visits" ) ``` It looks like you will first have to locate the "visits" element, which is t...
You could use a CssSelector to get the nodes you want from the Patient element: ``` from lxml.cssselect import CSSSelector visitSelector = CSSSelector('Visit') visits = visitSelector(child) ``` you can do the same to get the patientCode Tag and the SWOL28 tag then you can access and modifiy the text of the elements...
8,694
36,669,131
I matched 2 columns in a DataFrame and yield the result in Boolean value in a new 'bool' column. First I wrote: ``` df_new = df[[7 for 32 in df if df 39 == 'False']] ``` But it didn't work. Then I wrote only to match the columns My code is ``` df['bool'] = (df.iloc[:, 7] == df.iloc[:, 32]) ``` The above code ma...
2016/04/16
[ "https://Stackoverflow.com/questions/36669131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4673147/" ]
You can compare the columns directly: ``` df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 3, 2]}) df['Bool'] = df.a == df.b >>> df a b Bool 0 1 1 True 1 2 3 False 2 3 2 False ``` To filter for False values, use the negation flag, i.e. `~`: ``` >>> df[~df.Bool] a b Bool 1 2 3 False 2 3 2 Fa...
I don't know your situation, I get the "FutureWarning: in the future, boolean array-likes will be handled as a boolean array index" when I use those code as below: ``` >>> import numpy as np >>> test=np.array([1,2,3]) >>> test3=test[[False,True,False]] __main__:1: FutureWarning: in the future, boolean array-likes will...
8,699
64,637,084
Could anyone please help me with why I am getting the below error, everything worked before when I used the same logic, after I converted my data type of date columns to the appropriate format. Below is the line of code I am trying to run ``` data['OPEN_DT'] = data['OPEN_DT'].apply(lambda x: datetime.strptime(x,'%Y-%...
2020/11/01
[ "https://Stackoverflow.com/questions/64637084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559396/" ]
I assumed that you don't want to repeat the add button, then, I removed the button from the template, that way you can only add the input fields: Here you can find a working example: <https://stackblitz.com/edit/js-gp6xjx?file=index.html> ```js const data = []; const appendContent = () => { let form_content = docu...
Alright, so I was fiddling with it a little bit, I'm not very experienced with pure javascript. I came up with a few ideas: 1 - Separate submit and add field buttons. When you press add field, it just adds new fields inside your form which will later be submitted as part of a complete form. 2 - Indexed forms The id...
8,700
44,872,673
Let's say I have this code in `test.py`: ``` import sys a = 'alfa' b = 'beta' c = 'gamma' d = 'delta' print(sys.argv[1]) ``` Running `python test.py a` would then return `a`. How can I make it return `alfa` instead?
2017/07/02
[ "https://Stackoverflow.com/questions/44872673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4931616/" ]
Using a dictionary that maps to those strings: ``` mapping = {'a': 'alfa', 'd': 'delta', 'b': 'beta', 'c': 'gamma'} ``` Then when you get your `sys.argv[1]` just access the value from your dictionary as: ``` print(mapping.get(sys.argv[1])) ``` Demo: File: `so_question.py` ``` import sys mapping = {'a': 'alf...
You can also use the `globals` or `locals`: ``` import sys a = 'alfa' b = 'beta' c = 'gamma' d = 'delta' print(globals().get(sys.argv[1])) # or print(locals().get(sys.argv[1])) ```
8,701
50,809,096
A few days ago I started getting the following error when using pip (1,2 or 3) to install. \* ``` Traceback (most recent call last): File "/home/c4pta1n/.local/bin/pip", line 7, in <module> from pip._internal import main File "/home/c4pta1n/.local/lib/python2.7/site-packages/pip/_internal/__init__.py", line ...
2018/06/12
[ "https://Stackoverflow.com/questions/50809096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8213561/" ]
[six 1.3.0](https://github.com/benjaminp/six/blob/1.3.0/six.py) doesn't have `add_metaclass`. It was released in 2013 year. Really time to upgrade it.
I found the answer to my issue. Apparently some linux versions have specific versions of pip and six that have to be installed through the distro package manager directly in order to work. There are some nuanced changes in how Debian makes use of pip, especially regarding updates, and they have coded these changes in t...
8,702
28,849,386
How to remove T from time format `%Y-%m-%dT%H:%M:%S` in python? Am using it in my html as ``` <b>Start:{{ start.date_start }}<br/> ```
2015/03/04
[ "https://Stackoverflow.com/questions/28849386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4631100/" ]
``` @register.filter def isotime(datestring): datestring = str(datestring) return datestring.replace("T"," ") ```
Manually format the datetime, don't rely on the default `str()` formatting. You can use [`datetime.datetime.isoformat()`](https://docs.python.org/2/library/datetime.html#datetime.datetime.isoformat) for example, passing in a space as the separator: ``` <b>Start:{{ start.date_start.isoformat(' ') }}<br/> ``` or you ...
8,703
22,882,427
I want to take input as string as raw\_input and want to use this value in another line for taking the input in python. My code is below: ``` p1 = raw_input('Enter the name of Player 1 :') p2 = raw_input('Enter the name of Player 2 :') p1 = input('Welcome %s > Enter your no:') % p1 ``` Here in place of `%s` I want ...
2014/04/05
[ "https://Stackoverflow.com/questions/22882427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3494397/" ]
You can do (the vast majority will agree that this is the best way): ``` p1 = input('Welcome {0} > Enter your no:'.format(p1)) ```
Try ``` input("Welcome " + p1 + "> Enter your no:") ``` It concatenates the value of `p1` to the input string Also see [here](https://docs.python.org/2/library/string.html) ``` input("Welcome {0}, {1} > Enter your no".format(p1, p2)) #you can have multiple values ``` **EDIT** Note that using `+` is [discouraged...
8,704
26,664,102
Here are the commands I am running: ``` $ python setup.py bdist_wheel usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' $ pip --version pip 1.5.6 from /usr/local/...
2014/10/30
[ "https://Stackoverflow.com/questions/26664102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036670/" ]
Update your `pip` first: ``` pip install --upgrade pip ``` for Python 3: ``` pip3 install --upgrade pip ```
I tried everything said here without any luck, but found a workaround. After running this command (and failing) : `bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg` Go to the temporary directory the tool made (given in the output of the last command), then execute `python setup.py bdist_whe...
8,707
39,137,179
I am working on a rails application now that needs to run a single python script whenever a button is clicked on our apps home page. I am trying to figure out a way to have rails run this script, and both of my attempts so far have failed. My first try was to use the exec(..) command to just run the "python script.py...
2016/08/25
[ "https://Stackoverflow.com/questions/39137179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5805587/" ]
Here are ways to execute a shell script ``` `python pythonscript.py` ``` or ``` system( "python pythonscript.py" ) ``` or ``` exec(" python pythonscript.py") ``` exec replaces the current process by running the given external command. Returns none, the current process is replaced and never continues.
`exec` replaces the current process with the new one. You want to run it as a subprocess. See [When to use each method of launching a subprocess in Ruby](https://stackoverflow.com/questions/7212573/when-to-use-each-method-of-launching-a-subprocess-in-ruby) for an overview; I suggest using either backticks for a simple ...
8,717
65,148,247
For an unknown reason, I ran into a docker error when I tried to run a `docker-compose up` on my project this morning. My web container isn't able to connect to the db host and `nc` still returning > > web\_1 | nc: bad address 'db' > > > There is the relevant part of my docker-compose definition : ```yaml versi...
2020/12/04
[ "https://Stackoverflow.com/questions/65148247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950328/" ]
I was able to fix that by running `docker-compose down && docker-compose up` but it could be kinda bad if your down was removing all your volumes and so, your data... The inspection of networking is now alright : ```json [ { "Name": "my_docker_network", "Id": "236c45042b03c3a2922d9a9fabf644048901c...
I had the same problem, but with rabbitmq service in my compose file. At first I solved it by deleting all existing container and volumes on my machine, (but it happened again here and then) but later I updated the rabbitmq image version to latest in `docker-compose.yml`: ``` image: rabbitmq:latest ``` and the probl...
8,718
66,386,685
I'm working on a secure system where internet access is restricted. My company will let my install python and libraries, but they only allow the unblocking of specific urls temporarily. So I need to know what urls do I need to unblock to install python and what urls I need to unblock to execute **pip install pandas** ...
2021/02/26
[ "https://Stackoverflow.com/questions/66386685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12986251/" ]
You can do all that in one loop - that would be way faster. To know the correct position to put the number in, add extra counter for each array. ### Your kind of approach ```java int[] num = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; int[] odd = new int[10]; int[] even = new int[10]; int oddPos = 0; int...
the approach for detecting `odd` and `even` numbers is correct, But I think the problem with the code you wrote is that the length of `odd` and `even` arrays, isn't determinant. so for this matter, I suggest using `ArrayList<Integer>`, let's say you get the array in a function input, and want arrays in the output (I'll...
8,719
70,187,603
I am able to create an image via az cli commands with: ``` az vm create --resource-group $RG2 \ --name $VM_NAME --image $(az sig image-version show \ --resource-group $RG \ --gallery-name $SIG \ --gallery-image-definition $SIG_IMAGE_DEFINITION \ --gallery-image-version $VERSION \ --query id -o tsv) \ --size $SIZE \ --...
2021/12/01
[ "https://Stackoverflow.com/questions/70187603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372429/" ]
You can modify the [example script](https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-example-virtual-machines?tabs=cmd) in our doc to do this. Essentially, you need to get rid of step 4. and modify step 5 to not send a public IP when creating the NIC. This has been validated in my own subscription. `...
``` resource_name = f"myserver{random.randint(1000, 9999)}" VNET_NAME = "myteam-vpn-vnet" SUBNET_NAME = "myteam-subnet" IP_NAME = resource_name + "-ip" IP_CONFIG_NAME = resource_name + "-ip-config" NIC_NAME = resource_name + "-nic" Subnet=network_client.subnets.get(resource_group_name, VNET_NAME, SUBNET_NAME) # S...
8,724
61,037,527
I want to run my code on GPU provided by Kaggle. I am able to run my code on CPU though but unable to migrate it properly to run on Kaggle GPU I guess. On running this ``` with tf.device("/device:GPU:0"): hist = model.fit(x=X_train, y=Y_train, validation_data=(X_test, Y_test), batch_size=25, epochs=20, callbacks=cal...
2020/04/05
[ "https://Stackoverflow.com/questions/61037527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9872938/" ]
Can you try to update `@material-ui/core` by running ``` npm update ```
As described in the Material-UI project [CHANGELOG](https://github.com/mui-org/material-ui/releases/tag/v4.9.9) of the latest version (which is **v4.9.9** the time I'm writing this answer), there is a change related to `createSvgIcon` [![enter image description here](https://i.stack.imgur.com/n8NYJ.png)](https://i.st...
8,725
67,327,106
I am trying to load a serialized xgboost model from a pickle file. ``` import pickle def load_pkl(fname): with open(fname, 'rb') as f: obj = pickle.load(f) return obj model = load_pkl('model_0_unrestricted.pkl') ``` while printing the model object, I am getting the following error in linux(AWS Sagem...
2021/04/30
[ "https://Stackoverflow.com/questions/67327106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140489/" ]
Looks like you upgraded xgboost. You may consider downgrading to 1.2.0 by: ``` pip install xgboost==1.2.0 ```
I tried testing on notebook running on ubuntu, it seems to work fine, however can you check how are you initializing your classifier ? This is what I tried : ``` import numpy as np import pickle from scipy.stats import uniform, randint from sklearn.datasets import load_breast_cancer, load_diabetes, load_wine from skl...
8,726
52,104,644
I have the following function which basically asks user to enter the choice for "X" or "O". I used the while loop to keep asking user until I get the answer that's either "X" or "O". ``` def player_input(): choice = '' while choice != "X" and choice != "O": choice = input("Player 1, choose X or O: ")...
2018/08/30
[ "https://Stackoverflow.com/questions/52104644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9114293/" ]
Loop indexing is well known in Python to be an incredibly slow operation. By replacing a loop with array slicing, and a list with a Numpy array, we see increases @ 3x: ``` import numpy as np import timeit def generate_primes_original(limit): boolean_list = [False] * 2 + [True] * (limit - 1) for n in range(2, ...
If your are still using Python 2 use xrange instead of range for greater speed
8,728
32,478,825
I am using python and scikit-learn to find the cosine similarity between two strings(specifically, names).The program is able to find the similarity score between two strings but, when strings are abbreviated, it shows some undesirable output. e.g- String1 ="K KAPOOR",String2="L KAPOOR" The cosine similarity score of ...
2015/09/09
[ "https://Stackoverflow.com/questions/32478825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4994653/" ]
As mentioned in the other answer, the cosine similarity is one because the two strings have **the exact same representation**. That means that this code: ``` tfidf_vectorizer=TfidfVectorizer() tfidf_matrix=tfidf_vectorizer.fit_transform(documents) ``` produces, well: ``` print(tfidf_matrix.toarray()) [[ 1.] [ 1.]...
> > String1 ="K KAPOOR", String2="L KAPOOR" The cosine similarity score of these strings is 1 (maximum) while the two strings are entirely different names. Is there a way to modify it, in order to get some desired results. > > > **It depends.** You are facing an issue because the vector representation of these two...
8,729
2,545,655
Using Python 2.6.4, windows With the following script I want to test a certain xmlrpc server. I call a non-existent function and hope for a traceback with an error. Instead, the function does not return. What could be the cause? ``` import xmlrpclib s = xmlrpclib.Server("http://127.0.0.1:80", verbose=True) s.function...
2010/03/30
[ "https://Stackoverflow.com/questions/2545655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80500/" ]
As you noticed, this is a bug in the server (the client claims to understand 1.0 and the server ignores that and responds in 1.1 anyway, so doesn't close the socket). Python has a workaround for such buggy servers in 2.7 and 3.2, see [this issue](http://bugs.python.org/issue6267), but that workaround wasn't in 2.6.4. U...
Most likely, the server you're testing does not close the TCP connection once it has sent the response back to your client. Thus the client hangs, waiting for the server to close the connection before it can return from the function.
8,730
59,524,498
I am trying to create a seaborn Facetgrid to plot the normality distribution of all columns in my dataFrame decathlon. The data looks as such: ``` P100m Plj Psp Phj P400m P110h Ppv Pdt Pjt P1500 0 938 1061 773 859 896 911 880 732 757 752 1 839 975 870 749 887 878 ...
2019/12/30
[ "https://Stackoverflow.com/questions/59524498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10574250/" ]
I encountered this similar issue when running a Jupyter Notebook. My solution involved: 1. Restart the notebook 2. Re-run the imports `%matplotlib inline; import matplotlib.pyplot as plt`
As you did not post a full working example its a bit of guessing. What might go wrong is in the line where you have `g = g.map(plt.hist, "values")` because the error comes from deep within matplotlib. You can see this [here](https://stackoverflow.com/questions/40399631/valueerror-axes-instance-argument-was-not-found-i...
8,731
60,182,791
I have tried uploading file to Google Drive from my local system using a Python script but I keep getting HttpError 403. The script is as follows: ```python from googleapiclient.http import MediaFileUpload from googleapiclient import discovery import httplib2 import auth SCOPES = "https://www.googleapis.com/auth/dri...
2020/02/12
[ "https://Stackoverflow.com/questions/60182791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7640700/" ]
Try with this: ``` var str = @"email from Ram at 10:10 am"" ""email from Ramesh at 10:15 am"" ""email from Rajan at 10:20 am"" ""email from Rakesh at 10:25 am"; string[] sl=str.Trim().Split(new string[] { "\" \"" }, StringSplitOptions.None); foreach(string st in sl) { Console.WriteLine(st); } ``` **Output:** ...
It is possible to use additional `"` as they are part of the string literal. And they will be interpreted by the compiler as a single ": ``` var str = @"email from Ram at 10:10 am"" ""email from Ramesh at 10:15 am"" ""email from Rajan at 10:20 am"" ""email from Rakesh at 10:25 am"; var splitted = str.Split...
8,732
9,833,152
> > **Possible Duplicate:** > > [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) > > > If I have a string that looks something like... ``` "<tr><td>123</td><td>234</td>...<td>697</td></tr>" ``` Basica...
2012/03/23
[ "https://Stackoverflow.com/questions/9833152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399523/" ]
If that markup is part of a larger set of markup, you should prefer a tool with a HTML parser. One such tool is [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). Here's one way to find what you need using that tool: ``` >>> markup = '''"<tr><td>123</td><td>234</td>...<td>697</td></tr>"''' >>> from ...
Don't do this. Just use a proper HTML parser, and use something like xpath to get the elements you want. A lot of people like lxml. For this task, you will probably want to use the BeautifulSoup backend, or use BeautifulSoup directly, because this is presumably not markup from a source known to generate well-formed, v...
8,733
58,350,100
I am trying to solve this [Dynamic Array problem](https://www.hackerrank.com/challenges/dynamic-array/problem?isFullScreen=true) on HackerRank. This is my code: ```py #!/bin/python3 import math import os import random import re import sys # # Complete the 'dynamicArray' function below. # # The function is expected t...
2019/10/12
[ "https://Stackoverflow.com/questions/58350100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598839/" ]
you can try this, it works totally fine.(no runtime error) ========================================================== > > Replace your dynamicArray function with this code. Hopefully this will be helpful for you (^\_^). > > > def dynamicArray(n, queries): ``` col = [[] for i in range(n)] res = [] lastanswer = 0 ...
The answer to your question lies in the boilerplate provided by hackerrank. `# The function is expected to return an INTEGER_ARRAY.` You can also see that `result = dynamicArray(n, queries)` is expected to return a list of integers from `map(str, result)`, which throws the exception. In your code you do `print(lastA...
8,735
23,211,546
I had asked a similar question [here](https://stackoverflow.com/questions/23159053/re-read-a-file-from-start-after-the-program-finishes-reading-it-python/23159107) and the answer that I get was to use the `seek()` method. Now I am doing the following: ``` with open("total.csv", 'rb') as input1: time.sleep(3) i...
2014/04/22
[ "https://Stackoverflow.com/questions/23211546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3534055/" ]
For simplicity, create an generator: ``` def repeated_reader(input, reader): while True: input.seek(0) for row in reader: yield row with open("total.csv", 'rb') as input1: reader = csv.reader(input1, delimiter="\t") for row in repeated_reader(input1, reader): #Read the ...
Does it have to be in the `for`-loop? You could achieve this behaviour like this (untested): ``` with open("total.csv", 'rb') as input1: time.sleep(3) reader = csv.reader(input1, delimiter="\t") while True: input1.seek(0) for row in reader: #Read the CSV row by row. ```
8,738
49,783,902
In python, if I use a ternary operator: ``` x = a if <condition> else b ``` Is `a` executed even if `condition` is false? Or does `condition` evaluate first and then goes to either `a` or `b` depending on the result?
2018/04/11
[ "https://Stackoverflow.com/questions/49783902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3754760/" ]
The condition is evaluated first, if it is False, `a` is not evaluated: [documentation](https://docs.python.org/3/reference/expressions.html#conditional-expressions).
It gets evaluated depending if meets the condition. For example: ``` condition = True print(2 if condition else 1/0) #Output is 2 print((1/0, 2)[condition]) #ZeroDivisionError is raised ``` No matter if `1/0` raise an error, is never evaluated as the condition was True on the evaluation. Sames happen in the other ...
8,741
58,512,790
I'm wanting to wrap some c++ code in python using swig, and I need to be able to use numpy.i to convert numpy arrays to vectors. This has been quite the frustrating process, as I haven't been able to find any useful info online as to where I actually get numpy.i from. This is what I currently have running: numpy 1...
2019/10/22
[ "https://Stackoverflow.com/questions/58512790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12114274/" ]
**Problem:** The numpy.i file I copied over from the python2.7 package isn't compatible, and the compatible version isn't included in the installation package when you go through anaconda (still not sure why they'd do that). **Answer:** Find which version of numpy you're running, then go here (<https://github.com/nump...
You should download new numpy.i file from <https://github.com/numpy/numpy/blob/master/tools/swig/numpy.i>. In this numpy.i file have no PyFile\_Check function, which python3 don't support. If you still use `/usr/lib/python2.7/dist-packages/instant/swig/numpy.i`, your code may appear error `undefined symbol: PyFile_Chec...
8,742
45,966,355
I would like to write a function which performs efficiently this "strange" sort (I am sorry for this pseudocode, it seems to me to be the clearest way to introduce the problem): ``` l=[[A,B,C,...]] while some list in l is not sorted (increasingly) do find a non-sorted list (say A) in l find the first two non-sorte...
2017/08/30
[ "https://Stackoverflow.com/questions/45966355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7871040/" ]
Here's a simple implementation that could use some improvement: ``` def strange_sort(lists_to_sort): # reverse so pop and append can be used lists_to_sort = lists_to_sort[::-1] sorted_list_of_lists = [] while lists_to_sort: l = lists_to_sort.pop() i = 0 # l[:i] is sorted ...
Firstly you would have to implement a `while` loop which would check if all of the numbers inside of the lists are sorted. I will be using `all` which checks if all the objects inside a sequence are `True`. ``` def a_sorting_function_of_some_sort(list_to_sort): while not all([all([number <= numbers_list[numbers_li...
8,743
55,218,096
Right now I am trying to write a python script which could give a binary result to check if my machine is connected to Corporate\_VPN (Connection\_Name) OR Not connected to Corporate\_VPN. I have tried few articles and post which I could find but with no success. Here are some: I have tried this post: [Getting Connec...
2019/03/18
[ "https://Stackoverflow.com/questions/55218096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8042963/" ]
For three numbers specifically, there are two basic approaches: * you can sort the three numbers and return the middle number from the sorted array. For this, a three-stage sorting network is generally useful. To build this, use this primitive which swaps `r0` and `r1` if `r0` is larger than `r1`, using `r3` as a temp...
What was the exact problem you encountered? Your `CMP` instruction is fine, and will set the status flags depending on the relative values of `R0` and `R1`, so you can then use a conditional branch (e.g. `BHI` or `BGT`) or one of the `IT` family of instructions that will allow you to execute other instructions conditio...
8,744
56,744,322
I am creating an E-commerce now when I try adding an Item into the cart it returns the error above? It is complaining about this line of code in the view: ``` else: order.items.add(order_item) ``` View ``` def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.obj...
2019/06/24
[ "https://Stackoverflow.com/questions/56744322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10374065/" ]
The Django [**`get_or_create(..)`** [Django-doc]](https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create), does *not* return a model instance, it returns a 2-tuple with the object, and a boolean (whether it created a record or not). Or as written in the documentation: > > (..) > > > Returns a tup...
add the below line into this. Just add 'created' as below. ``` order_item, created = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) ```
8,745
45,582,838
Is there a way to convert the string **"12345678aaaa12345678bbbbbbbb"** to **"12345678-aaaa-1234-5678-bbbbbbbb"** in python? I am not sure on how to do it, since I need to insert "-" after elements of variable lengths say after 8th element then 4th element and so on.
2017/08/09
[ "https://Stackoverflow.com/questions/45582838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123705/" ]
This function inserts a char at a postion for a string: ``` def insert(char,position,string): return string[:position] + char + string[position:] ```
Python strings cannot be mutated. What we can do is create another string with the hyphen inserted in between, as per your wish. Consider the string s = "12345678aaaa12345678bbbbbbbb" Giving `s[:8] + '-' + s[8:] will give you 12345678-aaaa12345678bbbbbbbb` You can give the hyphen as you wish by adjusting the `:` val...
8,746
14,412,907
I'm trying to scrape the [NDTV](http://en.wikipedia.org/wiki/NDTV) website for news titles. [This](http://archives.ndtv.com/articles/2012-01.html) is the page I'm using as a HTML source. I'm using BeautifulSoup (bs4) to handle the HTML code, and I've got everything working, except my code breaks when I encounter the hi...
2013/01/19
[ "https://Stackoverflow.com/questions/14412907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
What you see is a NavigableString instance (which is derived from the Python unicode type): ``` (Pdb) hypref.encode('utf-8') 'NDTV' (Pdb) hypref.__class__ <class 'bs4.element.NavigableString'> (Pdb) hypref.__class__.__bases__ (<type 'unicode'>, <class 'bs4.element.PageElement'>) ``` You need to convert to utf-8 usin...
``` strhyp = hypref.encode('utf-8') ``` <http://joelonsoftware.com/articles/Unicode.html>
8,755
29,318,565
I am writing a raingauge precipitation calculator based in the radius of the raingauge. When I run my script, I have this error message: ``` Type de raingauge radius [cm]: 5.0 Traceback (most recent call last): File "pluviometro.py", line 27, in <module> area_bocal = (pi * (raio_bocal * raio_bocal)) # cm.cm Type...
2015/03/28
[ "https://Stackoverflow.com/questions/29318565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824522/" ]
As mentioned in the [docs](https://docs.python.org/3/library/functions.html#input) > > The function then reads a line from input, **converts it to a string** (stripping a trailing newline), and returns that > > > So you need to type cast it to `float` explicitly ``` raio_bocal = float(input("Type de raingauge r...
You need to cast to float, input returns a string in python3: ``` float(input("Type de raingauge radius [cm]:")) ``` Probably safer use a while loop with a try/except when casting input. ``` while True: inp = input("Type de raingauge radius [cm]:") try: raio_bocal = float(inp) break except ...
8,756
35,258,492
I have a directory containing a certificate bundle, a Python script and a Node script. Both scripts make a GET request to the same URL and are provided with the same certificate bundle. The Python script makes the request as expected however the node script throws this error: > > { [Error: unable to verify the first ...
2016/02/07
[ "https://Stackoverflow.com/questions/35258492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066031/" ]
The [documentation](https://nodejs.org/api/https.html#https_https_request_options_callback) describes the `ca` option as follows: > > **ca: A string, Buffer or array of strings or Buffers of trusted certificates in PEM format. If this is omitted several well known "root" CAs will be used, like VeriSign. These are use...
Maybe you can use this module that fixes the problem, by downloading certificates usually used by browsers. <https://www.npmjs.com/package/ssl-root-cas>
8,757
43,935,569
my device will sent json data like this: ``` [{"channel":924125000, "sf":10, "time":"2017-05-11T16:56:15", "gwip":"192.168.1.125", "gwid":"00004c4978dbf5b4", "repeater":"00000000ffffffff", "systype":5, "rssi":-108.0, "snr":17.0, "snr_max":23.3, "snr_min":10.8, "macAddr":"00000000000000c3", "data":"47024830163312101791...
2017/05/12
[ "https://Stackoverflow.com/questions/43935569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8002033/" ]
because you have multiple objects in your json you should include them in a list : ``` json_List = json.loads('[' + jsonData + ']') ```
Paste it in a Tool like [JSONLINT](https://jsonlint.com/) and you get: > > Error: Parse error on line 17: > ...": 1, "fport": 2}], [{ "channel": 924 > ---------------------^ > Expecting 'EOF', got ',' > > > which is the cause of your error. This is not *valid* JSON. The correct structure would be something li...
8,758
5,524,241
I have two custom Django fields, a `JSONField` and a `CompressedField`, both of which work well. I would like to also have a `CompressedJSONField`, and I was rather hoping I could do this: ``` class CompressedJSONField(JSONField, CompressedField): pass ``` but on import I get: ``` RuntimeError: maximum recursio...
2011/04/02
[ "https://Stackoverflow.com/questions/5524241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/88411/" ]
after doing a few quick tests i found that if you remove the **metaclass** from the JSON and compressed fields and put it in the compressedJSON field it compiles. if you then need the JSON or Compressed fields then subclass them and jusst add the `__metaclass__ = models.SubfieldBase` i have to admit that i didn't do a...
It is hard to understand when exactly you are getting that error. But looking at DJango code, there is simlar implementation (multiple inheritance) refer: **class ImageFieldFile(ImageFile, FieldFile)** in django/db/models/fields
8,759
430,226
I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past. A couple scenarios I've come up with: 1. The querying process starts every X seconds, eg a cron job runs...
2009/01/10
[ "https://Stackoverflow.com/questions/430226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
"Do I just run a python script that doesn't end?" How is this unfamiliar territory? ``` import time polling_interval = 36.0 # (100 requests in 3600 seconds) running= True while running: start= time.clock() poll_twitter() anything_else_that_seems_important() work_duration = time.clock() - start tim...
You should have a page that is like a Ping or Heartbeat page. The you have another process that "tickles" or hits that page, usually you can do this in your Control Panel of your web host, or use a cron if you have a local access. Then this script can keep statistics of how often it has polled in a database or some dat...
8,760
42,673,016
I tried to make a checkbutton which is supposed to activate a function "rond" but it's not working... What have I done wrong ? ``` from tkinter import* def rond(): if okok.get()==1: print("ok") okok = BooleanVar() okok.set(0) root = Tk() can = Canvas(root, width=200, height=150, bg="light yellow") can.bind("<Bu...
2017/03/08
[ "https://Stackoverflow.com/questions/42673016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7678528/" ]
There are three problems: 1. The exception you are getting is because you have to create `root = Tk()` before the `BooleanVar`. 2. As already noted, you should use the [`Checkbutton`](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/checkbutton.html) widget instead of `Canvas`. The `command` then goes directly into t...
It looks like you're using canvas and not the check button. I would try something like this: cbutton = Checkbutton(root, etc, etc) or check out effbot.org for a good resource.
8,761
70,150,128
This is my project structure [![Project Structure](https://i.stack.imgur.com/BrsjM.png)](https://i.stack.imgur.com/BrsjM.png) I am able to access the default SQLite database `db.sqlite3` created by Django, by importing the models directly inside of my views files Like - `from basic.models import table1` Now, I hav...
2021/11/29
[ "https://Stackoverflow.com/questions/70150128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11827709/" ]
You can specify specific database as specified in [Documentation](https://docs.djangoproject.com/en/3.2/ref/django-admin/#cmdoption-inspectdb-database) ``` python manage.py inspectdb --database=otherdb > your_app/models.py ``` Also if possible putting otherdb in a different App is better.
You can attach the second database to the first one and use it from within the first one. You can use tables from both databases in single sql query. Here is the doc <https://www.sqlite.org/lang_attach.html>. ``` attach database '/path/to/dbfile.sqlite' as db_remote; select * from some_table join db_remote.remote_ta...
8,762
6,282,519
I'm not sure if I'm even asking this question correctly. I just built my first real program and I want to make it available to people in my office. I'm not sure if I will have access to the shared server, but I was hoping I could simply package the program (I hope I'm using this term correctly) and upload it to a websi...
2011/06/08
[ "https://Stackoverflow.com/questions/6282519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1382299/" ]
[PyInstaller](http://www.pyinstaller.org/) or [py2exe](http://www.py2exe.org/) can package your Python program. Both are actively maintained. PyInstaller is actively maintained. py2exe has not been updated for at least a year. I've used each with success. Also there is [cx\_Freeze](http://cx-freeze.sourceforge.net/...
Take a look at <http://www.py2exe.org/>
8,764
63,890,399
I am working with a dataframe which looks similar to this ``` Ind Pos Sample Ct LogConc RelConc 1 B1 wt1A 26.93 -2.0247878 0.009445223 2 B2 wt1A 27.14 -2.0960951 0.008015026 3 B3 wt1B 26.76 -1.9670628 0.010787907 4 B4 wt1B 26.94 -2.0281834 0.009371662 5 B5 wt1C 26.01...
2020/09/14
[ "https://Stackoverflow.com/questions/63890399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11637268/" ]
In `base R`, we can use `ave` and it is very fast ``` df1$AverageRelConc <- with(df1, ave(RelConc, Sample)) ``` -output ``` df1$AverageRelConc #[1] 0.008730125 0.008730125 0.010079784 0.010079784 0.018874878 0.018874878 0.024430844 0.024430844 0.393766166 0.393766166 #[11] 0.396856943 0.396856943 ``` --- Or usin...
Try this `tidyverse` option: ``` library(tidyverse) #Code df %>% group_by(Sample) %>% mutate(AvgRelConc=mean(RelConc,na.rm=T)) ``` Output: ``` # A tibble: 12 x 7 # Groups: Sample [6] Ind Pos Sample Ct LogConc RelConc AvgRelConc <int> <chr> <chr> <dbl> <dbl> <dbl> <dbl> 1 1 B1 wt1A...
8,765
4,666,527
Does anyone have some good resources on learning more advanced regular expressions I keep having problems where I want to make sure something is not enclosed in quotation marks i.e. I am trying to make an expression that will match lines in a python file containing an equality, i.e. ``` a = 4 ``` which is easy eno...
2011/01/12
[ "https://Stackoverflow.com/questions/4666527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392485/" ]
Parsing code with regular expressions is generally not a good idea, as the grammar of a programming language is not a regular language. I'm not much of a python programmer, but I think you would be a lot better off parsing python code with python modules such as [this one](http://docs.python.org/library/parser.html) or...
Python has an excellent [Language Reference](http://docs.python.org/reference/index.html) that also includes [descriptions of the lexical analysis and syntax](http://docs.python.org/reference/introduction.html#notation). In your case both statements are [assignments](http://docs.python.org/reference/simple_stmts.html#...
8,766
55,338,811
I'm currently working on a small project to learn python. This project creates a random forest, then sets the forest up on fire to stimulate a forest fire. So I managed to create the forest out using a function. The forest is just an array of 0s and 1s. 0 to represent water, 1 to present a tree. So now I'm currently r...
2019/03/25
[ "https://Stackoverflow.com/questions/55338811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11255128/" ]
use not exists ``` select mygroup from table_name t1 where not exists( select 1 from table_name t2 where t1.var2=t2.var1 and t1.mygroup=t2.mygroup) and t1.var2 is not null ```
Another approach to use cte and temptables: 1. Find out the var2 values that is not included in var1 for the same mygroup 2. List the mygroups and group them there var2 in the list you have found in step 1. Try below: ``` create table #temp (mygroup int, var1 int, var2 int) insert into #temp values (1 , 1, ...
8,768
59,289,903
Please help me make sense of this big fat error output. At this point I don't know which end is up. I have been spinning my wheels for days on this. This is **not** the first/only package installation that has given me these errors, but the project ran fine anyway, so I ignored it. Now I want a new package, and it wo...
2019/12/11
[ "https://Stackoverflow.com/questions/59289903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9068961/" ]
I don't know *why* this worked, but running a regular yarn-upgrade cleared the errors. I still got warnings about dependencies. I should have saved the terminal output from yarn-outdated before and after the upgrade, but alas, I did not. I still show a few mismatched dependencies.
deasync try´s to compile itself if it did not find a precompiled version for current Node version. This compilation has additional requirements so it is easier to use deasync/Node combinations where precompiled packages exists: * <https://github.com/abbr/deasync/issues/106> * <https://github.com/abbr/deasync-bin>
8,769
64,870,829
Let's say I have a list `list = ['aa', 'bb', 'aa', 'aaa', 'bbb', 'bbbb', 'cc']` if you do `list.sort()` you get back `['aa', 'aa', 'aaa', 'bb', 'bbb', 'bbbb', 'cc']` Is there a way in **python 3** we can get `['aaa', 'aa', 'aa', 'bbbb', 'bbb', 'bb', 'cc']` So within the same lexicographical group order, pick th...
2020/11/17
[ "https://Stackoverflow.com/questions/64870829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10688867/" ]
You can redefine what less-than means for the strings with a custom class. Use that class as the key for `list.sort` or `sorted`. ``` class C: def __init__(self, val): self.val = val def __lt__(self, other): min_len = min((len(self.val), len(other.val))) if self.val[:min_len] == other...
Tuples are ordered lexicographically, so you can use a tuple of (first character of string, negative length) as the sort key: ```python list.sort(key=lambda s: (s[0], -len(s))) ```
8,770
36,590,496
``` #!/usr/bin/python import requests import uuid random_uuid = uuid.uuid4() print random_uuid url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials" payload = '''json={ "": "0", "credentials": { "scope": "GLOBAL", "id": "random_uuid", "usern...
2016/04/13
[ "https://Stackoverflow.com/questions/36590496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6133947/" ]
You'll can use string formatting for that. In your JSON string, replace random\_uuid with %s, than do: ``` payload = payload % random_uuid ``` Another option is to use `json.dumps` to create the json: ``` payload_dict = { 'id': random_uuid, ... } payload = json.dumps(payload_dict) ```
This code may help. ``` #!/usr/bin/python import requests import uuid random_uuid = uuid.uuid4() print random_uuid url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials" payload = '''json={ "": "0", "credentials": { "scope": "GLOBAL", "id": "%s", ...
8,772
23,414,509
I have common problem. I have some data and I want search in them. My issue is, that I dont know a proper data structures and algorhitm suitable for this situation. There are two kind of objects - `Process` and `Package`. Both have some properties, but they are only data structures (dont have any methods). Next, there...
2014/05/01
[ "https://Stackoverflow.com/questions/23414509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285282/" ]
I would move the case into its own method on your Team model. ``` class Team def tree(type) ... end end ``` Then in your controller you could just have the following ``` if @team = fetch_team @output = @team.tree(params[:tree]) render json: @output else render json: {message: "team: '#{params[:id]}' ...
You could write ``` if @team = fetch_team @output = case params[:tree] when 'parents' then @team.ancestor_ids when 'children' then @team.child_ids when 'full' then @team.full_tree when nil then @team else {message: "requested query parameter: '#{params[:tre...
8,777
42,471,570
I am trying to build a classification model. I have 1000 text documents in local folder. I want to divide them into training set and test set with a split ratio of 70:30(70 -> Training and 30 -> Test) What is the better approach to do so? I am using python. --- I wanted a approach programatically to split the trainin...
2017/02/26
[ "https://Stackoverflow.com/questions/42471570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5024829/" ]
that's quite simple if you use numpy, first load the documents and make them a numpy array, and then: ``` import numpy as np docs = np.array([ 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', ]) idx = np.hstack((np.ones(7), np.zeros(3))) # generate indices np.random.shuffle(...
Just make a list of the filenames using `os.listdir()`. Use `collections.shuffle()` to shuffle the list, and then `training_files = filenames[:700]` and `testing_files = filenames[700:]`
8,778
39,516,760
I have a string that I pull from a REST API that is actually a JSON. I can't use `req.json()` as python doesn't format json correctly i.e. it is using single quotes and not double quotes, plus it puts a unicode symbol where there shouldn't be one. This means I can't use it to respond back to REST as the JSON is not f...
2016/09/15
[ "https://Stackoverflow.com/questions/39516760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164102/" ]
You can check if a string is valid json by catching the error. ``` import json def is_json(myjson): try: json_object = json.loads(myjson) except ValueError, e: return False return True ``` Test cases: ``` print is_json("{}") #prints True print is_json("{asdf}") ...
``` import json request_as_json = json.loads(r.text) ``` Then you can call things like `request_as_json['key']` ["More Info Here"](http://docs.python.org/library/json.html#json.loads)
8,783
56,590,075
I'm trying to read a timeseries of a single [WRF](https://www.mmm.ucar.edu/weather-research-and-forecasting-model) output variable. The time series is distributed, one timestamp per file, across more than 5000 netCDF files. Each file contains roughly 200 variables. Is there a way to call xarray.open\_mfdataset() for o...
2019/06/14
[ "https://Stackoverflow.com/questions/56590075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1854821/" ]
I'm not sure why providing the `data_vars=` argument still reads all data - I experienced the same issue reading WRF output. My workaround was to make a list of all the variables I didn't need (all 200+) and feed that to the `drop_variables=` argument. You can get a list of all variables and then just delete or comment...
As a follow up for the ones who will find this thread later. Based on the documentation (but a bit hidden), the "data\_vars=" argument only works with Python 3.9.
8,785
9,197,385
I'm using AWS for the first time and have just installed boto for python. I'm stuck at the step where it advices to: "You can place this file either at /etc/boto.cfg for system-wide use or in the home directory of the user executing the commands as ~/.boto." Honestly, I have no idea what to do. First, I can't find th...
2012/02/08
[ "https://Stackoverflow.com/questions/9197385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815878/" ]
> > "You can place this file either at /etc/boto.cfg for system-wide use > or in the home directory of the user executing the commands as > ~/.boto." > > > The former simply means that you might create a configuration file named `boto.cfg` within directory `/etc` (i.e. it won't necessarily be there already, depe...
For those who want to configure the credentials in Windows: 1-Create your file with the name you want(e.g boto\_config.cfg) and place it in a location of your choice(e.g C:\Users\\configs). 2- Create an environment variable with the Name='BOTO\_CONFIG' and Value= file\_location/file\_name 3- Boto is now ready to wor...
8,788
45,382,917
I cannot successfully run the `optimize_for_inference` module on a simple, saved TensorFlow graph (Python 2.7; package installed by `pip install tensorflow-gpu==1.0.1`). Background ========== Saving TensorFlow Graph ----------------------- Here's my Python script to generate and save a simple graph to add 5 to my in...
2017/07/28
[ "https://Stackoverflow.com/questions/45382917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5874320/" ]
**Here is the detailed guide on how to optimize for inference:** The `optimize_for_inference` module takes a `frozen binary GraphDef` file as input and outputs the `optimized Graph Def` file which you can use for inference. And to get the `frozen binary GraphDef file` you need to use the module `freeze_graph` which ta...
1. You are doing it wrong: `input` is a graphdef file for the [script](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/optimize_for_inference.py) not the data part of the checkpoint. You need to freeze the model to a `.pb` file/ or get the prototxt for graph and use the optimize for inferen...
8,790
309,135
I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit. I need Pros and Cons for Python development between this two editors...
2008/11/21
[ "https://Stackoverflow.com/questions/309135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35425/" ]
I use both Komodo Edit and Notepad++. Notepad++ is a lot quicker to launch and it's more lightweight, so I often use it for quick one-off editing. I use Komodo Edit for major projects, like my django and wxPython applications. KE is a full-featured IDE, so it has a lot more features. Main advantages of Komodo Edit ...
I haven't used Komodo yet (the download never quite finished on the slow connection I was on at the time), but I use Eclipse with PyDev regularly and enjoy the "IDE" features described by the other respondents. However, I'm also regularly frustrated by how much of a resource hog it is. I downloaded Notepad++ recently ...
8,791
5,495,143
``` var data; $(document).ready(function(){ var rows = document.getElementById("orderlist_1").rows; var cell = rows[rows.length - 1].cells[3]; data = "id="+cell.innerHTML checkAndNotify(); }) function checkAndNotify() { alert("oo"); $("#shownoti").load("/mostrecenttransaction","id=2008010661301520679"); ...
2011/03/31
[ "https://Stackoverflow.com/questions/5495143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167814/" ]
``` jQuery.ajax({ url: "mostRecentTransaction", type: "GET", data: { id : 2008010661301520679 }, success: function(data) { alert(data); jQuery('#shownoti').html(data).hide().fadeIn(1500); } }); ```
Try using setInterval instead of setTimeout
8,801
48,819,547
I want take logarithm multiple times. We know this ``` import numpy as np np.log(x) ``` now the second logarithm would be ``` np.log(np.log(x)) ``` what if one wants to take n number of logs? surely it would not be pythonic to repeat n times as above.
2018/02/16
[ "https://Stackoverflow.com/questions/48819547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As per @eugenhu's suggestion, one way is to use a generic function which loops iteratively: ``` import numpy as np def repeater(f, n): def fn(i): result = i for _ in range(n): result = f(result) return result return fn repeater(np.log, 5)(x) ```
You could use the following little trick: ``` >>> from functools import reduce >>> >>> k = 4 >>> x = 1e12 >>> >>> y = np.array(x) >>> reduce(np.log, (k+1) * (y,))[()] 0.1820258315495139 ``` and back: ``` >>> reduce(np.exp, (k+1) * (y,))[()] 999999999999.9813 ``` On my machine this is slightly faster than @jp\_d...
8,802
994,460
I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako) ``` <tr> <td>Yardage</td> <td>${h.text('yardage[]', maxlength=3, size=3)}</td> <td>${h.text('yardage[]', maxlength=3, size=3)}</td> <td>${h.text('yardage[]', maxlength=3,...
2009/06/15
[ "https://Stackoverflow.com/questions/994460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10738/" ]
Turns out what I wanted to do wasn't quite right. **Template**: ``` <tr> <td>Yardage</td> % for hole in range(9): <td>${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}</td> % endfor </tr> ``` (Should have made it in a loop to begin with.) You'll notice that the name of the first element will become ...
``` c.form_result = schema.to_python(request.params) - (without dict) ``` It seems to works fine.
8,805
38,608,781
Python has filter method which filters the desired output on some criteria as like in the following example. ``` >>> s = "some\x00string. with\x15 funny characters" >>> import string >>> printable = set(string.printable) >>> filter(lambda x: x in printable, s) 'somestring. with funny characters' ``` The example is ...
2016/07/27
[ "https://Stackoverflow.com/questions/38608781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5453723/" ]
As others said it is undefined behaviour. Why it is working though? It is probably because the function call is linked statically, during compile-time (it's not virtual function). The function `B::hi()` exists so it is called. Try to add variable to `class B` and use it in function `hi()`. Then you will see problem (t...
> > Now, why is this happening ? > > > Because it can happen. Anything can happen. The behaviour is *undefined*. The fact that something unexpected happened demonstrates well why UB is so dangerous. If it always caused a crash, then it would be far easier to deal with. > > What object was used to call such a me...
8,806
42,875,890
I do install odoo version 8 in ubuntu version 16 , then I doing like this link <https://www.getopenerp.com/easy-odoo8-installation/> . In step 3 , it is wrong it say "E:Package 'python-pybabel' has no installation candidate". what happens?
2017/03/18
[ "https://Stackoverflow.com/questions/42875890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7626653/" ]
python-pybabel was replace by python-babel package from what I see on the web search. After I face also this problem I use python-babel and all work correctly. best regards, CiprianR
Hello this is a command for dependencies, you need to run it : ``` sudo apt-get install python-psutil python-pybabel ```
8,808
62,045,094
I'm trying to create an s3 bucket in every region in AWS with boto3 in python but I'm failing to create a bucket in 4 regions (af-south-1, eu-south-1, ap-east-1 & me-south-1) My python code: ``` def create_bucket(name, region): s3 = boto3.client('s3') s3.create_bucket(Bucket=name, CreateBucketConfiguration={'...
2020/05/27
[ "https://Stackoverflow.com/questions/62045094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4213730/" ]
The regions your code fails in are relativly new regions, where you need to opt-in first to use them, see here [Managing AWS Regions](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html)
Newer AWS regions only support regional endpoints. Thus, if creating buckets in one of those regions, a regional endpoint needs to be created. Since I was creating buckets in multiple regions, I set the endpoint by creating a new instance of the client for each region. (This was in Node.js, but should still work with ...
8,811
30,518,714
After running a python program, I obtain a list of numeric data. How can I format the data in CSV? Goal: I hope to format it so that I can reuse the CSV-formatted data in Mathematica.
2015/05/28
[ "https://Stackoverflow.com/questions/30518714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4143312/" ]
Let's assume your list of numeric data is stored in a variable - `numericList` ``` import csv myFile = open(csvFile, 'wb') writer = csv.writer(myFile, quoting = csv.QUOTE_ALL) writer.writerow(numericList) ``` *wb* indicates that the file is opened for **w**riting in **b**inary mode. The `csvFile` should contain you...
for a simple case you can just as easily write it directly.. ``` f=open('test.csv','w') for p in data : f.write('%g,%g\n'%tuple(p)) f.close() ``` where data here is an `nx2` array.
8,812
52,161,349
I have successfully install pattern3 for python 3.6 in my Linux system. But after writing this code I got an error. ``` from pattern3.en import referenced print(referenced('university')) print(referenced('hour')) ``` > > IndentationError::expected an indented block > > >
2018/09/04
[ "https://Stackoverflow.com/questions/52161349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6051513/" ]
I solved this by entering to the problematic file, which should be `(C:\Python27\Lib\site-packages\pattern3\text\tree.py)` and fixing the problem myself: ```py from itertools import chain # 34 try: # 35 None # ===> THIS IS THE LINE I ADDED! <=== except: ...
Python will give you an error `expected an indented block` if you skip the indentation: Example of this: ``` if 5 > 2: print("Five is greater than two!") ``` run it,and it will give an error ``` if 5 > 2: print("Five is greater than two!") ``` run it,it will not give any error.
8,813
25,538,584
I have 2 date columns (begin and end) in a data frame where the dates are in the following string format '%Y-%m-%d %H:%M:%S.%f'. How can I change these into date format in python? I also want to create a new column that shows the difference in days between the end and begin dates. Thanks in advance!
2014/08/27
[ "https://Stackoverflow.com/questions/25538584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313307/" ]
If you're using a recent version of pandas you can pass a format argument to `to_datetime`: ``` In [11]: dates = ["2014-08-27 19:53:06.000", "2014-08-27 19:53:15.002"] In [12]: pd.to_datetime(dates, format='%Y-%m-%d %H:%M:%S.%f') Out[12]: <class 'pandas.tseries.index.DatetimeIndex'> [2014-08-27 19:53:06, 2014-08-27 1...
The `datetime` module has everything you need to play around with dates. Note that in the format you describe `%Y-%m-%d %H:%M:%S.%f` the `%f` does not appear in the [known directives](https://docs.python.org/3/library/time.html#time.strftime) and is not included in my answer ``` from datetime import datetime dates = [...
8,814
19,845,259
I am getting below errors while configuring Grinder on JIRA instances, followed all instruction as per <https://confluence.atlassian.com/display/ATLAS/JIRA+Performance+Testing+with+Grinder#JIRAPerformanceTestingwithGrinder-Prerequisites> Errors : $ cat project\_manager\_8/error\_xxxx004.fm.XXXXX.com-0.log ``` 11/7/1...
2013/11/07
[ "https://Stackoverflow.com/questions/19845259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608551/" ]
It's taken me 2 weeks to find out how to REALLY fix this issue. I had put a new class file under the **App\_Code** folder (I haven't used that folder for ages). For some reason I had set the "Build Action" to "*Compile*". Well, I guess anything under the **App\_Code** folder is already compiled by default, so when the ...
It appears that something was wrong with either one of the web.config's. Simply took the web.config's from a blank MVC4 project and replaced. Incidentally, having the namespace in both the config and layout does not throw an error.
8,815
48,189,688
Im trying to find if a .xlsx file contains a @. I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns? the code: ``` df = pandas.read_excel(open(path,'rb'), sheetname=0) out = 'False' for col in df.co...
2018/01/10
[ "https://Stackoverflow.com/questions/48189688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495850/" ]
Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section. ``` import json import requests response = requests.get() # api call users = json.loads(response.text) for user in users: print(user['id']) ```
It seems what you are looking for is the [json](https://docs.python.org/2/library/json.html) module. with it you can use this to parse a string into json format: ``` import json output=json.loads(myJsonString) ```
8,816
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You can use `collections.dequeue`, which has a `rotate` method. However, if you want to make it on your own you can do it like this: ``` >>> a = ['a','b','c','d'] >>> counter = 0 >>> start_index=2 >>> while counter < len(a): ... print(a[start_index]) ... start_index+=1 ... counter += 1 ... if start_ind...
Use the following function: ``` def cycle_list(l, i): for element in l[i:]: yield element for element in l[:i]: yield element ```
8,821
13,610,654
I understand [from this question](https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): ...
2012/11/28
[ "https://Stackoverflow.com/questions/13610654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
[Indeed, see the comments, it is not true] If you are running CPython you can see from the set source code that it doesn't release the GIL (http://hg.python.org/cpython/file/db20367b20de/Objects/setobject.c) so all its operations should be atomic. If it is all what you need and you are sure to run your code on CPytho...
You can implement your own context manager: ``` class LockableSet: def __enter__(self): self.lock() return self def __exit__(self, exc_type, exc_value, traceback): #Do what you want with the error self.unlock() with LockableSet() as s: s.whatever() raise Exception() `...
8,831
11,965,655
I have created a utility software for operating file copy process in python.Every thing is working nice but when i start copying any files larger than 2 Gb the the whole system hangs. It seems to me that it might be a memory leak issue. I have tried: * Copying it using Shutil Module * Using Lazy operation by copying ...
2012/08/15
[ "https://Stackoverflow.com/questions/11965655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599825/" ]
Since you only have 2 GB of memory when you copy a file that's larger than your memory, it causes issues. Don't load the entire file into memory. Instead, I would do something like: ``` with open(myLargeFile) as f: with open(myOtherLargeFile, "w") as fo: for line in f: fo.write(line) ``` Sinc...
The good approach for this problem is: * use multiprocessing or multithreading * split file into chunks * use python dbm for storing which chunk belongs to which filename, filepath and chunk offset( for file.seek function) * create queue for read and write chunks
8,836
48,441,737
I have a raspberry pi and I have installed dockers in it. I have made a python script to read gpio status in it. So when I run the below command ``` sudo docker run -it --device /dev/gpiomem app-image ``` It runs perfectly and shows the gpio status. Now I have created a `docker-compose.yml` file as I want to deploy ...
2018/01/25
[ "https://Stackoverflow.com/questions/48441737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9267000/" ]
Adding devices, capabilities, and using privileged mode are not supported in swarm mode. Those options in the yml file exist for using `docker-compose` instead of `docker stack deploy`. You can track the progress on getting these features added to swarm mode in [github issue #24862](https://github.com/moby/moby/issues/...
As stated in [docker-compose devices](https://docs.docker.com/compose/compose-file/#devices) > > Note: This option is ignored when deploying a stack in swarm mode with > a (version 3) Compose file. > > > The devices option is ignored in swarm. You can use `privileged: true` which will give access to all devices.
8,837
19,331,093
I am trying to create a legend for a plot with variable sets of data. There are at least 2, and at most 5. The first two will always be there, but the other three are optional, so how can I create a legend for only the existing number of data sets? I've tried if-statements to tell python what to do if that variable do...
2013/10/12
[ "https://Stackoverflow.com/questions/19331093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873277/" ]
Because selectedFiles is a tuple, and the logic of processing each item inside it is same. you can iterate it with a for loop. ``` lines = [os.path.basename(str(os.path.splitext(filename)[0])) for filename in selectedFiles] #extend lines' length to 5 and fill the space with None lines = lines + [None] * (5-len(lines)...
I have no idea what your data structures look like, but it looks like you just want ``` lines = (os.path.basename(str(os.path.splitext(x)[0])) for x in selectedFiles) legend(lines, loc='upper left') ```
8,838
56,106,783
I am building a dockerfile with the `docker build .` command. While building, I am experiencing the following error: ``` Downloading/unpacking requests Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement requests No distributions at all found fo...
2019/05/13
[ "https://Stackoverflow.com/questions/56106783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439964/" ]
You have a pip problem, not a docker problem, you need to add `pip install --index-url https://pypi.python.org/simple/ --upgrade pip` to your docker file: ``` FROM jonasbonno/rpi-grovepi RUN pip install --index-url https://pypi.python.org/simple/ --upgrade pip RUN hash -r RUN pip install requests RUN git clone https:/...
#### Legacy problem In Python 2.7, a pip installer of *Pylons* threw the same error. I then read somewhere that upgrading *pip* could help, and doing so in the bash of the container, you get the same error again, now for *pip* itself: ```bash Cannot fetch index base URL https://pypi.python.org/simple/ Could not find ...
8,841
19,312,270
Is there any way to break string based on punctuation-word ``` #!/usr/bin/python #Asking user to Enter a line in specified format myString=raw_input('Enter your String:\nFor Example:I am doctor break I stays in CA break you can contact me on +000000\n') # 'break' is punctuation word <my code which breaks the user ...
2013/10/11
[ "https://Stackoverflow.com/questions/19312270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699472/" ]
If you have written you `java-script` code then make sure that you `return false` from the js code if it is not valid and in aspx file you need to use return as follows ``` <asp:Button runat="server" id="btnLogin" Text="Login" OnClientClick="return Validate()"/> ``` Edit -1 ------- There is a chance that your...
You need add a add an attribute to button(btnLogin) `OnClientClick="Validate()"`. Like: ``` <asp:Button runat="server" id="btnLogin" Text="Login" OnClientClick="Validate()"/> ``` Define javascript function `Validate()` and return false if your form value is not valid.
8,842
52,175,927
I am coming from a C# background and Python's Asyncio library is confusing me. I have read the following [1](https://stackoverflow.com/questions/37278647/fire-and-forget-python-async-await/37345564#37345564) [2](https://stackoverflow.com/questions/33357233/when-to-use-and-when-not-to-use-python-3-5-await/33399896#3339...
2018/09/05
[ "https://Stackoverflow.com/questions/52175927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8714371/" ]
As the **requests** library is not asynchronous, you can use [run\_in\_executor](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor) method, so it won't block the running thread. As the result, you can define `requestPage` as a regular function and call it in the `main` function like ...
Ok, I think I found a basic solution. ``` async def requestPage(url): request = requests.get(url, headers=headers) soup = BeautifulSoup(request.content, 'html.parser') return soup async def getValueAsync(func, param): # Create new task task = asyncio.ensure_future(func(param)) # Execute task. ...
8,846
57,417,108
I have to parse the following file in python: ``` 20100322;232400;1.355800;1.355900;1.355800;1.355900;0 20100322;232500;1.355800;1.355900;1.355800;1.355900;0 20100322;232600;1.355800;1.355800;1.355800;1.355800;0 ``` I need to end upwith the following variables (first line is parsed as example): ``` year = 2010 mont...
2019/08/08
[ "https://Stackoverflow.com/questions/57417108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5328289/" ]
``` from decimal import Decimal from datetime import datetime line = "20100322;232400;1.355800;1.355900;1.355800;1.355900;0" tokens = line.split(";") dt = datetime.strptime(tokens[0] + tokens[1], "%Y%m%d%H%M%S") decimals = [Decimal(string) for string in tokens[2:6]] # datetime objects also have some useful attribut...
You could use regex: ``` import re to_parse = """ 20100322;232400;1.355800;1.355900;1.355800;1.355900;0 20100322;232500;1.355800;1.355900;1.355800;1.355900;0 20100322;232600;1.355800;1.355800;1.355800;1.355800;0 """ stx = re.compile( r'(?P<date>(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2}));' r'(?P<time>(?P<...
8,847
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I suggest using the 'pip' command on the command line. ``` pip search sqlite pip install pysqlite ```
<https://pip.pypa.io/en/latest/installing.html> python get-pip.py python [complete path] python c:\folder\get-pip.py
8,848
33,978,739
First post to the forum here. I searched for an answer, but wasnt exactly sure how to phrase the search. I am currently working through "learn python the hard way" and one of the drills he uses this coding: ``` target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.wri...
2015/11/29
[ "https://Stackoverflow.com/questions/33978739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5616687/" ]
Using a comma sends each object as a separate argument. Concatenate them with `+` instead, or `join()` them: ``` target.write(line1 + "\n" + line2 + "\n" + line3) ``` Or: ``` target.write('\n'.join((line1, line2, line3))) ```
You can use Python's `str` `format`: ``` target.write('{}\n{}\n{}'.format(line1, line2, line3)) ```
8,855
33,580,308
Hello I am new to python, I was trying to find the distance from different points. Example: The distance between each door is about 2.5 feet. So the distance between door 1 and door 2 is 2.5 feet. How would i go about looking for two different distanced in the door dictionary. or should i use something else. ``` d =...
2015/11/07
[ "https://Stackoverflow.com/questions/33580308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5533124/" ]
try this ``` final ListPopupWindow listPopupWindow = new ListPopupWindow( context); listPopupWindow.setAdapter(new ArrayAdapter( context, R.layout.list_row_layout, arrayOfValues)); listPopupWindow.setAnchorView(your_view); ...
Exmaple : ``` findViewById(R.id.btn).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //use MotionEvent event : getX() and getY() will return your pressing location in the button. } }); ```
8,856
72,363,146
I am working on a project where I have to send arguments by a command line to a python file (using system exec) and then visualize the results saved in a folder after the python file finishes executing. I need to have this by only clicking on one button, so my question is, if there is any way to realize this scenario o...
2022/05/24
[ "https://Stackoverflow.com/questions/72363146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18449615/" ]
The way you phrased your question makes me think that you want to wait until the command you call via system exec finished and then run some code. You could simply use a sequence structure for this. However, if you need to do this *asynchronously*, i.e. launch the command and get an event when the command finished so ...
Use "wait until completion?" input of System Exec function to make sure the script finished execution, then proceed with the results visualization part.
8,857
69,856,536
**Goal:** Using python, I want to create a service account in a project on the Google Cloud Platform and grant that service account one role. **Problem:** The docs explain [here](https://cloud.google.com/iam/docs/granting-changing-revoking-access#grant-single-role) how to grant a single role to the service acc...
2021/11/05
[ "https://Stackoverflow.com/questions/69856536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13439686/" ]
Creating a service account, creating a service account key, downloading a service account JSON key file, and granting a role are separate steps. There is no single API to create a service account and grant a role at the same time. Anytime you update a project's IAM bindings is a risk. Google prevents multiple applicat...
As mentioned in John’s answer, you should be very careful when manipulating the IAM module, if something goes wrong it could end in services completely inoperable. Here is a Google’s document which [manipulates the IAM resources using the REST API](https://cloud.google.com/resource-manager/reference/rest/v1/projects/se...
8,858
63,695,246
Is there a fast possibility to reverse a binary number in python? Example: I have the number 11 in binary 0000000000001011 with 16 Bits. Now I'm searching for a **fast** function f, which returns 1101000000000000 (decimal 53248). Lookup tables are no solutions since i want it to scale to 32Bit numbers. Thank you for y...
2020/09/01
[ "https://Stackoverflow.com/questions/63695246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8080648/" ]
This might be faster using small 8-bit lookup table: ``` num = 11 # One time creation of 8bit lookup rev = [int(format(b, '08b')[::-1], base=2) for b in range(256)] # Run for each number to be flipped. lower_rev = rev[num & 0xFF] << 8 upper_rev = rev[(num & 0xFF00) >> 8] flipped = lower_rev + upper_rev ```
My current approach is to access the bits via bit shifting and mask and to shift them in the mirror number until they reach their destination. Still I have the feeling that there is room for improvement. ``` num = 11 print(format(num, '016b')) right = num left = 0 for i in range(16): tmp = right & 1 left = (left ...
8,859
52,553,757
I am a newcomer to python. I want to implement a "For" loop on the elements of a dataframe, with an embedded "if" statement. Code: ``` import numpy as np import pandas as pd #Dataframes x = pd.DataFrame([1,-2,3]) y = pd.DataFrame() for i in x.iterrows(): for j in x.iteritems(): if x>0: y = x...
2018/09/28
[ "https://Stackoverflow.com/questions/52553757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1978243/" ]
In pandas is best avoid loops if exist vectorized solution: ``` x = pd.DataFrame([1,-2,3], columns=['a']) y = pd.DataFrame(np.where(x['a'] > 0, x['a'] * 2, 0), columns=['b']) print (y) b 0 2 1 0 2 6 ``` **Explanation**: First compare column by value for boolean mask: ``` print (x['a'] > 0) 0 True 1 F...
You can try this: ``` y = (x[(x > 0)]*2).fillna(0) ```
8,862
20,629,561
#### With many started postgresql services, psql chooses the lowest postgresql version I have installed two versions of postgresql, `12` and `13` (in an earlier version of this question, these were `9.1` and `9.2`, I change this to be in line with the added output details from the higher versions). ``` sudo service p...
2013/12/17
[ "https://Stackoverflow.com/questions/20629561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813589/" ]
This situation with two clusters in Ubuntu may happen when upgrading to a newer release providing an newer postgresql version. The automatic upgrade does not remove the old cluster, presumably for fear of erasing valuable data (which is wise because some postgres upgrades may require human work to be complete). If yo...
`psql` fails because none of your postgres is running. First, you should understand **why** there are 2 different servers, then delete one of them (through `apt-get`, I think), and if necessary reconfigure the other (if you type `sudo service portgresql start`, both of the servers will start, and to connect to 9.2 y...
8,863
47,684,408
new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the re...
2017/12/06
[ "https://Stackoverflow.com/questions/47684408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5540416/" ]
There are a few things you need to take into consideration. **Centralising this element** To address your issue of centralising this element with a couple of methods: **Option 1.** You can make the entire `span` width 100% and center the text within it by adding this to `#header-content`: ``` width: 100%; display:...
First you need to make the image `max-width:100%` to avoid overflow, then simply adjust left/right/bottom values since your element is absolute position and add `text-align:center` : ```css .elixir { position: absolute; top: 5px; left: 15px; color: white; font-weight: bold; font-size: 50px; } .lev...
8,864
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
I think the solutions using split are good. I tried to solve it without `split` and here's what I came up with. ``` sOdd = "The cat jumped over the moon very quickly." sEven = "The cat jumped over the moon very quickly now." def split_on_delim_mid(s, delim=" "): delim_indexes = [ x[0] for x in enumerate(s) if...
Solutions with `split()` and `join()` are fine if you want to get half the words, not half the string (counting the characters and not the words). I think the latter is impossibile without a `for` loop or a list comprehension (or an expensive workaround such a recursion to find the indexes of the spaces maybe). But if...
8,867
4,184,841
I need to color the white part surrounded by black edges! ``` from PIL import Image import sys image=Image.open("G:/ghgh.bmp") data=image.load() image_width,image_height=image.size sys.setrecursionlimit(10115) def f(x,y): if(x<image_width and y<image_height and x>0 and y>0): if (data[x,y]==255): ...
2010/11/15
[ "https://Stackoverflow.com/questions/4184841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508292/" ]
Some warnings provide a description, others may not. Maybe the documentation is just incomplete or the authors figure some warnings don't need additional clarification?
If stylecop check is been run during a build (MSBuild/VS build) the show help option wont appear, however if you right click on the solution and run stylecop check, it will have the show help option. Hope that helps
8,877
29,775,006
I've been writing automated tests with Selenium Webdriver 2.45 in python. To get through some of the things I need to test I must retrieve the various `JSESSION` cookies that are generate from the site. When I use webdrivers `get_cookies()` function with Firefox or Chrome all of the needed cookies return to me. When I ...
2015/04/21
[ "https://Stackoverflow.com/questions/29775006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3249517/" ]
What you describe sounds like an issue I ran into a few months ago. My tests ran fine with Chrome and Firefox but not in IE, and the problem was cookies. Upon investigation what I found is that my web site had set its session cookies to be [HTTP-only](https://en.wikipedia.org/wiki/HTTP_cookie#Secure_and_HttpOnly). When...
There is an open issue with IE and Safari. Those driver will not return correct cookies information. At least not the domain. See [this](https://code.google.com/p/selenium/issues/detail?id=8509)
8,878
60,992,133
I am trying to get my PTZ camera to stream using python 3 and openCV. The URL i use in the code works with VLC stream but not with the code. ``` import cv2 import numpy as np cap = cv2.VideoCapture(src="rtsp://USER:[email protected]:XXX/Streaming/Channels/101/") FRAME_WIDTH = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) ...
2020/04/02
[ "https://Stackoverflow.com/questions/60992133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13198103/" ]
one small change, remove **src=** from the cv2.VideoCapture() method. It should look like, ``` cap = cv2.VideoCapture("rtsp://USER:[email protected]:XXX/Streaming/Channels/101/") ```
This is working for me in Hikvision camera. Avoid using special letter in the password. ``` import cv2 cap = cv2.VideoCapture('rtsp://username:[email protected]:554') while True: ret, img = cap.read() cv2.imshow('video output', img) k = cv2.waitKey(10)& 0xff if k == 27: break cap.release()...
8,879
67,740,665
The Script, running on a Linux host, should call some Windows hosts holding Oracle Databases. Each Oracle Database is in DNS with its name "db-[ORACLE\_SID]". Lets say you have a database with ORACLE SID `TEST02`, it can be resolved as `db-TEST02`. The complete script is doing some more stuff, but this example is suffi...
2021/05/28
[ "https://Stackoverflow.com/questions/67740665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15623827/" ]
The first thing that comes to mind for me would be to use the append feature on Python file handlers. You could do something like this for each line of text: ```py def writecond(text, cond): fname = cond + '.txt' with open(fname, 'a') as file: file.write(text) ``` Another thing you could do is have a...
I figured out one option of handling objects dynamically and keeping track of it. ``` file_handler = {} with open(file) as f: for line in f: if line.split()[1] not in file_handler.keys(): file_handler[line.split()[1]] = open(line.split()[1],"w") file_handler[line.split()[1]].write(...
8,880
74,195,370
Hello so im new on python, i want to know how to do multiple string input on list. I already try to append the input to the list, but it doesn't give me expected output. Here is the source code: ``` test=[] input1=input("Enter multiple strings: ") splitinput1=input1.split() for x in range(len(splitinput1)): test.a...
2022/10/25
[ "https://Stackoverflow.com/questions/74195370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19363291/" ]
> > reducing vertex data down to 32bits per vertex is as far as the GPU will allow > > > You seem to think that vertex buffer sizes are what's holding you back. Make no mistake here, they are not. You have many gigs of VRAM to work with, use them if it will make your code faster. Specifically, anything you're unpa...
I think your code is CPU bound. While your approach has very small vertices, you have non-trivial API overhead. A better approach is rendering all quads with a single draw call. I would probably use instancing for that. Assuming you want arbitrary per-quad size, position, and orientation in 3D space, here’s one possi...
8,881
48,702,330
Code: ``` a={'day': [{'average_price': 9.3, 'buy_m2m': 9.3, 'buy_price': 9.3, 'buy_quantity': 1, 'buy_value': 9.3, 'close_price': 0, 'exchange': 'NSE', 'instrument_token': 2867969, 'last_price': 9.3, 'm2m': 0.0, 'multiplier': 1, 'net_buy_amount_m2m': 9.3, 'net_sell_amount_m2m': 0, ...
2018/02/09
[ "https://Stackoverflow.com/questions/48702330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9337404/" ]
`Footer` is not inside a section element, so your selector won't work. ```css .mypage :not(footer) p{ color:red } ``` ```html <body class="mypage"> <section> <p>Hello world</p> </section> <footer> <p>footer content</p> </footer> </body> ```
Why not target the footer again ? ``` .mypage section p{color: red} .mypage footer p{color: blue} <body class="mypage"> <section> <p>Hello world</p> </section> <footer> <p>footer content</p> </footer> </body> ```
8,882
37,297,276
I have a data frame ``` df=data.frame(f=c('a','ab','abc'),v=1:3) ``` and make a new column with: ``` df$c=paste(df$v,df$f,sep='') ``` the result is ``` > df f v c 1 a 1 1a 2 ab 2 2ab 3 abc 3 3abc ``` I would like column c to be in this format: ``` > df f v c 1 a 1 1 a 2 ab 2 2 ab 3 abc...
2016/05/18
[ "https://Stackoverflow.com/questions/37297276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2123706/" ]
You can use the `format()` function to pretty print the values of your column. For example: ``` > format(df$f, width = 3, justify = "right") [1] " a" " ab" "abc" ``` So your code should be: ``` df <- within(df, { c <- paste0(v, format(f, width = 3, justify = "right")) }) df ``` The result: ``` > df f v ...
You can use the `formatC`function as follow ``` df$c <- paste(df$v, formatC(as.character(df$f), width = 3, flag = " "), sep = "") df f v c 1 a 1 1 a 2 ab 2 2 ab 3 abc 3 3abc ``` **DATA** ``` df <- data.frame(f = c('a','ab','abc'), v=1:3) ```
8,883
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
**Updated Answer** For ASP Core 1.1.0 generic model binding is now done using `Get`: ``` var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>(); ``` --- **Original Answer** How about this: ``` var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>(...
You don't read the configuration manually generally in ASP.NET Core yourself, instead you create an object that matches your definition. You can read more on that in the official documentation [here](https://docs.asp.net/en/latest/fundamentals/configuration.html). E.g. ``` public class MyOptions { public string O...
8,884
70,736,110
I have a pandas dataframe like this: ``` df = pd.DataFrame([ {'A': 'aaa', 'B': 0.01, 'C': 0.00001, 'D': 0.00999999999476131, 'E': 0.00023191546403037534}, {'A': 'bbb', 'B': 0.01, 'C': 0.0001, 'D': 0.010000000000218279, 'E': 0.002981781316158273}, {'A': 'ccc', 'B': 0.1, 'C': 0...
2022/01/17
[ "https://Stackoverflow.com/questions/70736110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14382768/" ]
You can use a `-log10` operation to obtain the number of decimals before a digit (credit goes to @Willem van Onsem's answer [here](https://stackoverflow.com/questions/57663565/pandas-column-with-count-of-decimal-places)). Then you can incorporate this into a lambda function that you `apply` rowwise: ``` import numpy ...
I use part of the solution above of Derek and make my solution: ``` df['b_decimals'] = -np.floor(np.log10(df['B'])) df['c_decimals'] = -np.floor(np.log10(df['C'])) df['D'] = [np.around(x, y) for x, y in zip(df['D'], df['b_decimals'].astype(int))] df['E'] = [np.around(x, y) for x, y in zip(df['E'], df['c_decimals'].as...
8,890