qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
19,512,457
What can i do to optimize this function, and make it looks like more pythonic? ``` def flatten_rows_to_file(filename, rows): f = open(filename, 'a+') temp_ls = list() for i, row in enumerate(rows): temp_ls.append("%(id)s\t%(price)s\t%(site_id)s\t%(rating)s\t%(shop_id)s\n" % row) if i and i ...
2013/10/22
[ "https://Stackoverflow.com/questions/19512457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2000477/" ]
A few things that come to mind immediately: 1. Use a `with` statement, rather than manually closing your file. 2. Pass a generator expression to `f.writelines` rather than building up a 100000 row list over and over (let the standard library handle how much, if any, it buffers the output). 3. Or, better yet, use the `...
It is generally a good idea to use the `with` statement to make sure the file is closed properly. Also, unless I'm mistaken there should be no need to manually buffer the lines. You can just as well specify a buffer size when opening the file, determining [how often the file is flushed](https://stackoverflow.com/q/3167...
36,380,144
i'm new at here and im new at coding something at node.js. My question is how to use the brackets i mean, i'm working on a steam trade bot and i need to get understand how to use options and callbacks. Let me give you a example, [![enter image description here](https://i.stack.imgur.com/VMV5q.png)](https://i.stack.img...
2016/04/03
[ "https://Stackoverflow.com/questions/36380144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The brackets are documentation notation indicating that those parameters are optional, and can be omitted from any given invocation. They are not indicative of syntax you should be using in your program. Both of these styles should work, given that documentation. The callback being optional. ``` makeOffer({ ... }); ...
~~`makeOffer(accessToken[, itemsFromThem])` is not JavaScript syntax. It's just common notation that's used to indicate that the function can take any number of arguments, like so:~~ ``` makeOffer(accessToken, something, somethingElse); makeOffer(accessToken, something, secondThing, thirdThing); makeOffer(accessToken)...
36,380,144
i'm new at here and im new at coding something at node.js. My question is how to use the brackets i mean, i'm working on a steam trade bot and i need to get understand how to use options and callbacks. Let me give you a example, [![enter image description here](https://i.stack.imgur.com/VMV5q.png)](https://i.stack.img...
2016/04/03
[ "https://Stackoverflow.com/questions/36380144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The brackets are documentation notation indicating that those parameters are optional, and can be omitted from any given invocation. They are not indicative of syntax you should be using in your program. Both of these styles should work, given that documentation. The callback being optional. ``` makeOffer({ ... }); ...
I don't have full code of what You've done. But I'll give necessary part of it. Look here: ``` var SteamTradeOffers = require('steam-tradeoffers'); var offers = new SteamTradeOffers(); // look at api, it needs 2 arguments // 1. offer object, that consist of params like this: var offer = { partnerAccountId: 'stea...
36,380,144
i'm new at here and im new at coding something at node.js. My question is how to use the brackets i mean, i'm working on a steam trade bot and i need to get understand how to use options and callbacks. Let me give you a example, [![enter image description here](https://i.stack.imgur.com/VMV5q.png)](https://i.stack.img...
2016/04/03
[ "https://Stackoverflow.com/questions/36380144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
~~`makeOffer(accessToken[, itemsFromThem])` is not JavaScript syntax. It's just common notation that's used to indicate that the function can take any number of arguments, like so:~~ ``` makeOffer(accessToken, something, somethingElse); makeOffer(accessToken, something, secondThing, thirdThing); makeOffer(accessToken)...
I don't have full code of what You've done. But I'll give necessary part of it. Look here: ``` var SteamTradeOffers = require('steam-tradeoffers'); var offers = new SteamTradeOffers(); // look at api, it needs 2 arguments // 1. offer object, that consist of params like this: var offer = { partnerAccountId: 'stea...
62,919,733
I have an ascii file containing 2 columns as following; ``` id value 1 15.1 1 12.1 1 13.5 2 12.4 2 12.5 3 10.1 3 10.2 3 10.5 4 15.1 4 11.2 4 11.5 4 11.7 5 12.5 5 12.2 ``` I want to estimate the average value of column "value" for each id (i.e. group by id) Is it possible to do that in python using nu...
2020/07/15
[ "https://Stackoverflow.com/questions/62919733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5834711/" ]
If you don't know how to read the file, there are several methods as you can see [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html) that you could use, so you can try one of them, e.g. `pd.read_csv()`. Once you have read the file, you could try this using pandas functions as `pd.DataFrame.groupby`...
``` import pandas as pd filename = "data.txt" df = pd.read_fwf(filename) df.groupby(['id']).mean() ``` Output ``` value id 1 13.566667 2 12.450000 3 10.266667 4 12.375000 5 12.350000 ```
15,316,886
I'm new to python and would like to take this ``` K=[['d','o','o','r'], ['s','t','o','p']] ``` to print: ``` door, stop ```
2013/03/09
[ "https://Stackoverflow.com/questions/15316886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2152618/" ]
How about: `', '.join(''.join(x) for x in K)`
Using `str.join()` and `map()`: ``` In [26]: K=[['d','o','o','r'], ['s','t','o','p']] In [27]: ", ".join(map("".join,K)) Out[27]: 'door, stop' ``` > > S.join(iterable) -> string > > > Return a string which is the concatenation of the strings in the > iterable. The separator between elements is S. > > >
30,331,919
Can someone explain why the following occurs? My use case is that I have a python list whose elements are all numpy ndarray objects and I need to search through the list to find the index of a particular ndarray obj. Simplest Example: ``` >>> import numpy as np >>> a,b = np.arange(0,5), np.arange(1,6) >>> a array([0,...
2015/05/19
[ "https://Stackoverflow.com/questions/30331919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2383529/" ]
Applying the idea in <https://stackoverflow.com/a/17703076/901925> (see the Related sidebare) ``` [np.array_equal(b,x) for x in l].index(True) ``` should be more reliable. It ensures a correct array to array comparison. Or `[id(b)==id(x) for x in l].index(True)` if you want to ensure it compares ids.
The idea is to convert numpy arrays to lists and transform the problem to finding a list in an other list: ```py def find_array(list_of_numpy_array,taregt_numpy_array): out = [x.tolist() for x in list_of_numpy_array].index(taregt_numpy_array.tolist()) return out ```
53,723,025
I have anaconda installed, and I use Anaconda Prompt to install python packages. But I'm unable to install RASA-NLU using conda prompt. Please let me know the command for the same I have used the below command: ``` conda install rasa_nlu ``` Error: ``` PackagesNotFoundError: The following packages are not availab...
2018/12/11
[ "https://Stackoverflow.com/questions/53723025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7905329/" ]
Turns out the framework search path (under Project->Target->Build Settings) was indeed the culprit. Removing my custom overrides solved the issue. Interestingly, if I remember correctly, I had added them, because Xcode wasn't able to find my frameworks... See also <https://forums.developer.apple.com/message/328635#328...
Set "Always Search User Paths" to NO and problem will be solved
68,299,665
I am new to using webdataset library from pytorch. I have created .tar files of a sample dataset present locally in my system using webdataset.TarWriter(). The .tar files creation seems to be successful as I could extract them separately on windows platform and verify the same dataset files. Now, I create `train_datas...
2021/07/08
[ "https://Stackoverflow.com/questions/68299665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2562870/" ]
I have had the same error since yesterday, I finally found the culprit. [WebDataset/tarIterators.py](https://github.com/webdataset/webdataset/blob/master/webdataset/tariterators.py) makes use of [WebDataset/gopen.py](https://github.com/webdataset/webdataset/blob/master/webdataset/gopen.py). In gopen.py `urllib.parse.ur...
Add "file:" in the front of local file path, like this: ``` from itertools import islice import webdataset as wds import os import tqdm path = "file:D:/Dataset/00000.tar" dataset = wds.WebDataset(path) for sample in islice(dataset, 0, 3): for key, value in sample.items(): print(key, repr(value)[:50]) ...
66,178,922
I am trying to run Django tests on Gitlab CI but getting this error, Last week it was working perfectly but suddenly I am getting this error during test run > > django.db.utils.OperationalError: could not connect to server: Connection refused > Is the server running on host "database" (172.19.0.3) and accepting > TCP...
2021/02/12
[ "https://Stackoverflow.com/questions/66178922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15200334/" ]
Unsure if it would help in your case but I was getting the same issue with docker-compose. What solved it for me was explicitly specifying the hostname for postgres. ``` services: database: image: postgres:12-alpine hostname: database environment: - POSTGRES_DB=test - POSTGRES_USER=test ...
Could you do a `docker container ls` and check if the container name of the database is in fact, "database"? You've skipped setting the `container_name` for that container, and it may be so that docker isn't creating it with the default name of the service, i.e. "database", thus the DNS isn't able to find it under that...
66,178,922
I am trying to run Django tests on Gitlab CI but getting this error, Last week it was working perfectly but suddenly I am getting this error during test run > > django.db.utils.OperationalError: could not connect to server: Connection refused > Is the server running on host "database" (172.19.0.3) and accepting > TCP...
2021/02/12
[ "https://Stackoverflow.com/questions/66178922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15200334/" ]
Unsure if it would help in your case but I was getting the same issue with docker-compose. What solved it for me was explicitly specifying the hostname for postgres. ``` services: database: image: postgres:12-alpine hostname: database environment: - POSTGRES_DB=test - POSTGRES_USER=test ...
Reboot the server. I encounter similar errors on Mac and Linux from time to time when I run more than one container that use postgres.
44,130,318
env:linux + python3 + rornado When i run client.py,he suggested that my connection was rejected, for a few ports,Using the 127.0.0.1:7233,The server does not have any response, but the client prompts to refuse to connect,Who can tell me why? server.py ``` # coding:utf8 import socket import time import threading # ...
2017/05/23
[ "https://Stackoverflow.com/questions/44130318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5472490/" ]
Are the `featured_value_id` array values unique inside the array? If not does it make a difference if you give the planner a little hand by making them unique?: ``` select distinct c.id from dematerialized_products cross join lateral ( select distinct id from unnest(feature_value_ids) u (id...
You didn't show execution plans, but obviously the time is spent sorting the values to eliminate doubles. If `EXPLAIN (ANALYZE)` shows that the sort is performed using temporary files, you can improve the performance by raising `work_mem` so that the sort can be performed in memory. You will still experience a perfor...
74,428,888
`polars.LazyFrame.var` will return variance value for each column in a table as below: ``` >>> df = pl.DataFrame({"a": [1, 2, 3, 4], "b": [1, 2, 1, 1], "c": [1, 1, 1, 1]}).lazy() >>> df.collect() shape: (4, 3) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ a ┆ b ┆ c β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•ͺ═════β•ͺ═════║ β”‚ 1 ┆ 1...
2022/11/14
[ "https://Stackoverflow.com/questions/74428888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20497072/" ]
polars doesn't know what the variance is until after it is calculated but that's the same time that it is displaying the results so there's no way to filter the columns reported and also have it be more performant than just displaying all the columns, at least with respect to the polars calculation. It could be that py...
Building on the answer from @dean MacGregor, we: * do the var calculation * melt * apply the filter * extract the `variable` column with column names * pass it as a list to `select` ```py df.select( ( df.var().melt().filter(pl.col('value')>0).collect() ["variable"] ) .to_list() )....
16,748,592
I'm trying to build a simple Scapy script which manually manages 3-way-handshake, makes an HTTP GET request (by sending a single packet) to a web server and manually manages response packets (I need to manually send ACK packets for the response). Here is the beginning of the script: ``` #!/usr/bin/python import logg...
2013/05/25
[ "https://Stackoverflow.com/questions/16748592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194426/" ]
Use sr(), read the data in from every ans that is received (you'll need to parse, as you go, the Content-Length or the chunk lengths depending on whether you're using transfer chunking) then send ACKs in response to the *last* element in the ans list, then repeat until the end criteria is satisfied (don't forget to inc...
Did you try: ``` responce = sr1(request) print responce.show2 ``` Also try using a different sniffer like wireshark or tcpdump as netcat has a few bugs.
16,748,592
I'm trying to build a simple Scapy script which manually manages 3-way-handshake, makes an HTTP GET request (by sending a single packet) to a web server and manually manages response packets (I need to manually send ACK packets for the response). Here is the beginning of the script: ``` #!/usr/bin/python import logg...
2013/05/25
[ "https://Stackoverflow.com/questions/16748592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194426/" ]
TCP\_PUSH=TCP(sport=1500, dport=80, flags="PA", seq=102, ack=my\_ack) send(ip/TCP\_PUSH) seq should be 101 not 102
Did you try: ``` responce = sr1(request) print responce.show2 ``` Also try using a different sniffer like wireshark or tcpdump as netcat has a few bugs.
16,748,592
I'm trying to build a simple Scapy script which manually manages 3-way-handshake, makes an HTTP GET request (by sending a single packet) to a web server and manually manages response packets (I need to manually send ACK packets for the response). Here is the beginning of the script: ``` #!/usr/bin/python import logg...
2013/05/25
[ "https://Stackoverflow.com/questions/16748592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194426/" ]
Use sr(), read the data in from every ans that is received (you'll need to parse, as you go, the Content-Length or the chunk lengths depending on whether you're using transfer chunking) then send ACKs in response to the *last* element in the ans list, then repeat until the end criteria is satisfied (don't forget to inc...
TCP\_PUSH=TCP(sport=1500, dport=80, flags="PA", seq=102, ack=my\_ack) send(ip/TCP\_PUSH) seq should be 101 not 102
57,327,185
I'm using Telethon in python to automatic replies in Telegram's Group. I wanna reporting spam or abuse an account automatically via the Telethon and I read the Telethon document and google it, but I can't find any example. If this can be done, please provide an example with a sample code.
2019/08/02
[ "https://Stackoverflow.com/questions/57327185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5704891/" ]
`display: flex;` This CSS property will make all child inline element. ``` <div style="display:flex; flex-direction: row;"> <div>1</div> <div>2</div> </div ``` This is an example of inline child. for more info please Check this link [CSS Flexbox Layout](https://www.w3schools.com/css/css3_flexbox.asp)
Can you describe what do you mean by "when the "Add Dates" button is pressed I want another line be available." ? In any case, when trying to inline two objects, you should put style="display: inline" property onto very element you want to be displayed inline. Thus, try to add style="display: inline" property on eleme...
57,327,185
I'm using Telethon in python to automatic replies in Telegram's Group. I wanna reporting spam or abuse an account automatically via the Telethon and I read the Telethon document and google it, but I can't find any example. If this can be done, please provide an example with a sample code.
2019/08/02
[ "https://Stackoverflow.com/questions/57327185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5704891/" ]
the default layout should be fine for what you're asking. div by default is a block element, meaning, by default, its elements will be placed in a new line. your exact code + iterating the .dates div: [stackblitz demo](https://stackblitz.com/edit/angular-nqkr2f?file=app/sidenav-overview-example.html) [![image of def...
Can you describe what do you mean by "when the "Add Dates" button is pressed I want another line be available." ? In any case, when trying to inline two objects, you should put style="display: inline" property onto very element you want to be displayed inline. Thus, try to add style="display: inline" property on eleme...
57,327,185
I'm using Telethon in python to automatic replies in Telegram's Group. I wanna reporting spam or abuse an account automatically via the Telethon and I read the Telethon document and google it, but I can't find any example. If this can be done, please provide an example with a sample code.
2019/08/02
[ "https://Stackoverflow.com/questions/57327185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5704891/" ]
`display: flex;` This CSS property will make all child inline element. ``` <div style="display:flex; flex-direction: row;"> <div>1</div> <div>2</div> </div ``` This is an example of inline child. for more info please Check this link [CSS Flexbox Layout](https://www.w3schools.com/css/css3_flexbox.asp)
the default layout should be fine for what you're asking. div by default is a block element, meaning, by default, its elements will be placed in a new line. your exact code + iterating the .dates div: [stackblitz demo](https://stackblitz.com/edit/angular-nqkr2f?file=app/sidenav-overview-example.html) [![image of def...
66,510,970
I've tried relentlessly for about 1-2hrs to get this piece of code to work. I need to add the role to a user, simple enough right? This code, searches for the role but cannot find it, is this because I am sending it from a channel which that role doesn't have access to? I need help please. Edit 1: removed quotations ...
2021/03/06
[ "https://Stackoverflow.com/questions/66510970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15250234/" ]
Use `in_array` and looking for last character in array: ``` if (in_array(substr($var, -1, 1), ['s', 'z'])) ```
Or maybe: ``` in_array(array_pop(explode('', $var)), ['s', 'z'])` ? ``` not really much more readable neither gallant, but what do I know? :)
66,510,970
I've tried relentlessly for about 1-2hrs to get this piece of code to work. I need to add the role to a user, simple enough right? This code, searches for the role but cannot find it, is this because I am sending it from a channel which that role doesn't have access to? I need help please. Edit 1: removed quotations ...
2021/03/06
[ "https://Stackoverflow.com/questions/66510970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15250234/" ]
Use `in_array` and looking for last character in array: ``` if (in_array(substr($var, -1, 1), ['s', 'z'])) ```
Tired of code that's too easy to understand? Regular expressions to the rescue: ``` preg_match('/[sz]$/', $var) ```
66,510,970
I've tried relentlessly for about 1-2hrs to get this piece of code to work. I need to add the role to a user, simple enough right? This code, searches for the role but cannot find it, is this because I am sending it from a channel which that role doesn't have access to? I need help please. Edit 1: removed quotations ...
2021/03/06
[ "https://Stackoverflow.com/questions/66510970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15250234/" ]
Use `in_array` and looking for last character in array: ``` if (in_array(substr($var, -1, 1), ['s', 'z'])) ```
If you are able to use PHP8, then you should this simple solution available in PHP8. <https://www.php.net/manual/en/function.str-ends-with.php> ``` <?php $text = 'foods'; if (str_ends_with($text, 's') || str_ends_with($text, 'z')) { ... } ```
66,510,970
I've tried relentlessly for about 1-2hrs to get this piece of code to work. I need to add the role to a user, simple enough right? This code, searches for the role but cannot find it, is this because I am sending it from a channel which that role doesn't have access to? I need help please. Edit 1: removed quotations ...
2021/03/06
[ "https://Stackoverflow.com/questions/66510970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15250234/" ]
Or maybe: ``` in_array(array_pop(explode('', $var)), ['s', 'z'])` ? ``` not really much more readable neither gallant, but what do I know? :)
Tired of code that's too easy to understand? Regular expressions to the rescue: ``` preg_match('/[sz]$/', $var) ```
66,510,970
I've tried relentlessly for about 1-2hrs to get this piece of code to work. I need to add the role to a user, simple enough right? This code, searches for the role but cannot find it, is this because I am sending it from a channel which that role doesn't have access to? I need help please. Edit 1: removed quotations ...
2021/03/06
[ "https://Stackoverflow.com/questions/66510970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15250234/" ]
Or maybe: ``` in_array(array_pop(explode('', $var)), ['s', 'z'])` ? ``` not really much more readable neither gallant, but what do I know? :)
If you are able to use PHP8, then you should this simple solution available in PHP8. <https://www.php.net/manual/en/function.str-ends-with.php> ``` <?php $text = 'foods'; if (str_ends_with($text, 's') || str_ends_with($text, 'z')) { ... } ```
49,510,815
I am trying to create a class that returns the class name together with the attribute. This needs to work both with instance attributes and class attributes ``` class TestClass: obj1 = 'hi' ``` I.e. I want the following (note: both with and without class instantiation) ``` >>> TestClass.obj1 ('TestClass', 'hi')...
2018/03/27
[ "https://Stackoverflow.com/questions/49510815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9490769/" ]
I got help from a colleague for defining meta classes, and came up with the following solution ``` class MyMeta(type): def __new__(mcs, name, bases, dct): c = super(MyMeta, mcs).__new__(mcs, name, bases, dct) c._member_names = [] for key, value in c.__dict__.items(): if type(val...
Way 1 ----- You can use [`classmethod`](https://www.programiz.com/python-programming/methods/built-in/classmethod) decorator to define methods callable at the whole class: ``` class TestClass: _obj1 = 'hi' @classmethod def obj1(cls): return cls.__name__, cls._obj1 class TestSubClass(TestClass): ...
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
Using `re`: ``` import re tupl = ('zone1', 'pcomp110007') ", ".join(map(lambda x: " ".join(re.findall('([A-Z]+)([0-9])+',x.upper())[0]), tupl)) #'ZONE 1, PCOMP 7' ```
A recursive solution: ``` def non_regex_split(s,i=0): if len(s) == i: return s try: return '%s %d' %(s[:i], int(s[i:])) except: return non_regex_split(s,i+1) ', '.join(non_regex_split(s).upper() for s in tags) ```
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
My thoughts: Keep `sep` a normal function like it is in your original code for readability / maintenance, but also leverage `re` as suggested in Abdou's answer. ``` import re tags = ('zone1', 'pcomp110007') def sep(astr): alpha, num = re.match('([^\d]+)([\d]+)', astr).groups() return '{} {}'.format(alpha.upp...
Here is my stab: ``` >>> for i, s in enumerate(tags[1][::-1]): ... if s.isalpha(): ... print (tags[1][:i], tags[1][i:]) break ... pcomp1 10007 ``` I walk back thru the string to find first alpha, then split and print each side (alpha, numeric). I left out conversion to upper case which is easy to add
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
Regex does help. This should always work: ``` import re tags = ('zone1', 'pcomp110007') def sep(s): word = re.split(r'\d', s)[0] return word.upper() + " " + s[len(word):] print(', '.join(map(sep, tags))) ```
A recursive solution: ``` def non_regex_split(s,i=0): if len(s) == i: return s try: return '%s %d' %(s[:i], int(s[i:])) except: return non_regex_split(s,i+1) ', '.join(non_regex_split(s).upper() for s in tags) ```
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
Regex does help. This should always work: ``` import re tags = ('zone1', 'pcomp110007') def sep(s): word = re.split(r'\d', s)[0] return word.upper() + " " + s[len(word):] print(', '.join(map(sep, tags))) ```
Thank you all for the answers. I timed a couple here are the results and the timing script: ``` setup = ''' import re tags = ('zone1', 'pcomp110007') def sepListComp(astr): res = ''.join([x.upper() for x in astr if x.isalpha()]), ''.join([x for x in astr if x.isnumeric()]) return '{} {}'.format(*res) def sep...
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
I think your way is pythonic enough. If you want to make it "more functional style", then you can use this one: ``` sep = lambda s: " ".join((filter(str.isalpha, s).upper(), filter(str.isdigit, s))) print(', '.join(map(sep, tags))) ``` Updated: It's Python3 version, for Python2 you need to use `upper` for `s`, not f...
A recursive solution: ``` def non_regex_split(s,i=0): if len(s) == i: return s try: return '%s %d' %(s[:i], int(s[i:])) except: return non_regex_split(s,i+1) ', '.join(non_regex_split(s).upper() for s in tags) ```
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
Using `re`: ``` import re tupl = ('zone1', 'pcomp110007') ", ".join(map(lambda x: " ".join(re.findall('([A-Z]+)([0-9])+',x.upper())[0]), tupl)) #'ZONE 1, PCOMP 7' ```
Thank you all for the answers. I timed a couple here are the results and the timing script: ``` setup = ''' import re tags = ('zone1', 'pcomp110007') def sepListComp(astr): res = ''.join([x.upper() for x in astr if x.isalpha()]), ''.join([x for x in astr if x.isnumeric()]) return '{} {}'.format(*res) def sep...
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
My thoughts: Keep `sep` a normal function like it is in your original code for readability / maintenance, but also leverage `re` as suggested in Abdou's answer. ``` import re tags = ('zone1', 'pcomp110007') def sep(astr): alpha, num = re.match('([^\d]+)([\d]+)', astr).groups() return '{} {}'.format(alpha.upp...
I think your way is pythonic enough. If you want to make it "more functional style", then you can use this one: ``` sep = lambda s: " ".join((filter(str.isalpha, s).upper(), filter(str.isdigit, s))) print(', '.join(map(sep, tags))) ``` Updated: It's Python3 version, for Python2 you need to use `upper` for `s`, not f...
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
My thoughts: Keep `sep` a normal function like it is in your original code for readability / maintenance, but also leverage `re` as suggested in Abdou's answer. ``` import re tags = ('zone1', 'pcomp110007') def sep(astr): alpha, num = re.match('([^\d]+)([\d]+)', astr).groups() return '{} {}'.format(alpha.upp...
Using `re`: ``` import re tupl = ('zone1', 'pcomp110007') ", ".join(map(lambda x: " ".join(re.findall('([A-Z]+)([0-9])+',x.upper())[0]), tupl)) #'ZONE 1, PCOMP 7' ```
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
Regex does help. This should always work: ``` import re tags = ('zone1', 'pcomp110007') def sep(s): word = re.split(r'\d', s)[0] return word.upper() + " " + s[len(word):] print(', '.join(map(sep, tags))) ```
Here is my stab: ``` >>> for i, s in enumerate(tags[1][::-1]): ... if s.isalpha(): ... print (tags[1][:i], tags[1][i:]) break ... pcomp1 10007 ``` I walk back thru the string to find first alpha, then split and print each side (alpha, numeric). I left out conversion to upper case which is easy to add
40,615,604
I am looking for a nice, efficient and pythonic way to go from something like this: `('zone1', 'pcomp110007')` to this: `'ZONE 1, PCOMP 110007'` without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j...
2016/11/15
[ "https://Stackoverflow.com/questions/40615604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6162307/" ]
I think your way is pythonic enough. If you want to make it "more functional style", then you can use this one: ``` sep = lambda s: " ".join((filter(str.isalpha, s).upper(), filter(str.isdigit, s))) print(', '.join(map(sep, tags))) ``` Updated: It's Python3 version, for Python2 you need to use `upper` for `s`, not f...
Thank you all for the answers. I timed a couple here are the results and the timing script: ``` setup = ''' import re tags = ('zone1', 'pcomp110007') def sepListComp(astr): res = ''.join([x.upper() for x in astr if x.isalpha()]), ''.join([x for x in astr if x.isnumeric()]) return '{} {}'.format(*res) def sep...
23,407,824
I am building a website with django for months. So now i thought its time to test it with some friend. While deploying it to a Ubuntu 14.4 64bit LTS ( Same as development environment ) i found a strange error. Called ``` OSError at /accounts/edit/ [Errno 21] Is a directory: '/var/www/media/' ``` I also tried with ...
2014/05/01
[ "https://Stackoverflow.com/questions/23407824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2665252/" ]
Looks like `profile.avatar.name` evaluates to a **blank string** So No file is being provided to `os.remove` to remove and It **can't remove a directory** and **raises OSError** : See here: <https://docs.python.org/2/library/os.html#os.remove> You can rectify this error by **applying a conditional**, which is what to...
This just happened to me for another reason. Answering here in case it is not the situation above. I had a file named "admin" in my static folder, which matched the directory "admin" where Django's admin app stores its static files. When running `collectstatic` it would conflict between those two. I had to remove my ...
73,401,346
In the following code I am having a problem, the log file should get generated each day with timestamp in its name. Right now the first file has name as **dashboard\_asset\_logs** and then other subsequent log files come as **dashboard\_asset\_logs.2022\_08\_18.log, dashboard\_asset\_logs.2022\_08\_19.log**. How can t...
2022/08/18
[ "https://Stackoverflow.com/questions/73401346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8838167/" ]
In short, you will have to write your own `TimedRotatingFileHandler` implementation to make it happen. The more important question is why you need it? File name without date is a file with log from the current day and this log is incomplete during the day. When log is rotated at midnight, old file (the one without the ...
You might be able to use the `namer` property of the handler, which you can set to a callable to customise naming. See [the documentation](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.BaseRotatingHandler.namer) for it.
27,656,401
I've got rather small flask application which I run using: ``` $ python wsgi.py ``` When editing files, server reloads on each file save. This reload takes even up to 10sec. That's system section from my Virtual Box: ``` Base: 2048Mb, Memory: Processors: 4 Acceleration: VT-x/AMD-V, Nested Paging, PAE/NX ``` How ...
2014/12/26
[ "https://Stackoverflow.com/questions/27656401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743105/" ]
Your problem might be virtualenv being sync'd too. I stumbled upon the same problem, and the issue was that VirtualBox's default synchronization implementation is very very slow when dealing with too many files in the mounted directory. Upon investigating, I found: ``` $ cd my-project $ tree | tail -n 1 220 director...
Try changing the file system for NFS. I had this problem, I switched to NFS and has been fixed. ``` config.vm.synced_folder ".", "/vagrant", type: "nfs" ``` [ENABLING NFS SYNCED FOLDERS](http://docs.vagrantup.com/v2/synced-folders/nfs.html)
19,077,580
I use python 2.7.5. I have got some files in the directory/sub directory. Sample of the `file1` is given below ``` Title file name path1 /path/to/file options path2=/path/to/file1,/path/to/file2,/path/to/file3,/path/to/file4 some_vale1 some_vale2 some_value3=abcdefg some_value4=/path/to/value some_value5 ``` ...
2013/09/29
[ "https://Stackoverflow.com/questions/19077580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2221360/" ]
This one-liner does the entire transformation: ``` str = re.sub(r'(options) (\S+)', r'\2\n \1', str.replace('/path/', '/root/directory/path/') ``` See a [live demo](http://codepad.org/I5IpoYcW) of this code
You can try this: ``` result = re.sub(r'([ \t =,])/', replace_text, text, 1) ``` The last `1` is to indicate the first match only, so that only the first path is substituted. By the way, I think that you want to conserve the space/tab or comma right? Make replace\_text like this: ``` replace_text = r'\1/root/direc...
19,077,580
I use python 2.7.5. I have got some files in the directory/sub directory. Sample of the `file1` is given below ``` Title file name path1 /path/to/file options path2=/path/to/file1,/path/to/file2,/path/to/file3,/path/to/file4 some_vale1 some_vale2 some_value3=abcdefg some_value4=/path/to/value some_value5 ``` ...
2013/09/29
[ "https://Stackoverflow.com/questions/19077580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2221360/" ]
Ok. Got the answer from Bohemian and Jerry. Got it working with combined code. ``` str = re.sub(r'(options) (\S+)', r'\2\n \1', re.sub(r'([ \t =,])/', replace_text, text)) ```
You can try this: ``` result = re.sub(r'([ \t =,])/', replace_text, text, 1) ``` The last `1` is to indicate the first match only, so that only the first path is substituted. By the way, I think that you want to conserve the space/tab or comma right? Make replace\_text like this: ``` replace_text = r'\1/root/direc...
30,265,557
I have a matrix with x rows (i.e. the number of draws) and y columns (the number of observations). They represent a distribution of y forecasts. Now I would like to make sort of a 'heat map' of the draws. That is, I want to plot a 'confidence interval' (not really a confidence interval, but just all the values with s...
2015/05/15
[ "https://Stackoverflow.com/questions/30265557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2151205/" ]
So, the hard part of this is transforming your data into the right shape, which is why it's nice to share something that really looks like your data, not just a single column. Let's say your data is this a matrix with 10,000 rows and 10 columns. I'll just use a uniform distribution so it will be a boring plot at the e...
That is not a lot to go on, but I would probably start with the `hexbin` or `hexbinplot` package. Several alternatives are presented in this SO post. [Formatting and manipulating a plot from the R package "hexbin"](https://stackoverflow.com/questions/15504983/formatting-and-manipulating-a-plot-from-the-r-package-hexbi...
38,729,374
My `.profile` defines a function ``` myps () { ps -aef|egrep "a|b"|egrep -v "c\-" } ``` I'd like to execute it from my python script ``` import subprocess subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True) ``` Getting an error back ``` bash: -c: line 0: syntax error near unexpected token...
2016/08/02
[ "https://Stackoverflow.com/questions/38729374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359862/" ]
``` script=''' . ~/.profile # load local function definitions so typeset -f can emit them ssh user@box ksh -s <<EOF $(typeset -f) myps EOF ''' import subprocess subprocess.call(['ksh', '-c', script]) # no shell=True ``` --- There are a few pertinent items here: * The dotfile defining this function needs to be loca...
The original command was not interpreting the `;` before `myps` properly. Using `sh -c` fixes that, but... ( please see Charles Duffy comments below ). Using a combination of single/double quotes sometimes makes the syntax easier to read and less prone to mistakes. With that in mind, a safe way to run the command ( pr...
38,729,374
My `.profile` defines a function ``` myps () { ps -aef|egrep "a|b"|egrep -v "c\-" } ``` I'd like to execute it from my python script ``` import subprocess subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True) ``` Getting an error back ``` bash: -c: line 0: syntax error near unexpected token...
2016/08/02
[ "https://Stackoverflow.com/questions/38729374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359862/" ]
I ended up using this. ``` import subprocess import sys import re HOST = "user@" + box COMMAND = 'my long command with many many flags in single quotes' ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stde...
The original command was not interpreting the `;` before `myps` properly. Using `sh -c` fixes that, but... ( please see Charles Duffy comments below ). Using a combination of single/double quotes sometimes makes the syntax easier to read and less prone to mistakes. With that in mind, a safe way to run the command ( pr...
38,729,374
My `.profile` defines a function ``` myps () { ps -aef|egrep "a|b"|egrep -v "c\-" } ``` I'd like to execute it from my python script ``` import subprocess subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True) ``` Getting an error back ``` bash: -c: line 0: syntax error near unexpected token...
2016/08/02
[ "https://Stackoverflow.com/questions/38729374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359862/" ]
I ended up using this. ``` import subprocess import sys import re HOST = "user@" + box COMMAND = 'my long command with many many flags in single quotes' ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stde...
``` script=''' . ~/.profile # load local function definitions so typeset -f can emit them ssh user@box ksh -s <<EOF $(typeset -f) myps EOF ''' import subprocess subprocess.call(['ksh', '-c', script]) # no shell=True ``` --- There are a few pertinent items here: * The dotfile defining this function needs to be loca...
21,083,746
How do you cache a paginated Django queryset, specifically in a ListView? I noticed one query was taking a long time to run, so I'm attempting to cache it. The queryset is huge (over 100k records), so I'm attempting to only cache paginated subsections of it. I can't cache the entire view or template because there are ...
2014/01/13
[ "https://Stackoverflow.com/questions/21083746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
The problem turned out to be a combination of factors. Mainly, the result returned by the `paginate_queryset()` contains a reference to the unlimited queryset, meaning it's essentially uncachable. When I called `cache.set(mykey, (paginator, page, object_list, other_pages))`, it was trying to serialize thousands of reco...
I wanted to paginate my infinite scrolling view on my home page and this is the solution I came up with. It's a mix of Django CCBVs and the author's initial solution. The response times, however, didn't improve as much as I would've hoped for but that's probably because I am testing it on my local with just 6 posts an...
21,083,746
How do you cache a paginated Django queryset, specifically in a ListView? I noticed one query was taking a long time to run, so I'm attempting to cache it. The queryset is huge (over 100k records), so I'm attempting to only cache paginated subsections of it. I can't cache the entire view or template because there are ...
2014/01/13
[ "https://Stackoverflow.com/questions/21083746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247542/" ]
You can extend the `Paginator` to support caching by a provided `cache_key`. A blog post about usage and implementation of a such `CachedPaginator` can be found [here](http://toastdriven.com/blog/2008/nov/07/cachedpaginator/). The source code is posted at [djangosnippets.org](http://www.djangosnippets.org/snippets/117...
I wanted to paginate my infinite scrolling view on my home page and this is the solution I came up with. It's a mix of Django CCBVs and the author's initial solution. The response times, however, didn't improve as much as I would've hoped for but that's probably because I am testing it on my local with just 6 posts an...
35,795,663
**[What I want]** is to find the only one smallest positive real root of quartic function **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** **[Existing Method]** My equation is for collision prediction, the maximum degree is quartic function as **f(x)** = **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** and **a,b,c,d,e**...
2016/03/04
[ "https://Stackoverflow.com/questions/35795663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6017946/" ]
An other answer : do it with analytic methods ([Ferrari](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Ferrari),[Cardan](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Cardan#Formules_de_Cardan)), and speed the code with Just in Time compilation ([Numba](http://numba.pydata.org)) : Let see the improvement first : ```...
the numpy solution to do that without loop is : ``` p=array([a,b,c,d,e]) r=roots(p) r[(r.imag==0) & (r.real>=0) ].real.min() ``` `scipy.optimize` methods will be slower, unless you don't need precision: ``` In [586]: %timeit r=roots(p);r[(r.imag==0) & (r.real>=0) ].real.min() 1000 loops, best of 3: 334 Β΅s per loop...
35,795,663
**[What I want]** is to find the only one smallest positive real root of quartic function **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** **[Existing Method]** My equation is for collision prediction, the maximum degree is quartic function as **f(x)** = **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** and **a,b,c,d,e**...
2016/03/04
[ "https://Stackoverflow.com/questions/35795663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6017946/" ]
the numpy solution to do that without loop is : ``` p=array([a,b,c,d,e]) r=roots(p) r[(r.imag==0) & (r.real>=0) ].real.min() ``` `scipy.optimize` methods will be slower, unless you don't need precision: ``` In [586]: %timeit r=roots(p);r[(r.imag==0) & (r.real>=0) ].real.min() 1000 loops, best of 3: 334 Β΅s per loop...
In SymPy the `real_roots` function will return the sorted roots of a polynomial and you can loop through them and break on the first positive one: ``` for do in range(100): p = Poly.from_list([randint(-100,100) for i in range(5)], x) for i in real_roots(p): if i.is_positive: print(i) break else: ...
35,795,663
**[What I want]** is to find the only one smallest positive real root of quartic function **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** **[Existing Method]** My equation is for collision prediction, the maximum degree is quartic function as **f(x)** = **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** and **a,b,c,d,e**...
2016/03/04
[ "https://Stackoverflow.com/questions/35795663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6017946/" ]
An other answer : do it with analytic methods ([Ferrari](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Ferrari),[Cardan](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Cardan#Formules_de_Cardan)), and speed the code with Just in Time compilation ([Numba](http://numba.pydata.org)) : Let see the improvement first : ```...
If polynomial coefficients are known ahead of time, you can speed up by vectorizing the computation in `roots` (given Numpy >= 1.10 or so): ``` import numpy as np def roots_vec(p): p = np.atleast_1d(p) n = p.shape[-1] A = np.zeros(p.shape[:1] + (n-1, n-1), float) A[...,1:,:-1] = np.eye(n-2) A[...,...
35,795,663
**[What I want]** is to find the only one smallest positive real root of quartic function **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** **[Existing Method]** My equation is for collision prediction, the maximum degree is quartic function as **f(x)** = **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** and **a,b,c,d,e**...
2016/03/04
[ "https://Stackoverflow.com/questions/35795663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6017946/" ]
An other answer : do it with analytic methods ([Ferrari](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Ferrari),[Cardan](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Cardan#Formules_de_Cardan)), and speed the code with Just in Time compilation ([Numba](http://numba.pydata.org)) : Let see the improvement first : ```...
In SymPy the `real_roots` function will return the sorted roots of a polynomial and you can loop through them and break on the first positive one: ``` for do in range(100): p = Poly.from_list([randint(-100,100) for i in range(5)], x) for i in real_roots(p): if i.is_positive: print(i) break else: ...
35,795,663
**[What I want]** is to find the only one smallest positive real root of quartic function **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** **[Existing Method]** My equation is for collision prediction, the maximum degree is quartic function as **f(x)** = **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e** and **a,b,c,d,e**...
2016/03/04
[ "https://Stackoverflow.com/questions/35795663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6017946/" ]
If polynomial coefficients are known ahead of time, you can speed up by vectorizing the computation in `roots` (given Numpy >= 1.10 or so): ``` import numpy as np def roots_vec(p): p = np.atleast_1d(p) n = p.shape[-1] A = np.zeros(p.shape[:1] + (n-1, n-1), float) A[...,1:,:-1] = np.eye(n-2) A[...,...
In SymPy the `real_roots` function will return the sorted roots of a polynomial and you can loop through them and break on the first positive one: ``` for do in range(100): p = Poly.from_list([randint(-100,100) for i in range(5)], x) for i in real_roots(p): if i.is_positive: print(i) break else: ...
68,400,475
I am trying to display a 2d list as CSV like structure in a new tkinter window here is my code ``` import tkinter as tk import requests import pandas as pd import numpy as np from tkinter import messagebox from finta import TA from math import exp import xlsxwriter from tkinter import * from tkinter.ttk import * impo...
2021/07/15
[ "https://Stackoverflow.com/questions/68400475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15530206/" ]
The problem update 2 is that you are using pack and grid in the same window. When I click submit the new window comes up (I couldn't reproduce that problem) but the word "results" is missing. This is because you are trying to use pack and grid on the same window. To fix this, show "results" using grid like this: ``` c...
I've organized your imports. This should remove naming conflicts. Note: You will have to declare `tkinter` objects with `tk.` and `ttk` objects with `ttk.` This should also help to remove naming conflicts. ```py import tkinter as tk from tkinter import ttk from tkinter import messagebox import requests import csv i...
61,529,832
I have a python script called script.py that has two optional arguments (-a, -b) and has a single positional argument that either accepts a file or uses stdin. I want to make it so that a flag/file cannot be used multiple times. Thus, something like this shouldn't be allowed ``` ./script.py -a 5 -a 7 test.txt ./script...
2020/04/30
[ "https://Stackoverflow.com/questions/61529832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12912748/" ]
@ajrwhite adding attachments had one trick, you need to use 'Alias' from mactypes to convert a string/path object to a mactypes path. I'm not sure why but it works. here's a working example which creates messages with recipients and can add attachments: ``` from appscript import app, k from mactypes import Alias from...
Figured it out using [py-appscript](http://appscript.sourceforge.net/py-appscript/doc_3x/appscript-manual/03_quicktutorial.html) ``` pip install appscript ``` ``` from appscript import app, k outlook = app('Microsoft Outlook') msg = outlook.make( new=k.outgoing_message, with_properties={ k.subject:...
61,529,832
I have a python script called script.py that has two optional arguments (-a, -b) and has a single positional argument that either accepts a file or uses stdin. I want to make it so that a flag/file cannot be used multiple times. Thus, something like this shouldn't be allowed ``` ./script.py -a 5 -a 7 test.txt ./script...
2020/04/30
[ "https://Stackoverflow.com/questions/61529832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12912748/" ]
Figured it out using [py-appscript](http://appscript.sourceforge.net/py-appscript/doc_3x/appscript-manual/03_quicktutorial.html) ``` pip install appscript ``` ``` from appscript import app, k outlook = app('Microsoft Outlook') msg = outlook.make( new=k.outgoing_message, with_properties={ k.subject:...
I have been trying to edit Jayme’s code to send an email to several recipients, and I finally figured that I just had to repeat the following lines: ``` msg.make( new=k.recipient, with_properties={ k.email_address: { k.name: 'Fake Person1', k.address: '[email protected]'}}) msg.make( new=k.rec...
61,529,832
I have a python script called script.py that has two optional arguments (-a, -b) and has a single positional argument that either accepts a file or uses stdin. I want to make it so that a flag/file cannot be used multiple times. Thus, something like this shouldn't be allowed ``` ./script.py -a 5 -a 7 test.txt ./script...
2020/04/30
[ "https://Stackoverflow.com/questions/61529832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12912748/" ]
@ajrwhite adding attachments had one trick, you need to use 'Alias' from mactypes to convert a string/path object to a mactypes path. I'm not sure why but it works. here's a working example which creates messages with recipients and can add attachments: ``` from appscript import app, k from mactypes import Alias from...
I have been trying to edit Jayme’s code to send an email to several recipients, and I finally figured that I just had to repeat the following lines: ``` msg.make( new=k.recipient, with_properties={ k.email_address: { k.name: 'Fake Person1', k.address: '[email protected]'}}) msg.make( new=k.rec...
22,699,040
I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa...
2014/03/27
[ "https://Stackoverflow.com/questions/22699040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153018/" ]
I highly recommend to use this regex which will capture what you want: ``` re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page) ``` explanation: ``` parsable-cite= matches the characters parsable-cite= literally (case sensitive) \\ matches the character \ literally \" matches the character " literally 1st Captur...
Make your regex lazy: ``` re.findall(r'^parsable-cite=.*?>$',page) ^ ``` Or use a negated class (preferable): ``` re.findall(r'^parsable-cite=[^>]*>$',page) ``` `.*` is greedy by default and will try to match as much as possible before concluding a match. [regex101 demo](http://rege...
22,699,040
I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa...
2014/03/27
[ "https://Stackoverflow.com/questions/22699040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153018/" ]
I highly recommend to use this regex which will capture what you want: ``` re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page) ``` explanation: ``` parsable-cite= matches the characters parsable-cite= literally (case sensitive) \\ matches the character \ literally \" matches the character " literally 1st Captur...
The `.*` you have there is "greedy", meaning it will match as much as it can, including any number of `>` characters and whatever comes after them. If what you really want is "everything up to the next `>`" then you should say `[^>]*>` instead, meaning "any number of non-`>` characters, then a `>`".
22,699,040
I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa...
2014/03/27
[ "https://Stackoverflow.com/questions/22699040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153018/" ]
I highly recommend to use this regex which will capture what you want: ``` re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page) ``` explanation: ``` parsable-cite= matches the characters parsable-cite= literally (case sensitive) \\ matches the character \ literally \" matches the character " literally 1st Captur...
maybe something like this: ``` (?<=parsable-cite=\\\")\w{2}\/\d{3}\/\d{3} ``` <http://regex101.com/r/kE9uE3>
22,699,040
I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa...
2014/03/27
[ "https://Stackoverflow.com/questions/22699040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153018/" ]
I highly recommend to use this regex which will capture what you want: ``` re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page) ``` explanation: ``` parsable-cite= matches the characters parsable-cite= literally (case sensitive) \\ matches the character \ literally \" matches the character " literally 1st Captur...
Though this is a json string where html is embedded inside, but you can still use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/documentation.html) for this purpose: ``` soup = BeautifulSoup(htmls); tags = soup.findAll("external-xref", {"parsable-cite":re.compile("")}) for t in tags: print t['parsab...
22,699,040
I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa...
2014/03/27
[ "https://Stackoverflow.com/questions/22699040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153018/" ]
I highly recommend to use this regex which will capture what you want: ``` re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page) ``` explanation: ``` parsable-cite= matches the characters parsable-cite= literally (case sensitive) \\ matches the character \ literally \" matches the character " literally 1st Captur...
This might work if its between `\"` delimiters ``` # \bparsable-cite\s*=\s*\"((?s:(?!\").)*)\" \b parsable-cite \s* = \s* \" ( # (1 start) (?s: (?! \" ) . )* ) # (1 end) \" ``` Or, just ``` # (?s)\bparsable-ci...
22,699,040
I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa...
2014/03/27
[ "https://Stackoverflow.com/questions/22699040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1153018/" ]
I highly recommend to use this regex which will capture what you want: ``` re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page) ``` explanation: ``` parsable-cite= matches the characters parsable-cite= literally (case sensitive) \\ matches the character \ literally \" matches the character " literally 1st Captur...
If you think it will be very similar each time: ``` re.findall(r"pl/\d+/\d+", page) ```
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
I don't know of any, but if all else fails you could use [ctypes](http://docs.python.org/lib/module-ctypes.html) to directly use libdwarf, libelf or libbfd.
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
I don't know of any, but if all else fails you could use [ctypes](http://docs.python.org/lib/module-ctypes.html) to directly use libdwarf, libelf or libbfd.
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
You should give [Construct](http://construct.wikispaces.com/) a try. It is very useful to parse binary data into python objects. There is even an example for the [ELF32](http://sebulbasvn.googlecode.com/svn/trunk/construct/formats/executable/elf32.py) file format.
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
You should give [Construct](http://construct.wikispaces.com/) a try. It is very useful to parse binary data into python objects. There is even an example for the [ELF32](http://sebulbasvn.googlecode.com/svn/trunk/construct/formats/executable/elf32.py) file format.
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
I've been developing a DWARF parser using [Construct](http://construct.wikispaces.com/). Currently fairly rough, and parsing is slow. But I thought I should at least let you know. It may suit your needs, with a bit of work. I've got the code in Mercurial, hosted at bitbucket: * <http://bitbucket.org/cmcqueen1975/pyth...
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
I've been developing a DWARF parser using [Construct](http://construct.wikispaces.com/). Currently fairly rough, and parsing is slow. But I thought I should at least let you know. It may suit your needs, with a bit of work. I've got the code in Mercurial, hosted at bitbucket: * <http://bitbucket.org/cmcqueen1975/pyth...
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
[hachior](http://bitbucket.org/haypo/hachoir/wiki/Home) is another library for parsing binary data
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
[hachior](http://bitbucket.org/haypo/hachoir/wiki/Home) is another library for parsing binary data
45,954
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi...
2008/09/05
[ "https://Stackoverflow.com/questions/45954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
45,107,439
This is more a question out of interest. I observed the following behaviour and would like to know why / how this happens (tried in python 2.7.3 & python 3.4.1) ``` ph = {1:0, 2:0} d1 = {'a':ph, 'b':ph} d2 = {'a':{1:0,2:0},{'b':{1:0,2:0}} >>> d1 {'a':{1:0,2:0},{'b':{1:0,2:0}} ``` so d1 and d2 are the same. However w...
2017/07/14
[ "https://Stackoverflow.com/questions/45107439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8308726/" ]
Try using [pythontutor](http://www.pythontutor.com). If you put your code into it you will see this: [![enter image description here](https://i.stack.imgur.com/z3sr1.png)](https://i.stack.imgur.com/z3sr1.png) You can see that as you suspected the dictionaries in `d1` are references to the same object, `ph`. This mea...
Both keys in `d1` point to the same reference, so when you delete from `d1` it affects `ph` whether you reach it by `d1['a']` or `d1['b']` - you're getting to the same place. `d2` on the other hand instantiates two separate objects, so you're only affecting one of those in your example. Your workaround would be [`.de...
69,687,722
I wanna know how can i get **1 minute** gold price data **of a specific time and date interval** (such as an 1 houre interval in 18th october: 2021-10-18 09:30:00 to 2021-10-18 10:30:00) from yfinance or any other source in python? my code is: ``` gold = yf.download(tickers="GC=F", period="5d", interval="1m") ``` i...
2021/10/23
[ "https://Stackoverflow.com/questions/69687722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4688178/" ]
Your call to `yfinance` returns a Pandas `DataFrame` with `datetime` as the index. We can use this to filter the dataframe to only entries between our `start` and `end` times. ``` import yfinance as yf from datetime import datetime gold = yf.download(tickers="GC=F", period="5d", interval="1m") start = datetime(2021,...
Edit 2021-10-25 =============== To clear my answer. Question was: > > i wanna set specific date and time intervals. thanks > > > All you need is in the code documentation. So `start` and `end` could be date or **\_datetime** ``` start: str Download start date string (YYYY-MM-DD) or _datetime...
59,819,633
i want to login on instagram using selenium python. I tried to find elements by name, tag and css selector but selenium doesn't find any element (i think). I also tried to switch to the iFrame but nothing. This is the error: > > Traceback (most recent call last): > File "C:/Users/anton/Desktop/Instabot/chrome insta...
2020/01/20
[ "https://Stackoverflow.com/questions/59819633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12507302/" ]
You try to return an Object and this is not possible. ``` function Main(){ // create an array that holds objects const people = [ { firstName: 'Fathi', lastName: 'Noor', age: 27, colors: ['red', 'blue'], bodyAttributes: { weig...
You have to `map` the array. See this [doc](https://reactjs.org/docs/lists-and-keys.html). For each person, you decide how to display each field, here I used `<p>` tags, you can display them in a table, or in a custom card.. Your choice! Remember that inside `{}` brackets goes Javascript expressions while in `()` go...
59,819,633
i want to login on instagram using selenium python. I tried to find elements by name, tag and css selector but selenium doesn't find any element (i think). I also tried to switch to the iFrame but nothing. This is the error: > > Traceback (most recent call last): > File "C:/Users/anton/Desktop/Instabot/chrome insta...
2020/01/20
[ "https://Stackoverflow.com/questions/59819633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12507302/" ]
You try to return an Object and this is not possible. ``` function Main(){ // create an array that holds objects const people = [ { firstName: 'Fathi', lastName: 'Noor', age: 27, colors: ['red', 'blue'], bodyAttributes: { weig...
``` function Main(){ // create an array that holds objects const people = [ { firstName: 'Fathi', lastName: 'Noor', age: 27, colors: ['red', 'blue'], bodyAttributes: { weight: 64, height: 171 } ...
50,091,373
I am new to using Pandas on Windows and I'm not sure what I am doing wrong here. My data is located at 'C:\Users\me\data\lending\_club\loan.csv' ``` path = 'C:\\Users\\me\\data\\lending_club\\loan.csv' pd.read_csv(path) ``` And I get this error: ``` ----------------------------------------------------------------...
2018/04/29
[ "https://Stackoverflow.com/questions/50091373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3971910/" ]
Just use forward slash(`'/'`) instead of backslash(`'\'`) ``` path = 'C:/Users/me/data/lending_club/loan.csv' ```
Python only access to the current folder's files. If you want to access files from an other folder, try this : ``` import sys sys.path.insert(0, 'C:/Users/myFolder') ``` Those lines allow your script to access an other folder. Be carrefull, you shoud use slashes /, not backslashes \
51,947,506
i have been trying to install module for python-3.6 through pip. i've read these post from stackoverflow and from python website, which seemed promising but they didn't worked for me. [Install a module using pip for specific python version](https://stackoverflow.com/questions/10919569/install-a-module-using-pip-for-sp...
2018/08/21
[ "https://Stackoverflow.com/questions/51947506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088290/" ]
to install package for a specific python installation, you need a package installer shipped with that installation, in your case, `pip` is installed by an anaconda installation, use `pip.exe` or `easy_install.exe` from this python3.6 installation's `Scripts` directory instead.
First, Uninstall all the versions you have! then go to the library <https://www.python.org/downloads/> Select the required vesrsion MSI file. Run as administrator!
51,947,506
i have been trying to install module for python-3.6 through pip. i've read these post from stackoverflow and from python website, which seemed promising but they didn't worked for me. [Install a module using pip for specific python version](https://stackoverflow.com/questions/10919569/install-a-module-using-pip-for-sp...
2018/08/21
[ "https://Stackoverflow.com/questions/51947506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088290/" ]
to install package for a specific python installation, you need a package installer shipped with that installation, in your case, `pip` is installed by an anaconda installation, use `pip.exe` or `easy_install.exe` from this python3.6 installation's `Scripts` directory instead.
i think as my python was 3.6 also my anaconda distribution, So anaconda was automatically taking over all commands. i installed python 3.7 with anaconda 3.6 and it worked fine as it was mentioned in python website
42,776,294
I need to extract list of IP addresses and port number as well as other information in the following html table, I am using python 2.7 with lxml currently, but have no idea how to find the proper path to these elements, here is the address to table: [link to table](https://hidester.com/proxylist/)
2017/03/14
[ "https://Stackoverflow.com/questions/42776294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1624681/" ]
Looking at the examples at [github](https://github.com/kivy/kivy/search?utf8=%E2%9C%93&q=background_color "github") it seems the values aren't 0-255 RGB like you might expect but are 0.0-1.1 ``` bubble.background_color = (1, 0, 0, .5) #50% translucent red background_color: .8, .8, 0, 1 ``` etc. You'll probably need...
delete background\_normal: ' ', just use background\_color: (R, G, B, A) pick a color in this [tool](https://developer.mozilla.org/es/docs/Web/CSS/CSS_Colors/Herramienta_para_seleccionar_color) and divide R, G and B by 100 A=always 1 (transparency), for example if you choose (255, 79, 25, 1) write instead (2.55, 0.79, ...
21,821,045
I want to get a buffer from a numpy array in Python 3. I have found the following code: ``` $ python3 Python 3.2.3 (default, Sep 25 2013, 18:25:56) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> a = numpy.arange(10) >>> numpy.getbuffer(a) ``` Howeve...
2014/02/17
[ "https://Stackoverflow.com/questions/21821045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856504/" ]
According to [Developer notes on the transition to Python 3](https://github.com/numpy/numpy/blob/master/doc/Py3K.rst.txt#pybuffer-object): > > PyBuffer (object) > > > Since there is a native buffer object in Py3, the `memoryview`, the > `newbuffer` and **`getbuffer` functions are removed from multiarray in Py3**: ...
Numpy's [`arr.tobytes()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tobytes.html) seems to be significantly faster than [`bytes(memoryview(arr))`](https://docs.python.org/dev/library/stdtypes.html#memoryview) in returning a `bytes` object. So, you may want to have a look at `tobytes()` as well. ...
10,830,820
I need to backup various file types to GDrive (not just those convertible to GDocs formats) from some linux server. What would be the simplest, most elegant way to do that with a python script? Would any of the solutions pertaining to GDocs be applicable?
2012/05/31
[ "https://Stackoverflow.com/questions/10830820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303295/" ]
You can use the Documents List API to write a script that writes to Drive: <https://developers.google.com/google-apps/documents-list/> Both the Documents List API and the Drive API interact with the same resources (i.e. same documents and files). This sample in the Python client library shows how to upload an unconv...
The current documentation for saving a file to google drive using python can be found here: <https://developers.google.com/drive/v3/web/manage-uploads> However, the way that the google drive api handles document storage and retrieval does not follow the same architecture as POSIX file systems. As a result, if you wish...
10,830,820
I need to backup various file types to GDrive (not just those convertible to GDocs formats) from some linux server. What would be the simplest, most elegant way to do that with a python script? Would any of the solutions pertaining to GDocs be applicable?
2012/05/31
[ "https://Stackoverflow.com/questions/10830820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303295/" ]
You can use the Documents List API to write a script that writes to Drive: <https://developers.google.com/google-apps/documents-list/> Both the Documents List API and the Drive API interact with the same resources (i.e. same documents and files). This sample in the Python client library shows how to upload an unconv...
I found that [PyDrive](https://pypi.python.org/pypi/PyDrive) handles the Drive API elegantly, and it also has great [documentation](http://pythonhosted.org/PyDrive/quickstart.html) (especially walking the user through the authentication part). **EDIT:** Combine that with the material on [Automating pydrive verificati...
42,852,722
I'm iterating through such a feed: ``` {"siri":{"serviceDelivery":{"responseTimestamp":"2017-03-14T18:37:23Z","producerRef":"IVTR_RELAIS","status":"true","estimatedTimetableDelivery":[ {"lineRef":{"value":"C01742"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"SNCF-ACCES:VehicleJourney::UPAL97_2017031...
2017/03/17
[ "https://Stackoverflow.com/questions/42852722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5689072/" ]
See the code snippet ``` public static class MyDownloadTask extends AsyncTask<Void, Integer, Void> { @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // receive the published update here // progressBar.setProgress(values[0]); } @O...
With this example you can set download speed on your progressdialog ``` public class AsyncDownload extends AsyncTask<Void, Double, String> { ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(MainActivity.thi...
22,923,983
I am embedding python code in my c++ program. The use of PyFloat\_AsDouble is causing loss of precision. It keeps only up to 6 precision digits. My program is very sensitive to precision. Is there a known fix for this? Here is the relevant C++ code: ``` _ret = PyObject_CallObject(pFunc, pArgs); vector<double> retVals...
2014/04/07
[ "https://Stackoverflow.com/questions/22923983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249560/" ]
Assuming that the Python object contains floating point values stored to double precision, then your code works as you expect. Most likely you are simply mis-diagnosing a problem that does not exist. My guess is that you are looking at the values in the debugger which only displays the values to a limited precision. O...
print type(PyList\_GetItem(\_ret, i)) My bet is it will show float. Edit: in the python code, not in the C++ code.
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
you can escape the interpolation of `{two}` by doubling the curly brackets: ``` x = "this string takes two like {one} and {{two}}" y = x.format(one=1) z = y.format(two=2) print(z) # this string takes two like 1 and 2 ``` --- a different way to go are [template strings](https://docs.python.org/3/library/string.html#...
You can replace `{two}` by `{two}` to enable further replacement later: ``` y = x.format(one="one", two="{two}") ``` This easily extends in multiple replacement passages, but it requires that you give all keys, in each iteration.
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
If placeholders in your string don't have any format specifications, in Python 3 you can use `str.format_map` and provide a mapping, returning the field name for missing fields: ``` class Default(dict): def __missing__(self, key): return '{' + key + '}' ``` ``` In [6]: x = "this string takes two like {on...
you can escape the interpolation of `{two}` by doubling the curly brackets: ``` x = "this string takes two like {one} and {{two}}" y = x.format(one=1) z = y.format(two=2) print(z) # this string takes two like 1 and 2 ``` --- a different way to go are [template strings](https://docs.python.org/3/library/string.html#...
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
you can escape the interpolation of `{two}` by doubling the curly brackets: ``` x = "this string takes two like {one} and {{two}}" y = x.format(one=1) z = y.format(two=2) print(z) # this string takes two like 1 and 2 ``` --- a different way to go are [template strings](https://docs.python.org/3/library/string.html#...
All great answers, I will start using this `Template` package soon. Very disappointed in the default behavior here, not understanding why a string template requires passing all the keys each time, if there are 3 keys I can't see a logical reason you can't pass 1 or 2 (but I also don't know how compilers work) Solved b...
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
I think [`string.Template`](https://docs.python.org/2/library/string.html#string.Template) does what you want: ``` from string import Template s = "this string takes two like $one and $two" s = Template(s).safe_substitute(one=1) print(s) # this string takes two like 1 and $two s = Template(s).safe_substitute(two=2) ...
You can replace `{two}` by `{two}` to enable further replacement later: ``` y = x.format(one="one", two="{two}") ``` This easily extends in multiple replacement passages, but it requires that you give all keys, in each iteration.
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
If placeholders in your string don't have any format specifications, in Python 3 you can use `str.format_map` and provide a mapping, returning the field name for missing fields: ``` class Default(dict): def __missing__(self, key): return '{' + key + '}' ``` ``` In [6]: x = "this string takes two like {on...
You can replace `{two}` by `{two}` to enable further replacement later: ``` y = x.format(one="one", two="{two}") ``` This easily extends in multiple replacement passages, but it requires that you give all keys, in each iteration.
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
You can replace `{two}` by `{two}` to enable further replacement later: ``` y = x.format(one="one", two="{two}") ``` This easily extends in multiple replacement passages, but it requires that you give all keys, in each iteration.
All great answers, I will start using this `Template` package soon. Very disappointed in the default behavior here, not understanding why a string template requires passing all the keys each time, if there are 3 keys I can't see a logical reason you can't pass 1 or 2 (but I also don't know how compilers work) Solved b...
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
If placeholders in your string don't have any format specifications, in Python 3 you can use `str.format_map` and provide a mapping, returning the field name for missing fields: ``` class Default(dict): def __missing__(self, key): return '{' + key + '}' ``` ``` In [6]: x = "this string takes two like {on...
I think [`string.Template`](https://docs.python.org/2/library/string.html#string.Template) does what you want: ``` from string import Template s = "this string takes two like $one and $two" s = Template(s).safe_substitute(one=1) print(s) # this string takes two like 1 and $two s = Template(s).safe_substitute(two=2) ...
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
I think [`string.Template`](https://docs.python.org/2/library/string.html#string.Template) does what you want: ``` from string import Template s = "this string takes two like $one and $two" s = Template(s).safe_substitute(one=1) print(s) # this string takes two like 1 and $two s = Template(s).safe_substitute(two=2) ...
All great answers, I will start using this `Template` package soon. Very disappointed in the default behavior here, not understanding why a string template requires passing all the keys each time, if there are 3 keys I can't see a logical reason you can't pass 1 or 2 (but I also don't know how compilers work) Solved b...
44,576,509
I am having a problem like ``` In [5]: x = "this string takes two like {one} and {two}" In [6]: y = x.format(one="one") --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-6-b3c89fbea4d3> in <module>() -...
2017/06/15
[ "https://Stackoverflow.com/questions/44576509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3282434/" ]
If placeholders in your string don't have any format specifications, in Python 3 you can use `str.format_map` and provide a mapping, returning the field name for missing fields: ``` class Default(dict): def __missing__(self, key): return '{' + key + '}' ``` ``` In [6]: x = "this string takes two like {on...
All great answers, I will start using this `Template` package soon. Very disappointed in the default behavior here, not understanding why a string template requires passing all the keys each time, if there are 3 keys I can't see a logical reason you can't pass 1 or 2 (but I also don't know how compilers work) Solved b...
32,703,469
I am new to kafka. We are trying to import data from a csv file to Kafka. We need to import everyday, in the mean while the previous day's data is depredated. How could remove all messages under a Kafka topic in python? or how could I remove the Kafka topic in python? Or I saw someone suggest to wait to data expire, ho...
2015/09/21
[ "https://Stackoverflow.com/questions/32703469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1028315/" ]
You cannot delete messages in Kafka topic. You can: * Set `log.retention.*` properties which is basically the expiration of messages. You can choose either time-based expiration (e. g. keep messages that are six hour old or newer) or space-based expiration (e. g. keep at max 1 GB of messages). See [Broker config](http...
The simplest approach is to simply delete the topic. I use this in Python automated test suites, where I want to verify a specific set of test messages gets sent through Kafka, and don't want to see results from previous test runs ``` def delete_kafka_topic(topic_name): call(["/usr/bin/kafka-topics", "--zookeeper"...
43,214,036
I've a python script that I'm invoking from C#. Code Provided below. Issue with this process is that if Python script fails I'm not able to understand in C# and display that exception. I'm using C#, MVC, Python. Can you please modify below code and show me how can I catch the exception thrown at the time of Python Scri...
2017/04/04
[ "https://Stackoverflow.com/questions/43214036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4879531/" ]
Here is the working code.. To get the error or any exception in Python to C# RedirectStandardError property true and next get the Standard Error. Working version of the code is provided below - ``` process.StartInfo = processStartInfo; processStartInfo.RedirectStandardError = true; ...
You can subscribe for `ErrorDataReceived` event and read the error message. ``` process.ErrorDataReceived+=process_ErrorDataReceived; ``` and here is your event handler ``` void process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(e.Data); } ```
43,214,036
I've a python script that I'm invoking from C#. Code Provided below. Issue with this process is that if Python script fails I'm not able to understand in C# and display that exception. I'm using C#, MVC, Python. Can you please modify below code and show me how can I catch the exception thrown at the time of Python Scri...
2017/04/04
[ "https://Stackoverflow.com/questions/43214036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4879531/" ]
Here is the working code.. To get the error or any exception in Python to C# RedirectStandardError property true and next get the Standard Error. Working version of the code is provided below - ``` process.StartInfo = processStartInfo; processStartInfo.RedirectStandardError = true; ...
You can get exceptions passed from Python to C# when embedding CPython in C# with pythonnet: <https://github.com/pythonnet/pythonnet/blob/master/README.md>
37,947,258
Newbie in mongodb/python/pymongo. My mongodb client code works OK. Here it is : ``` db.meteo.find().forEach( function(myDoc) { db.test.update({"contract_name" : myDoc.current_observation.observation_location.city}, { $set: { "temp_c_meteo" : myDoc.current_observation.temp_c , ...
2016/06/21
[ "https://Stackoverflow.com/questions/37947258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6494503/" ]
Try this solution: ``` ArrayList<IonicBond> list = IonicBond.where { typeRs { classCode == "WD996" } || typeIIs { classCode == "WD996" } }.list() ```
Detached Criteria is one way to query the GORM. You first create a DetachedCriteria with the name of the domain class for which you want to execute the query. Then you call the method 'build' with a 'where' query or criteria query. ``` def criteria = new DetachedCriteria(IonicBond).build { or { typeI...
37,947,258
Newbie in mongodb/python/pymongo. My mongodb client code works OK. Here it is : ``` db.meteo.find().forEach( function(myDoc) { db.test.update({"contract_name" : myDoc.current_observation.observation_location.city}, { $set: { "temp_c_meteo" : myDoc.current_observation.temp_c , ...
2016/06/21
[ "https://Stackoverflow.com/questions/37947258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6494503/" ]
I found out that `createCriteria()` uses `INNER JOIN` by default, meaning it will really not include `IonicBond` instances that have only `typeIIs` children, or `typeRs`, only both. The solution is to change it to a `LEFT JOIN` using `createAlias()`: ``` import org.hibernate.Criteria ... ArrayList<IonicBond> list...
Detached Criteria is one way to query the GORM. You first create a DetachedCriteria with the name of the domain class for which you want to execute the query. Then you call the method 'build' with a 'where' query or criteria query. ``` def criteria = new DetachedCriteria(IonicBond).build { or { typeI...
19,252,087
Hi all we are using google api for e.g. this one '<http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s>' % query via python script but very fast it gets blocked. Any work around for this? Thank you. Below is my current codes. ``` #!/usr/bin/env python import math,sys import json import urllib def gsearch(s...
2013/10/08
[ "https://Stackoverflow.com/questions/19252087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711681/" ]
Try this: ``` $(".profileImage").click(function() { $(this).animate({opacity: "0.0"}).animate({width: 0}).hide(0); }) ``` Animate your opacity to 0 to fade it from view, then animate your width to 0 to regain the space, then hide it to remove it from visibility altogether. Note that if you want to redisplay, you...
what about using the fadeOut callback ``` $(".profileImage").click(function() { $(this).animate({opacity:0},400, function(){ // sliding code goes here $(this).animate({width:0},300).hide(); }); }); ```
67,764,659
I working with vscode for python programming.how can i change color text error output in terminal? .can you help me?
2021/05/30
[ "https://Stackoverflow.com/questions/67764659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847527/" ]
may be useful for someOne. for First and last day of Persian Month : ``` function GetStartEndMonth(currentDate) { const splitDate = splitGeorgianDateToPersianDateArray(currentDate); const year = splitDate[0]; const month = splitDate[1]; const lastDayOfPersianMonth = GetLastDayOfPersianMonth(month, ...
I think you need to set ``` dayGridMonthPersian :{duration: { week: 4 }} ```
53,489,173
I understand there are many answers already on SO dealing with split python URL's. BUT, I want to split a URL and then use it in a function. I'm using a curl request in python: ``` r = requests.get('http://www.datasciencetoolkit.org/twofishes?query=New%York') r.json() ``` Which provides the following: ``` {'interp...
2018/11/26
[ "https://Stackoverflow.com/questions/53489173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9439560/" ]
Taking your example, I'd suggest using regex and string interpolation. This answer assumes the API returns data the same way every time. ``` import re, requests def lat_long(city: str) -> tuple: # replace spaces with escapes city = re.sub('\s', '%20', city) res = requests.get(f'http://www.datasciencetoolk...
You can loop over this list 'interpretations' looking for the city name, and return the coordinates when you find the correct city. ``` def lat_long(city): geocode_result = requests.get('http://www.datasciencetoolkit.org/twofishes?query= "city"') for interpretation in geocode_result["interpretations"]: ...