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
5,333,509
What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it? For example I have the numbers 1,2,5,15 and I want to reverse the bits like so: ``` original reversed 1 - 0001 - 1000 - 8 2 - 0010 - 0100 - 4 5 - 0101 - 1010 - 10 15 - 1111 - 1111...
2011/03/17
[ "https://Stackoverflow.com/questions/5333509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
``` reversed_ = sum(1<<(numbits-1-i) for i in range(numbits) if original>>i&1) ```
Numpy indexing arrays provide concise notation for application of bit reversal permutations. ``` import numpy as np def bitrev_map(nbits): """create bit reversal mapping >>> bitrev_map(3) array([0, 4, 2, 6, 1, 5, 3, 7], dtype=uint16) >>> import numpy as np >>> np.arange(8)[bitrev_map(3)] array([0, 4, 2, ...
5,333,509
What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it? For example I have the numbers 1,2,5,15 and I want to reverse the bits like so: ``` original reversed 1 - 0001 - 1000 - 8 2 - 0010 - 0100 - 4 5 - 0101 - 1010 - 10 15 - 1111 - 1111...
2011/03/17
[ "https://Stackoverflow.com/questions/5333509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
``` reversed_ = sum(1<<(numbits-1-i) for i in range(numbits) if original>>i&1) ```
You can do something like this where you can define how many bits in the argument l. ``` def reverse(x, l): r = x & 1 for i in range (1, l): r = r << 1 | (x >> i) & 1 print(bin(r)) return r ```
5,333,509
What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it? For example I have the numbers 1,2,5,15 and I want to reverse the bits like so: ``` original reversed 1 - 0001 - 1000 - 8 2 - 0010 - 0100 - 4 5 - 0101 - 1010 - 10 15 - 1111 - 1111...
2011/03/17
[ "https://Stackoverflow.com/questions/5333509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
If you truly want 32 bits rather than 4, then here is a function to do what you want: ``` def revbits(x): return int(bin(x)[2:].zfill(32)[::-1], 2) ``` Basically I'm converting to binary, stripping off the '0b' in front, filling with zeros up to 32 chars, reversing, and converting back to an integer. It might ...
Numpy indexing arrays provide concise notation for application of bit reversal permutations. ``` import numpy as np def bitrev_map(nbits): """create bit reversal mapping >>> bitrev_map(3) array([0, 4, 2, 6, 1, 5, 3, 7], dtype=uint16) >>> import numpy as np >>> np.arange(8)[bitrev_map(3)] array([0, 4, 2, ...
5,333,509
What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it? For example I have the numbers 1,2,5,15 and I want to reverse the bits like so: ``` original reversed 1 - 0001 - 1000 - 8 2 - 0010 - 0100 - 4 5 - 0101 - 1010 - 10 15 - 1111 - 1111...
2011/03/17
[ "https://Stackoverflow.com/questions/5333509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
[This](http://wiki.python.org/moin/BitwiseOperators) is the first link I found googling for "python bitwise" and it has a pretty good summary of how to do bit-twiddling in Python. If you don't care too much about speed, the most straightforward solution is to go through each bit-place of the original number and, if it...
You can do something like this where you can define how many bits in the argument l. ``` def reverse(x, l): r = x & 1 for i in range (1, l): r = r << 1 | (x >> i) & 1 print(bin(r)) return r ```
28,055,565
I have an python `dict` whose keys and values are strings, integers and other dicts and tuples ([json does not support those](https://stackoverflow.com/q/7001606/850781)). I want to save it to a text file and then read it from the file. **Basically, I want a [`read`](http://www.lispworks.com/documentation/HyperSpec/Bod...
2015/01/20
[ "https://Stackoverflow.com/questions/28055565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/850781/" ]
You could use `repr()` on the `dict`, then read it back in and parse it with `ast.literal_eval()`. It's as human readable as Python itself is. Example: ``` In [1]: import ast In [2]: x = {} In [3]: x['string key'] = 'string value' In [4]: x[(42, 56)] = {'dict': 'value'} In [5]: x[13] = ('tuple', 'value') In [6]:...
Honestly, json is your answer [EDIT: so long as the keys are strings, didn't see the part about dicts as keys], and that's why it's taken over in the least 5 years. What legibility issues does json have? There are tons of json indenter, pretty-printer utilities, browser plug-ins [1][2] - use them and it certainly is hu...
73,067,801
I'm using databricks, and I have a repo in which I have a basic python module within which I define a class. I'm able to import and access the class and its methods from the databricks notebook. One of the methods within the class within the module looks like this (simplified) ```py def read_raw_json(self): ...
2022/07/21
[ "https://Stackoverflow.com/questions/73067801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9485834/" ]
The INFILE statement is for reading a file as raw TEXT. If you have a SAS dataset then you can just SET the dataset to read it into a data step. So the equivalent for your attempted method would be something like: ``` data _null_; set "C:\myfiles\sample.sas7bdat" end=eof; if eof then put "Observations read=====...
One cool thing about sas7bdat files is the amount of metadata stored with them. The row count of that file is already known by SAS as an attribute. You can use `proc contents` to read it. `Observations` is the number of rows in the table. ``` libname files "C:\myfiles"; proc contents data=files.sample; run; ``` A m...
57,009,331
I'm currently coding a text based game in python in which the narrative will start differently depending on answers to certain questions. The first question is simple, a name. I can't seem to get the input to display in the correct text option after the prompt. I tried using "if name is True" and "if name is str" ...
2019/07/12
[ "https://Stackoverflow.com/questions/57009331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11389547/" ]
use `isinstance` instead of `is`. And, You do not need to use `str(input())` because `input` returns `str`. ``` while True: try: # This will query for first user input, Name. name = input("Please enter your name: ") except ValueError: print("Sorry, I didn't understand that.") # ...
The exception handling around `input` is not required as the `input` function always returns a string. If the user does not enter a value an empty string is returned. Therefore your code can be simplified to ``` name = input("Please enter your name: ") # In python an empty string is considered `False` allowing # yo...
57,009,331
I'm currently coding a text based game in python in which the narrative will start differently depending on answers to certain questions. The first question is simple, a name. I can't seem to get the input to display in the correct text option after the prompt. I tried using "if name is True" and "if name is str" ...
2019/07/12
[ "https://Stackoverflow.com/questions/57009331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11389547/" ]
use `isinstance` instead of `is`. And, You do not need to use `str(input())` because `input` returns `str`. ``` while True: try: # This will query for first user input, Name. name = input("Please enter your name: ") except ValueError: print("Sorry, I didn't understand that.") # ...
The issue is you're checking if name is str, not if type(name) is str. ``` if type(name) is str: ```
55,327,900
I'm currently developing my first python program, a booking system using tkinter. I have a customer account creation screen that uses a number of Entry boxes. When the Entry box is clicked the following key bind is called to clear the entry box of its instruction (ie. "enter name") ``` def entry_click(event): if "en...
2019/03/24
[ "https://Stackoverflow.com/questions/55327900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11240330/" ]
Just add an arg to your `entry_focusout` event and bind to the `Entry` widgets with a lambda function. ``` from tkinter import * root = Tk() def entry_click(event): if event.widget["foreground"] == "grey": event.widget.delete(0, "end") event.widget.insert(0, "") event.widget.configure(fg="black") d...
> > **Question**: Return empty `tk.Entry` box to previous state when clicked away > > > The following is a `OOP` **universal** solution. Thanks to @Henry Yik, for the `if event.widget["foreground"] == "grey":` part. ``` class EntryInstruction(tk.Entry): def __init__(self, parent, instruction=None): ...
6,003,932
``` import cgi def fill(): s = """\ <html><body> <form method="get" action="./show"> <p>Type a word: <input type="text" name="word"> <input type="submit" value="Submit"</p> </form></body></html> """ return s # Receive the Request object def show(req): # The getfirst() method returns the value of the first fi...
2011/05/14
[ "https://Stackoverflow.com/questions/6003932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/640666/" ]
``` while flag!=1: x=1 ``` This loop won't ever finish. When is `flag` ever going to change so that `flag != 1` is False? Remember, `flag` is a *local* variable so changing it anywhere else isn't going to have an effect -- especially since no other code is going to have the opportunity to run while that l...
it is not the most elegant way to do this, but if you need to change the value of flag outside your method, you should use it as a `global` variable. ``` def test(): global flag # use this everywhere you're using flag. print flag while flag!=1: x=1 return ``` but to make a waiting meth...
59,282,950
We use python with pyspark api in order to run simple code on spark cluster. ``` from pyspark import SparkContext, SparkConf conf = SparkConf().setAppName('appName').setMaster('spark://clusterip:7077') sc = SparkContext(conf=conf) rdd = sc.parallelize([1, 2, 3, 4]) rdd.map(lambda x: x**2).collect() ``` It works wh...
2019/12/11
[ "https://Stackoverflow.com/questions/59282950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4406595/" ]
You try to run pyspark (which calls spark-submit) form a remote computer outside the spark cluster. This is technically possible but it is not the intended way of deploying applications. In yarn mode, it will make your computer participate in the spark protocol as a client. Thus it would require opening several ports a...
According to this [Amazon Doc](https://aws.amazon.com/premiumsupport/knowledge-center/emr-submit-spark-job-remote-cluster/?nc1=h_ls), you can't do that: > > *Common errors* > > > **Standalone mode** > > > Amazon EMR doesn't support standalone mode for Spark. It's not > possible to submit a Spark application to a...
1,247,133
Working in python I want to extract a dataset with the following structure: Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the poten...
2009/08/07
[ "https://Stackoverflow.com/questions/1247133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408134/" ]
you should probably use a defaultdictionary for this: ``` from collections import defaultdict itemdict = defaultdict(list) for id, parent_id in itemlist: itemdict[parent_id].append(id) ``` then you can recursively print it (with indentation) like ``` def printitem(id, depth=0): print ' '*depth, id ...
Are you saying that each item only maintains a reference to its parents? If so, then how about ``` def getChildren(item) : children = [] for possibleChild in allItems : if (possibleChild.parent == item) : children.extend(getChildren(possibleChild)) return children ``` This returns a l...
1,247,133
Working in python I want to extract a dataset with the following structure: Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the poten...
2009/08/07
[ "https://Stackoverflow.com/questions/1247133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408134/" ]
Are you saying that each item only maintains a reference to its parents? If so, then how about ``` def getChildren(item) : children = [] for possibleChild in allItems : if (possibleChild.parent == item) : children.extend(getChildren(possibleChild)) return children ``` This returns a l...
How about something like this, ``` #!/usr/bin/python tree = { 0:(None, [1,2,3]), 1:(0, [4]), 2:(0, []), 3:(0, [5,6]), 4:(1, [7]), 5:(3, []), 6:(3, []), ...
1,247,133
Working in python I want to extract a dataset with the following structure: Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the poten...
2009/08/07
[ "https://Stackoverflow.com/questions/1247133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408134/" ]
you should probably use a defaultdictionary for this: ``` from collections import defaultdict itemdict = defaultdict(list) for id, parent_id in itemlist: itemdict[parent_id].append(id) ``` then you can recursively print it (with indentation) like ``` def printitem(id, depth=0): print ' '*depth, id ...
If you want to keep the structure of your dataset, this will produce a list of the format [id, [children of id], id2, [children of id2]] ``` def children(id): return [id]+[children(x.id) for x in filter(lambda x:x.parent == id, items)] ```
1,247,133
Working in python I want to extract a dataset with the following structure: Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the poten...
2009/08/07
[ "https://Stackoverflow.com/questions/1247133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408134/" ]
If you want to keep the structure of your dataset, this will produce a list of the format [id, [children of id], id2, [children of id2]] ``` def children(id): return [id]+[children(x.id) for x in filter(lambda x:x.parent == id, items)] ```
How about something like this, ``` #!/usr/bin/python tree = { 0:(None, [1,2,3]), 1:(0, [4]), 2:(0, []), 3:(0, [5,6]), 4:(1, [7]), 5:(3, []), 6:(3, []), ...
1,247,133
Working in python I want to extract a dataset with the following structure: Each item has a unique ID and the unique ID of its parent. Each parent can have one or more children, each of which can have one or more children of its own, to n levels i.e. the data has an upturned tree-like structure. While it has the poten...
2009/08/07
[ "https://Stackoverflow.com/questions/1247133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408134/" ]
you should probably use a defaultdictionary for this: ``` from collections import defaultdict itemdict = defaultdict(list) for id, parent_id in itemlist: itemdict[parent_id].append(id) ``` then you can recursively print it (with indentation) like ``` def printitem(id, depth=0): print ' '*depth, id ...
How about something like this, ``` #!/usr/bin/python tree = { 0:(None, [1,2,3]), 1:(0, [4]), 2:(0, []), 3:(0, [5,6]), 4:(1, [7]), 5:(3, []), 6:(3, []), ...
7,394,301
i have a class "karte" i want to know is there a way of dynamic name creation of my new objects normal object creation would be > > karta=karte() > > > but i am curious in something like this > > karta[i]=karte() > > > or something like that where i would be the number of for loop. and at the end i would ca...
2011/09/12
[ "https://Stackoverflow.com/questions/7394301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666160/" ]
You can create a list of objects like this: ``` karta = [] for i in range(10): karta.append(karte()) ``` Or using a list comprehension: ``` karta = [karte() for i in range(10)] ``` Now you can access the objects like this: `karta[i]`. To accomplish your last example, you have to modify the `globals()` dictio...
Unless you have a real need to keep the objects out of a list and have names like karta1, karta2, etc. I would do as you suggest and use a list with a loop to initialize: ``` for i in some_range: karta[i]=karte() ```
69,238,333
I'm trying to fit a curve to a differential equation. For the sake of simplicity, I'm just doing the logistic equation here. I wrote the code below but I get an error shown below it. I'm not quite sure what I'm doing wrong. ``` import numpy as np import pandas as pd import scipy.optimize as optim from scipy.integrate ...
2021/09/18
[ "https://Stackoverflow.com/questions/69238333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10796158/" ]
@hpaulj has pointed out the problem with the shape of the return value from `logistic_solution` and shown that fixing that eliminates the error that you reported. There is, however, another problem in the code. The problem does not generate an error, but it does result in an incorrect solution to your test problem (th...
A sample run of `logistic_solution` produces a (18,1) result: ``` In [268]: logistic_solution(df_yeast['td'], *parsic) Out[268]: array([[ 1.00000000e+00], [ 2.66666671e+00], [ 4.33333337e+00], [ 1.00000004e+00], [-1.23333333e+01], [-4.06666666e+01], [-8.90000000e+01], ...
35,930,924
I am new to Python(I am using Python2.7) and Pycharm, but I need to use MySQLdb module to complete my task. I spent time to search for some guides or tips and finally I go to here but does not found MySQLdb to install. [MySQL-python](http://i.stack.imgur.com/EhTaq.png) But there is error: [Error](http://i.stack.imgur...
2016/03/11
[ "https://Stackoverflow.com/questions/35930924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5886173/" ]
I have a suggestion,if you have install MySQL database,you follow this,open pycharm and click File->Settings->Project->Project Interpreter,then select your Python interpreter and click install button (the little green plus sign),input "MySQL-Python" and click the button "install package",you will install MySQL-Python s...
From Windows Command Prompt / Linux Shell install using wheel ``` pip install wheel ``` Download 32 or 64 Bit version from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python> **64-Bit** ``` pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl ``` **32-Bit** ``` pip install MySQL_python-1.2.5-cp27-none-...
35,930,924
I am new to Python(I am using Python2.7) and Pycharm, but I need to use MySQLdb module to complete my task. I spent time to search for some guides or tips and finally I go to here but does not found MySQLdb to install. [MySQL-python](http://i.stack.imgur.com/EhTaq.png) But there is error: [Error](http://i.stack.imgur...
2016/03/11
[ "https://Stackoverflow.com/questions/35930924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5886173/" ]
If you are unable to install MySQL CLient in Pycharm, try opening the Terminal (Alt+F12) and write the command ``` pip install --only-binary :all: mysqlclient ``` This might help!
From Windows Command Prompt / Linux Shell install using wheel ``` pip install wheel ``` Download 32 or 64 Bit version from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python> **64-Bit** ``` pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl ``` **32-Bit** ``` pip install MySQL_python-1.2.5-cp27-none-...
35,930,924
I am new to Python(I am using Python2.7) and Pycharm, but I need to use MySQLdb module to complete my task. I spent time to search for some guides or tips and finally I go to here but does not found MySQLdb to install. [MySQL-python](http://i.stack.imgur.com/EhTaq.png) But there is error: [Error](http://i.stack.imgur...
2016/03/11
[ "https://Stackoverflow.com/questions/35930924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5886173/" ]
I have a suggestion,if you have install MySQL database,you follow this,open pycharm and click File->Settings->Project->Project Interpreter,then select your Python interpreter and click install button (the little green plus sign),input "MySQL-Python" and click the button "install package",you will install MySQL-Python s...
If you are unable to install MySQL CLient in Pycharm, try opening the Terminal (Alt+F12) and write the command ``` pip install --only-binary :all: mysqlclient ``` This might help!
12,609,728
I need to change to reference of a function in a mach-o binary to a custom function defined in my own dylib. The process I am now following is, 1. Replacing references to older functions to the new one. e.g `_fopen` to `_mopen` using sed. 2. I open the mach-o binary in [MachOView](http://sourceforge.net/projects/mach...
2012/09/26
[ "https://Stackoverflow.com/questions/12609728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390984/" ]
Just a guess and atm I am not able to test it, but try following code: ``` <Button.Template> <ControlTemplate> <Border Background="{StaticResource BlueGradient}" CornerRadius="5"> <DockPanel> <Image x:Name="imgIcon" DockPanel.Dock="Left" Height="32" Margin="4"/> ...
Just tried your code and it works fine, with a couple of caveats. In order to get it to work I needed to drop the resouceDictionary link, as I don't have that file. Is there any chance that some content is being defined, rather than just a style/template etc? Also I note that your code has an x:Class="ShinyButton", i...
22,960,956
The python package 'isbntools' (<https://github.com/xlcnd/isbntools>) allows to retrieve bibliography information about books from online resources. In particular the script `isbn_meta [number]` retrieves information about the book with given isbn-number `[number]`. Among other it uses data from google using googleapis...
2014/04/09
[ "https://Stackoverflow.com/questions/22960956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429540/" ]
you made me some good challenge with this, but here you go: Method that return image with bottom half coloured with some colour ``` - (UIImage *)image:(UIImage *)image withBottomHalfOverlayColor:(UIColor *)color { CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height); if (UIGraphicsBeginIm...
You can use some tricks: * Use 2 different images and change the whole background. * Use one background color (light blue) and 2 images, one with the bottom half transparent
22,960,956
The python package 'isbntools' (<https://github.com/xlcnd/isbntools>) allows to retrieve bibliography information about books from online resources. In particular the script `isbn_meta [number]` retrieves information about the book with given isbn-number `[number]`. Among other it uses data from google using googleapis...
2014/04/09
[ "https://Stackoverflow.com/questions/22960956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429540/" ]
**In Swift 4.** Some Changes ``` func withBottomHalfOverlayColor(myImage: UIImage, color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: myImage.size.width, height: myImage.size.height) UIGraphicsBeginImageContextWithOptions(myImage.size, false, myImage.scale) myImage.draw(in: rect) let...
You can use some tricks: * Use 2 different images and change the whole background. * Use one background color (light blue) and 2 images, one with the bottom half transparent
22,960,956
The python package 'isbntools' (<https://github.com/xlcnd/isbntools>) allows to retrieve bibliography information about books from online resources. In particular the script `isbn_meta [number]` retrieves information about the book with given isbn-number `[number]`. Among other it uses data from google using googleapis...
2014/04/09
[ "https://Stackoverflow.com/questions/22960956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429540/" ]
you made me some good challenge with this, but here you go: Method that return image with bottom half coloured with some colour ``` - (UIImage *)image:(UIImage *)image withBottomHalfOverlayColor:(UIColor *)color { CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height); if (UIGraphicsBeginIm...
**In Swift 4.** Some Changes ``` func withBottomHalfOverlayColor(myImage: UIImage, color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: myImage.size.width, height: myImage.size.height) UIGraphicsBeginImageContextWithOptions(myImage.size, false, myImage.scale) myImage.draw(in: rect) let...
22,960,956
The python package 'isbntools' (<https://github.com/xlcnd/isbntools>) allows to retrieve bibliography information about books from online resources. In particular the script `isbn_meta [number]` retrieves information about the book with given isbn-number `[number]`. Among other it uses data from google using googleapis...
2014/04/09
[ "https://Stackoverflow.com/questions/22960956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429540/" ]
you made me some good challenge with this, but here you go: Method that return image with bottom half coloured with some colour ``` - (UIImage *)image:(UIImage *)image withBottomHalfOverlayColor:(UIColor *)color { CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height); if (UIGraphicsBeginIm...
**Swift 5 extension** ``` extension UIImage { func withBottomHalfOverlayColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, scale) draw(in: rect) let context = UIGraphics...
22,960,956
The python package 'isbntools' (<https://github.com/xlcnd/isbntools>) allows to retrieve bibliography information about books from online resources. In particular the script `isbn_meta [number]` retrieves information about the book with given isbn-number `[number]`. Among other it uses data from google using googleapis...
2014/04/09
[ "https://Stackoverflow.com/questions/22960956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/429540/" ]
**In Swift 4.** Some Changes ``` func withBottomHalfOverlayColor(myImage: UIImage, color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: myImage.size.width, height: myImage.size.height) UIGraphicsBeginImageContextWithOptions(myImage.size, false, myImage.scale) myImage.draw(in: rect) let...
**Swift 5 extension** ``` extension UIImage { func withBottomHalfOverlayColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, scale) draw(in: rect) let context = UIGraphics...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
> > `TypeError: can't use a string pattern` > `on a bytes-like object` > > > what did i do wrong?? > > > You used a string pattern on a bytes object. Use a bytes pattern instead: ``` linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>') ^ Add the b there, it makes it into ...
That worked for me in python3. Hope this helps ``` import urllib.request import re urls = ["https://google.com","https://nytimes.com","http://CNN.com"] i = 0 regex = '<title>(.+?)</title>' pattern = re.compile(regex) while i < len(urls) : htmlfile = urllib.request.urlopen(urls[i]) htmltext = htmlfile.read() ...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
Well, my version of Python doesn't have a urllib with a request attribute but if I use "urllib.urlopen(url)" I don't get back a string, I get an object. This is the type error.
That worked for me in python3. Hope this helps ``` import urllib.request import re urls = ["https://google.com","https://nytimes.com","http://CNN.com"] i = 0 regex = '<title>(.+?)</title>' pattern = re.compile(regex) while i < len(urls) : htmlfile = urllib.request.urlopen(urls[i]) htmltext = htmlfile.read() ...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
If you are running Python 2.6 then there isn't any "request" in "urllib". So the third line becomes: ``` m = urllib.urlopen(url) ``` And in version 3 you should use this: ``` links = linkregex.findall(str(msg)) ``` Because 'msg' is a bytes object and not a string as findall() expects. Or you could decode using t...
The regular expression pattern and string have to be of the same type. If you're matching a regular string, you need a string pattern. If you're matching a byte string, you need a bytes pattern. In this case *m.read()* returns a byte string, so you need a bytes pattern. In Python 3, regular strings are unicode strings...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
If you are running Python 2.6 then there isn't any "request" in "urllib". So the third line becomes: ``` m = urllib.urlopen(url) ``` And in version 3 you should use this: ``` links = linkregex.findall(str(msg)) ``` Because 'msg' is a bytes object and not a string as findall() expects. Or you could decode using t...
The url you have for Google didn't work for me, so I substituted `http://www.google.com/ig?hl=en` for it which works for me. Try this: ``` import re import urllib.request url="http://www.google.com/ig?hl=en" linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read(): link...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
> > `TypeError: can't use a string pattern` > `on a bytes-like object` > > > what did i do wrong?? > > > You used a string pattern on a bytes object. Use a bytes pattern instead: ``` linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>') ^ Add the b there, it makes it into ...
The regular expression pattern and string have to be of the same type. If you're matching a regular string, you need a string pattern. If you're matching a byte string, you need a bytes pattern. In this case *m.read()* returns a byte string, so you need a bytes pattern. In Python 3, regular strings are unicode strings...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
> > `TypeError: can't use a string pattern` > `on a bytes-like object` > > > what did i do wrong?? > > > You used a string pattern on a bytes object. Use a bytes pattern instead: ``` linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>') ^ Add the b there, it makes it into ...
The url you have for Google didn't work for me, so I substituted `http://www.google.com/ig?hl=en` for it which works for me. Try this: ``` import re import urllib.request url="http://www.google.com/ig?hl=en" linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read(): link...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
If you are running Python 2.6 then there isn't any "request" in "urllib". So the third line becomes: ``` m = urllib.urlopen(url) ``` And in version 3 you should use this: ``` links = linkregex.findall(str(msg)) ``` Because 'msg' is a bytes object and not a string as findall() expects. Or you could decode using t...
Well, my version of Python doesn't have a urllib with a request attribute but if I use "urllib.urlopen(url)" I don't get back a string, I get an object. This is the type error.
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
The url you have for Google didn't work for me, so I substituted `http://www.google.com/ig?hl=en` for it which works for me. Try this: ``` import re import urllib.request url="http://www.google.com/ig?hl=en" linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read(): link...
That worked for me in python3. Hope this helps ``` import urllib.request import re urls = ["https://google.com","https://nytimes.com","http://CNN.com"] i = 0 regex = '<title>(.+?)</title>' pattern = re.compile(regex) while i < len(urls) : htmlfile = urllib.request.urlopen(urls[i]) htmltext = htmlfile.read() ...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
> > `TypeError: can't use a string pattern` > `on a bytes-like object` > > > what did i do wrong?? > > > You used a string pattern on a bytes object. Use a bytes pattern instead: ``` linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>') ^ Add the b there, it makes it into ...
If you are running Python 2.6 then there isn't any "request" in "urllib". So the third line becomes: ``` m = urllib.urlopen(url) ``` And in version 3 you should use this: ``` links = linkregex.findall(str(msg)) ``` Because 'msg' is a bytes object and not a string as findall() expects. Or you could decode using t...
5,184,483
So, I have this code: ``` url = 'http://google.com' linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>') m = urllib.request.urlopen(url) msg = m.read() links = linkregex.findall(msg) ``` But then python returns this error: ``` links = linkregex.findall(msg) TypeError: can't use a string pattern on a bytes-like ...
2011/03/03
[ "https://Stackoverflow.com/questions/5184483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
> > `TypeError: can't use a string pattern` > `on a bytes-like object` > > > what did i do wrong?? > > > You used a string pattern on a bytes object. Use a bytes pattern instead: ``` linkregex = re.compile(b'<a\s*href=[\'|"](.*?)[\'"].*?>') ^ Add the b there, it makes it into ...
Well, my version of Python doesn't have a urllib with a request attribute but if I use "urllib.urlopen(url)" I don't get back a string, I get an object. This is the type error.
55,937,156
I am trying to read glove.6B.300d.txt file into a Pandas dataframe. (The file can be downloaded from here: <https://github.com/stanfordnlp/GloVe>) Here are the exceptions I am getting: ``` glove = pd.read_csv(filename, sep = ' ') ParserError: Error tokenizing data. C error: EOF inside string starting at line 8 glove...
2019/05/01
[ "https://Stackoverflow.com/questions/55937156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8270077/" ]
You can do it in two steps. 1. Get all record which satisfy criteria like `dimension === 2` `let resultArr = jsObjects.filter(data => { return data.dimension === 2 })` 2. Get random object from result. `var randomElement = resultArr[Math.floor(Math.random() * resultArr.length)];` ```js var arr = [{ dimension: 2, x...
You could use `Math.random()` and in the range of `0` to `length` of array. ``` let result = jsObjects.filter(data => { return data.dimension === 2 }) let randomObj = result[Math.floor(Math.random() * result.length)] ```
26,193,193
How can I change the priority of the path in sys.path in python 2.7? I know that I can use `PYTHONPATH` environment variable, but it is what I will get: ``` $ PYTHONPATH=/tmp python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more informatio...
2014/10/04
[ "https://Stackoverflow.com/questions/26193193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470911/" ]
As you may know, [`sys.path` is initialized from](https://docs.python.org/2/tutorial/modules.html#the-module-search-path): * the current directory * your `PYTHONPATH` * an installation-dependent default However unfortunately that is only part of the story: `setuptools` creates [`easy-install.pth`](https://pythonhoste...
We encountered an almost identical situation and wanted to expand upon @kynan's response which is spot-on. In the case where you have such an `easy-install.pth` that you want to overcome, but which you cannot modify it (say you are a user with no root/admin access), you can do the following: * Set up an [alternate pyt...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
You can use a [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) to create the inner dicts automatically when needed: ``` from collections import defaultdict data = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4),...
Yes, with something like this. ```py my_query = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) ) dict_query = {} for key1, key2, value in my_query: if key1 not in dict_query: dict_query[key1] = {} dict_query[key1][key2] = va...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
Yes, with something like this. ```py my_query = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) ) dict_query = {} for key1, key2, value in my_query: if key1 not in dict_query: dict_query[key1] = {} dict_query[key1][key2] = va...
Alternatively to `defaultdict` you can use the dictionary method `setdefault()`: ``` dct = {} for k1, k2, v2 in c.fetchall(): v1 = dct.setdefault(k1, {}) v1[k2] = v2 ``` or ``` for k1, k2, v2 in c.fetchall(): dct.setdefault(k1, {})[k2] = v2 ``` Result: ``` {'Griffin': {'John': 7, 'James': 23, 'Mary'...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
Yes, with something like this. ```py my_query = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) ) dict_query = {} for key1, key2, value in my_query: if key1 not in dict_query: dict_query[key1] = {} dict_query[key1][key2] = va...
You can solve it holding on `itertools.groupby` and `functools.itemgetter`. ```py from operator import itemgetter from itertools import groupby result = { name: dict(v for _, v in values) for name, values in groupby(((x[0], x[1:]) for x in c.fetchall()), itemgetter(0))} print(result) # {'Griffin': {'John': 7, 'James'...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
You can use a [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) to create the inner dicts automatically when needed: ``` from collections import defaultdict data = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4),...
Coming with *dict comprehension* though with `itertools.groupby` magic: ``` from itertools import groupby counts = {k: dict(_[1:] for _ in g) for k, g in groupby(c.fetchall(), key=lambda t: t[0])} print(counts) ``` The output: ``` {'Griffin': {'John': 7, 'James': 23, 'Mary': 30}, 'Griffith': {'John': 4, 'Catherine...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
You can use a [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) to create the inner dicts automatically when needed: ``` from collections import defaultdict data = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4),...
Alternatively to `defaultdict` you can use the dictionary method `setdefault()`: ``` dct = {} for k1, k2, v2 in c.fetchall(): v1 = dct.setdefault(k1, {}) v1[k2] = v2 ``` or ``` for k1, k2, v2 in c.fetchall(): dct.setdefault(k1, {})[k2] = v2 ``` Result: ``` {'Griffin': {'John': 7, 'James': 23, 'Mary'...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
You can use a [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) to create the inner dicts automatically when needed: ``` from collections import defaultdict data = (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4),...
You can solve it holding on `itertools.groupby` and `functools.itemgetter`. ```py from operator import itemgetter from itertools import groupby result = { name: dict(v for _, v in values) for name, values in groupby(((x[0], x[1:]) for x in c.fetchall()), itemgetter(0))} print(result) # {'Griffin': {'John': 7, 'James'...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
Coming with *dict comprehension* though with `itertools.groupby` magic: ``` from itertools import groupby counts = {k: dict(_[1:] for _ in g) for k, g in groupby(c.fetchall(), key=lambda t: t[0])} print(counts) ``` The output: ``` {'Griffin': {'John': 7, 'James': 23, 'Mary': 30}, 'Griffith': {'John': 4, 'Catherine...
Alternatively to `defaultdict` you can use the dictionary method `setdefault()`: ``` dct = {} for k1, k2, v2 in c.fetchall(): v1 = dct.setdefault(k1, {}) v1[k2] = v2 ``` or ``` for k1, k2, v2 in c.fetchall(): dct.setdefault(k1, {})[k2] = v2 ``` Result: ``` {'Griffin': {'John': 7, 'James': 23, 'Mary'...
58,466,616
I am executing the following sqlite command: ``` c.execute("SELECT surname,forename,count(*) from census_data group by surname, forename") ``` so that c.fetchall() is as follows: ``` (('Griffin','John', 7), ('Griffin','James', 23), ('Griffin','Mary',30), ('Griffith', 'John', 4), ('Griffith','Catherine', 5) )...
2019/10/19
[ "https://Stackoverflow.com/questions/58466616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/607846/" ]
Coming with *dict comprehension* though with `itertools.groupby` magic: ``` from itertools import groupby counts = {k: dict(_[1:] for _ in g) for k, g in groupby(c.fetchall(), key=lambda t: t[0])} print(counts) ``` The output: ``` {'Griffin': {'John': 7, 'James': 23, 'Mary': 30}, 'Griffith': {'John': 4, 'Catherine...
You can solve it holding on `itertools.groupby` and `functools.itemgetter`. ```py from operator import itemgetter from itertools import groupby result = { name: dict(v for _, v in values) for name, values in groupby(((x[0], x[1:]) for x in c.fetchall()), itemgetter(0))} print(result) # {'Griffin': {'John': 7, 'James'...
66,912,406
Been following a tutorial on udemy for python, and atm im suppose to get a django app deployed. Since I already had a vps, I didnt go with the solution on the tutorial using google cloud, so tried to configure the app on my vps, which is also running plesk. Followed the tutorial at <https://www.plesk.com/blog/tag/djan...
2021/04/01
[ "https://Stackoverflow.com/questions/66912406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6291059/" ]
The '.no-content' has display: none which instantly removes the element and the animation does not take place I just removed that and it worked just fine. I added the other CSS to fix the position of the div 'I assumed you want it like this' ```js const App = () => { const [opened, setOpened] = React.useState(fal...
You dont need animation for that transition is much cleaner ```js const App = () => { const [opened, setOpened] = React.useState(false) return ( < div > < button className = 'btn' onClick = { () => setOpened(!opened) } > { opened ? 'Close' : 'Open' } < /button> < div style =...
63,510,765
I am following with Datacamp's tutorial on using convolutional autoencoders for classification [here](https://www.datacamp.com/community/tutorials/autoencoder-classifier-python). I understand in the tutorial that we only need the autoencoder's head (i.e. the encoder part) stacked to a fully-connected layer to do the cl...
2020/08/20
[ "https://Stackoverflow.com/questions/63510765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You are trying to render an object, and when you convert Javascript objects to string it will convert to "`[object Object]`". I think you are misunderstanding what the "name" prop of the input field should do in this context, you don't actually need that. A better way of writing your handleChange function would be: ...
You're using invalid html: ``` <input type="text-area" /> ``` [Textarea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element is to be: ``` <textarea /> ``` --- Okay, I found the issue with the userReview state. You should use: ``` <textarea onChange...> {userReview.userReview} /* name ...
2,893,193
I'd like to tell you what I've tried and then I'd really welcome any comments you can provide on how I can get PortAudio and PyAudio setup correctly! I've tried installing the stable and svn releases of PortAudio from [their website](http://www.portaudio.com/download.html) for my Core 2 Duo MacBook Pro running Snow L...
2010/05/23
[ "https://Stackoverflow.com/questions/2893193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51532/" ]
Thanks to PyAudio's author's speedy response to my inquiries, I now have a nicely installed copy. His directions are posted below for anyone who has similar issues. > > Hi Michael, > > > Try this: > > > 1) Make sure your directory layout is > like: > > > ./foo/pyaudio/portaudio-v19/ ./foo/pyaudio/ > > > 2) B...
I'm on Mac 10.5.8 Intel Core 2 duo and hitting the same issue. The directory layout you need is ``` ./foo/pyaudio/portaudio-v19/ ./foo/pyaudio ``` The reason is setup.py has the following: portaudio\_path = os.environ.get("PORTAUDIO\_PATH", "./portaudio-v19") alternatively, you should be able to set PORTAUDIO\_PATH...
70,872,795
i am new to c++ and i know so much more python than c++ and i have to change a code from c++ to python, in the code to change i found this sentence: ``` p->arity = std::stoi(x, nullptr, 10); ``` i think for sake of simplicity we can use ``` p->arity = x; /* or some whit pointers im really noob on c++ but i think ...
2022/01/27
[ "https://Stackoverflow.com/questions/70872795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11579387/" ]
The API keys are only available in the deployed function, not in the react app. You can call a function from your react app which then calls the MailChimp API. This keeps you API key out of the client side code which keeps it secure. As the documentation says, you set the API keys with the CLI in the terminal ``` fir...
Firebase can use Google Cloud Platform Services, you can integrate [GCP Secret Manager](https://cloud.google.com/secret-manager) on your functions. Google Secret Manager is a fully-managed, secure, and convenient storage system for such secrets. Developers have historically leveraged environment variables or the files...
45,224,882
As I understand, the current java.net.URL handshake (for a GSS/Kerberos authentication mode) always entails a 401 as a first leg operation, which is kind of inefficient if we know the client and server are going to use GSS/Kerberos, right? Does anyone know if preemptive authentication (where you can present the token u...
2017/07/20
[ "https://Stackoverflow.com/questions/45224882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874076/" ]
I have faced the same issue and came to the same conclusion as you - preemptive SPNEGO authentication is not supported neither in Oracle JRE HttpUrlConnection nor in Apache HTTP Components. I haven't checked other HTTP clients but almost sure that it should be the same. I started working on an alternative Spnego clien...
After much investigation, it looks like preemptive kerberos authentication is not available in the default Hotspot java implementation. The http-components from Apache is also not able to help with this. However, the default implementation does have the ability to only send headers when the payload is potentially larg...
45,224,882
As I understand, the current java.net.URL handshake (for a GSS/Kerberos authentication mode) always entails a 401 as a first leg operation, which is kind of inefficient if we know the client and server are going to use GSS/Kerberos, right? Does anyone know if preemptive authentication (where you can present the token u...
2017/07/20
[ "https://Stackoverflow.com/questions/45224882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874076/" ]
After much investigation, it looks like preemptive kerberos authentication is not available in the default Hotspot java implementation. The http-components from Apache is also not able to help with this. However, the default implementation does have the ability to only send headers when the payload is potentially larg...
The following example shows how you can do preemptive spnego login that uses a custom entry in the login.conf. This completely bypasses the AuthScheme stuff and does all the work of generating the "authorization" header. ``` import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpRespo...
45,224,882
As I understand, the current java.net.URL handshake (for a GSS/Kerberos authentication mode) always entails a 401 as a first leg operation, which is kind of inefficient if we know the client and server are going to use GSS/Kerberos, right? Does anyone know if preemptive authentication (where you can present the token u...
2017/07/20
[ "https://Stackoverflow.com/questions/45224882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874076/" ]
I have faced the same issue and came to the same conclusion as you - preemptive SPNEGO authentication is not supported neither in Oracle JRE HttpUrlConnection nor in Apache HTTP Components. I haven't checked other HTTP clients but almost sure that it should be the same. I started working on an alternative Spnego clien...
The following example shows how you can do preemptive spnego login that uses a custom entry in the login.conf. This completely bypasses the AuthScheme stuff and does all the work of generating the "authorization" header. ``` import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpRespo...
52,216,312
Data: ``` {"Survived":{"0":0,"1":1,"2":1,"3":1,"4":0,"5":0,"6":0,"7":0,"8":1,"9":1,"10":1,"11":1,"12":0,"13":0,"14":0,"15":1,"16":0,"17":1,"18":0,"19":1,"20":0,"21":1,"22":1,"23":1,"24":0,"25":1,"26":0,"27":0,"28":1,"29":0,"30":0,"31":1,"32":1,"33":0,"34":0,"35":0,"36":1,"37":0,"38":0,"39":1,"40":0,"41":0,"42":0,"43":...
2018/09/07
[ "https://Stackoverflow.com/questions/52216312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7170271/" ]
Try this ``` @Override public void onValidationFailed(View failedView, Rule<?> failedRule) { String message = failedRule.getFailureMessage(); if (failedView instanceof EditText) { failedView.requestFocus(); if(!TextUtils.isEmpty(message){ ((EditText) failedView).setError(message); ...
> > I found the problem : > > > ``` android:theme="@style/TextLabel" ``` > > Had to create a theme first and than a style and use it like : > > > ``` <style name="TextLabel" parent="BellicTheme"> ``` > > Thanks everyone > > >
44,550,192
Suppose I have the following dict... ``` sample = { 'a' : 100, 'b' : 3, 'e' : 42, 'c' : 250, 'f' : 42, 'd' : 42, } ``` I want to sort this dict with the highest order sort being by value and the lower order sort being by key. The key-value pairs of the result would be this ... ``` ( ('b', 3), ('d', 42)...
2017/06/14
[ "https://Stackoverflow.com/questions/44550192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1800838/" ]
You can define a lambda that uses both the value and key. ``` sorted(sample.items(), key=lambda x: (x[1], x[0])) ```
You can use the operator module: ``` import operator sample = { 'a' : 100, 'b' : 3, 'e' : 42, 'c' : 250, 'f' : 42, 'd' : 42, } sorted_by_value = tuple(sorted(sample.items(), key=operator.itemgetter(1))) sorted_by_key = tuple(sorted(sample.items(), key=operator.itemgetter(0))) ``` sorted\_by\_value: ``` (('b...
37,000,231
I have a Pandas DataFrame as follow: ```python In [28]: df = pd.DataFrame({'A':['CA', 'FO', 'CAP', 'CP'], 'B':['Name1', 'Name2', 'Name3', 'Name4'], 'C':['One', 'Two', 'Other', 'Some']}) In [29]: df Out[29]: A B C 0 CA Name1 One 1 FO Name2 ...
2016/05/03
[ "https://Stackoverflow.com/questions/37000231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3908401/" ]
You explicitly set the input's ID as "TextBox" but you're trying to retrieve it as `<%= TextBox.ClientID %>`, use "TextBox" as the ID (and better, give a more meaningful name to the ID). ClientId is used for ASP .net controls which have it's ID autogenerated by the ASP runtime.
Turns out I was referencing the wrong control. Referencing the correct control in the script solved my problem. The rest of the code is totally usable. Referencing a control with `#` in the call to the ID is required for jQuery functions but not plain Javascript. `<%= TextBox.ClientID %>` will work even for HTML input...
10,414,210
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
2012/05/02
[ "https://Stackoverflow.com/questions/10414210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552671/" ]
> > [`next(iterator[, default])`](http://docs.python.org/2/library/functions.html#next) > > > Retrieve the next item from the *iterator* by calling its `next()``(__next__()` in python 3) method. If *default* is given, it is returned if the iterator is exhausted, otherwise `StopIteration` is raised. > > > You get...
Apart from the obvious additional functionality, it also looks better when used together with generator expressions. Compare ``` (x for x in lst if x > 2).next() ``` to ``` next(x for x in lst if x > 2) ``` The latter is a lot more consistent with the rest of Python's style, IMHO.
10,414,210
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
2012/05/02
[ "https://Stackoverflow.com/questions/10414210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552671/" ]
[PEP 3114](http://www.python.org/dev/peps/pep-3114/) describes this change. An excerpt about the motivation: > > This PEP proposes that the `next` method be renamed to `__next__`, > consistent with all the other protocols in Python in which a method is > implicitly called as part of a language-level protocol, and t...
> > [`next(iterator[, default])`](http://docs.python.org/2/library/functions.html#next) > > > Retrieve the next item from the *iterator* by calling its `next()``(__next__()` in python 3) method. If *default* is given, it is returned if the iterator is exhausted, otherwise `StopIteration` is raised. > > > You get...
10,414,210
Python 2.6 introduced a `next` function. Why was this necessary? One could always type `obj.next()` instead of `next(obj)`. Is the latter more `pythonic`?
2012/05/02
[ "https://Stackoverflow.com/questions/10414210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552671/" ]
[PEP 3114](http://www.python.org/dev/peps/pep-3114/) describes this change. An excerpt about the motivation: > > This PEP proposes that the `next` method be renamed to `__next__`, > consistent with all the other protocols in Python in which a method is > implicitly called as part of a language-level protocol, and t...
Apart from the obvious additional functionality, it also looks better when used together with generator expressions. Compare ``` (x for x in lst if x > 2).next() ``` to ``` next(x for x in lst if x > 2) ``` The latter is a lot more consistent with the rest of Python's style, IMHO.
28,242,398
I am trying to create an algorithm in Python 2.7.9 which can be viewed below: ![enter image description here](https://i.stack.imgur.com/4qsGy.gif) This equates to: `10/3 (-510 + sqrt(15) * sqrt(-44879 + 1000 * y))` When I try to solve it in python with the following code: ``` from __future__ import division import...
2015/01/30
[ "https://Stackoverflow.com/questions/28242398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241308/" ]
You are missing the multiplication operator below: ``` x = "%0.2f" % (10/3 (-510 + sqrt(15) * sqrt(-44879 + 1000 * y))) ^ Need to add '*' ```
Where is the multiplication operator? ``` x = "%0.2f" % (10/3 * (-510 + sqrt(15) * sqrt(-44879 + 1000 * y))) ``` Tip Whenever you get `TypeError: 'int' object is not callable`, it means that you have something like an integer followed immediately by a brace. Check out for that, Debugging will be a piece of cake.
28,064,563
I am using distutils (setup.py) to create rpm-packages from my python projects. Now, one of my projects which had a very specific task (say png-creation) is moved to a more general project (image-toolkit). 1. Is there a way to tell the user that the old package (png-creation) is obsolete when he/she installs the new p...
2015/01/21
[ "https://Stackoverflow.com/questions/28064563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4034527/" ]
ARI uses a subscription based model for events. Quoting from the documentation on the [wiki](https://wiki.asterisk.org/wiki/display/AST/Introduction+to+ARI+and+Channels): > > Resources in Asterisk do not, by default, send events about themselves to a connected ARI application. In order to get events about resources, ...
For more clarity regarding what Matt Jordan has already provided, here's an example of doing what he suggests with [ari-py](https://github.com/asterisk/ari-py): ``` import ari import logging logging.basicConfig(level=logging.ERROR) client = ari.connect('http://localhost:8088', 'username', 'password') postRequest=clie...
28,064,563
I am using distutils (setup.py) to create rpm-packages from my python projects. Now, one of my projects which had a very specific task (say png-creation) is moved to a more general project (image-toolkit). 1. Is there a way to tell the user that the old package (png-creation) is obsolete when he/she installs the new p...
2015/01/21
[ "https://Stackoverflow.com/questions/28064563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4034527/" ]
ARI uses a subscription based model for events. Quoting from the documentation on the [wiki](https://wiki.asterisk.org/wiki/display/AST/Introduction+to+ARI+and+Channels): > > Resources in Asterisk do not, by default, send events about themselves to a connected ARI application. In order to get events about resources, ...
ws://(host):8088/ari/events?app=dialer&subscibeAll=true Adding SubscribeAll=true make what you want =)
28,064,563
I am using distutils (setup.py) to create rpm-packages from my python projects. Now, one of my projects which had a very specific task (say png-creation) is moved to a more general project (image-toolkit). 1. Is there a way to tell the user that the old package (png-creation) is obsolete when he/she installs the new p...
2015/01/21
[ "https://Stackoverflow.com/questions/28064563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4034527/" ]
ARI uses a subscription based model for events. Quoting from the documentation on the [wiki](https://wiki.asterisk.org/wiki/display/AST/Introduction+to+ARI+and+Channels): > > Resources in Asterisk do not, by default, send events about themselves to a connected ARI application. In order to get events about resources, ...
May be help someone: Subscribe to all events on channels, bridge and endpoints ``` POST http://localhost:8088/ari/applications/appName/subscription?api_key=user:password&eventSource=channel:,bridge:,endpoint: ``` Unsubscribe ``` DELETE http://localhost:8088/ari/applications/appName/subscription?api_key=user:passwo...
28,064,563
I am using distutils (setup.py) to create rpm-packages from my python projects. Now, one of my projects which had a very specific task (say png-creation) is moved to a more general project (image-toolkit). 1. Is there a way to tell the user that the old package (png-creation) is obsolete when he/she installs the new p...
2015/01/21
[ "https://Stackoverflow.com/questions/28064563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4034527/" ]
ws://(host):8088/ari/events?app=dialer&subscibeAll=true Adding SubscribeAll=true make what you want =)
For more clarity regarding what Matt Jordan has already provided, here's an example of doing what he suggests with [ari-py](https://github.com/asterisk/ari-py): ``` import ari import logging logging.basicConfig(level=logging.ERROR) client = ari.connect('http://localhost:8088', 'username', 'password') postRequest=clie...
28,064,563
I am using distutils (setup.py) to create rpm-packages from my python projects. Now, one of my projects which had a very specific task (say png-creation) is moved to a more general project (image-toolkit). 1. Is there a way to tell the user that the old package (png-creation) is obsolete when he/she installs the new p...
2015/01/21
[ "https://Stackoverflow.com/questions/28064563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4034527/" ]
ws://(host):8088/ari/events?app=dialer&subscibeAll=true Adding SubscribeAll=true make what you want =)
May be help someone: Subscribe to all events on channels, bridge and endpoints ``` POST http://localhost:8088/ari/applications/appName/subscription?api_key=user:password&eventSource=channel:,bridge:,endpoint: ``` Unsubscribe ``` DELETE http://localhost:8088/ari/applications/appName/subscription?api_key=user:passwo...
40,282,812
I have a data in mongoDB, I want to retrieve all the values of a key `"category"` using python code. I have tried several ways but in every case I have to give the "value" to retrieve. Any suggestions would be appreciated. ``` { id = "my_id1" tags: [tag1, tag2, tag3], category: "movie", }, { id = "my_id2" ...
2016/10/27
[ "https://Stackoverflow.com/questions/40282812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6858122/" ]
This Should Work ``` db.test.find({},{"category":1}); ```
Pymongo's `distinct()` method returns a list of all values associated with a key across all documents in a collection. The following code: ``` db.collection.distinct('category') ``` should return the following list: ``` ['movie', 'tv', 'movie'] ```
62,657,673
alright so I've been working on some program and I need to send emails from my gmail account.. so I wrote a code (irrelevent, it works) however the mails not send until I approve the captcha.. [captcha url](https://accounts.google.com/b/0/DisplayUnlockCaptcha) and then this solution only work once, What should I do ...
2020/06/30
[ "https://Stackoverflow.com/questions/62657673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13046336/" ]
``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoroutineController : MonoBehaviour { static CoroutineController _singleton; static Dictionary<string,IEnumerator> _routines = new Dictionary<string,IEnumerator>(100); [RuntimeInitializeOnLoadMethod( RuntimeIni...
My solution to starting the Coroutines from places that can't do this is making a Singleton CoroutineManager. I then use this CoroutineManager to invoke these Coroutines from places like ScriptableObjects. You can also use it to cache WaitForEndOfFrame or WaitForFixedUpdate so you don't need to create new ones every ti...
62,657,673
alright so I've been working on some program and I need to send emails from my gmail account.. so I wrote a code (irrelevent, it works) however the mails not send until I approve the captcha.. [captcha url](https://accounts.google.com/b/0/DisplayUnlockCaptcha) and then this solution only work once, What should I do ...
2020/06/30
[ "https://Stackoverflow.com/questions/62657673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13046336/" ]
``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoroutineController : MonoBehaviour { static CoroutineController _singleton; static Dictionary<string,IEnumerator> _routines = new Dictionary<string,IEnumerator>(100); [RuntimeInitializeOnLoadMethod( RuntimeIni...
To better understand the concept look at this absolutely bare-minimum version of CoroutineController class. It's just a field and a method, that's all: ``` using UnityEngine; public class CoroutinePawn : MonoBehaviour { public static CoroutinePawn Instance { get; private set; } [RuntimeInitializeOnLoadMethod(...
62,657,673
alright so I've been working on some program and I need to send emails from my gmail account.. so I wrote a code (irrelevent, it works) however the mails not send until I approve the captcha.. [captcha url](https://accounts.google.com/b/0/DisplayUnlockCaptcha) and then this solution only work once, What should I do ...
2020/06/30
[ "https://Stackoverflow.com/questions/62657673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13046336/" ]
My solution to starting the Coroutines from places that can't do this is making a Singleton CoroutineManager. I then use this CoroutineManager to invoke these Coroutines from places like ScriptableObjects. You can also use it to cache WaitForEndOfFrame or WaitForFixedUpdate so you don't need to create new ones every ti...
To better understand the concept look at this absolutely bare-minimum version of CoroutineController class. It's just a field and a method, that's all: ``` using UnityEngine; public class CoroutinePawn : MonoBehaviour { public static CoroutinePawn Instance { get; private set; } [RuntimeInitializeOnLoadMethod(...
53,058,052
I am trying to create executable python file using pyinstaller, but while loading hooks, it shows error like this, ``` 24021 INFO: Removing import of PySide from module PIL.ImageQt 24021 INFO: Loading module hook "hook-pytz.py"... 24506 INFO: Loading module hook "hook-encodings.py"... 24600 INFO: Loading module hook...
2018/10/30
[ "https://Stackoverflow.com/questions/53058052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9921123/" ]
I have been working on this issue for a few days not and don't have hair left. For some reason nltk and pyinstaller do not work well together. So my first solution to this issue is to use something other than nltk if it is possible to code the solution without nltk. If you must use NLTK, I solved this by forcing the...
I solved the problems editing the pyinstaller nltk-hook. After much research, I decided to go it alone in the code structure. I solved my problem by commenting on the lines: `datas=[]` `'''for p in nltk.data.path: datas.append((p, "nltk_data"))'''` `hiddenimports = ["nltk.chunk.named_entity"]` What's more, you need...
53,058,052
I am trying to create executable python file using pyinstaller, but while loading hooks, it shows error like this, ``` 24021 INFO: Removing import of PySide from module PIL.ImageQt 24021 INFO: Loading module hook "hook-pytz.py"... 24506 INFO: Loading module hook "hook-encodings.py"... 24600 INFO: Loading module hook...
2018/10/30
[ "https://Stackoverflow.com/questions/53058052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9921123/" ]
[This answer](https://stackoverflow.com/a/54760437/8379443) worked for me... it modifies the code in `hook-nltk.py` to only include the path if it exists. `hook-nltk.py` can be found in your PyInstaller location within the hooks folder (something like <'path-to-python-installation'>\Lib\site-packages\PyInstaller\hooks...
I solved the problems editing the pyinstaller nltk-hook. After much research, I decided to go it alone in the code structure. I solved my problem by commenting on the lines: `datas=[]` `'''for p in nltk.data.path: datas.append((p, "nltk_data"))'''` `hiddenimports = ["nltk.chunk.named_entity"]` What's more, you need...
53,058,052
I am trying to create executable python file using pyinstaller, but while loading hooks, it shows error like this, ``` 24021 INFO: Removing import of PySide from module PIL.ImageQt 24021 INFO: Loading module hook "hook-pytz.py"... 24506 INFO: Loading module hook "hook-encodings.py"... 24600 INFO: Loading module hook...
2018/10/30
[ "https://Stackoverflow.com/questions/53058052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9921123/" ]
[This answer](https://stackoverflow.com/a/54760437/8379443) worked for me... it modifies the code in `hook-nltk.py` to only include the path if it exists. `hook-nltk.py` can be found in your PyInstaller location within the hooks folder (something like <'path-to-python-installation'>\Lib\site-packages\PyInstaller\hooks...
I have been working on this issue for a few days not and don't have hair left. For some reason nltk and pyinstaller do not work well together. So my first solution to this issue is to use something other than nltk if it is possible to code the solution without nltk. If you must use NLTK, I solved this by forcing the...
28,616,942
I am trying to upload video files to a Bucket in S3 server from android app using a signed URLs which is generated from server side (coded in python) application. We are making a PUT request to the signed URL but we are getting > > `connection reset by peer exception`. > > > But when I try the same URL on the PO...
2015/02/19
[ "https://Stackoverflow.com/questions/28616942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2562861/" ]
Done this using [Retrofit](http://square.github.io/retrofit/) HTTP client library,it successfully uploaded file to Amazon s3 server. code: ``` public interface UploadService { String BASE_URL = "https://bucket.s3.amazonaws.com/folder"; /** * @param url :signed s3 url string after 'BASE_URL'. * @...
Use dynamic URL instead of providing the base URL, use @Url instead of @Path and pass a complete URI, encode= false is by default Eg: `@Multipart @PUT @Headers("x-amz-acl:public-read") Call<Void> uploadFile(@Url String url, @Header("Content-Type") String contentType, @Part MultipartBody.Part part);`
41,363,888
I could send mail using the following code ``` E:\Python\django-test\LYYDownloaderServer>python manage.py shell Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.c...
2016/12/28
[ "https://Stackoverflow.com/questions/41363888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485853/" ]
First, it doesn't matter if you were able to send the mail using the console, but if you received the mail. I assume you did. Second, it's best to try with exactly the same email address in the console as the one set in the `ADMINS`, just to be sure. Finally, the sender address might also matter. The default is "root...
Djano sends admin emails on error using logging system. As I can see from your `views.py` you are changing logging settings. This can be the cause of the problem as you cleared that django admin handler `mail_admins`. For more information check [django documentation](https://docs.djangoproject.com/en/1.10/topics/logg...
41,363,888
I could send mail using the following code ``` E:\Python\django-test\LYYDownloaderServer>python manage.py shell Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.c...
2016/12/28
[ "https://Stackoverflow.com/questions/41363888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485853/" ]
First, it doesn't matter if you were able to send the mail using the console, but if you received the mail. I assume you did. Second, it's best to try with exactly the same email address in the console as the one set in the `ADMINS`, just to be sure. Finally, the sender address might also matter. The default is "root...
The [Django doc](https://docs.djangoproject.com/en/1.10/howto/error-reporting/#server-errors) says: In order to send email, EMAIL\_HOST, EMAIL\_HOST\_USER and EMAIL\_HOST\_PASSWORD are at the very least needed, but as I tested, we should also specify SERVER\_EMAIL, and only when SERVER\_EMAIL is equal to EMAIL\_HOST\_U...
70,453,702
I am a trader, I want to use the XTB API to access the account,T try to learn Python I found XTBApi I install it Windows (python3 -m venv env) but when I enter the command (. \ venv \ Scripts \ activate) it doesn't work: The specified path could not be found. What do I have to do? Thanks How can i convert linux script...
2021/12/22
[ "https://Stackoverflow.com/questions/70453702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17330089/" ]
`stringr` is fine, but here a very good solution exists in base R. ``` x <- head(state.name) x # [1] "Alabama" "Alaska" "Arizona" "Arkansas" "California" "Colorado" substring(x, 5) # [1] "ama" "ka" "ona" "nsas" "fornia" "rado" ```
You may find this useful to rename columns. ```r library(dplyr) library(stringr) df %>% rename_with(str_sub, start = 5L) ``` If you don't want to do it for all of the columns, you can use the `.cols` argument. ```r # like this iris %>% rename_with(str_sub, start = 5L, .cols = starts_with("Sepal")) # or this...
70,453,702
I am a trader, I want to use the XTB API to access the account,T try to learn Python I found XTBApi I install it Windows (python3 -m venv env) but when I enter the command (. \ venv \ Scripts \ activate) it doesn't work: The specified path could not be found. What do I have to do? Thanks How can i convert linux script...
2021/12/22
[ "https://Stackoverflow.com/questions/70453702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17330089/" ]
`stringr` is fine, but here a very good solution exists in base R. ``` x <- head(state.name) x # [1] "Alabama" "Alaska" "Arizona" "Arkansas" "California" "Colorado" substring(x, 5) # [1] "ama" "ka" "ona" "nsas" "fornia" "rado" ```
This is not the best way but should be here for offering an alternative with `Base R`. ``` substr(state.name,5,nchar(state.name)) # [1] "ama" "ka" "ona" "nsas" "fornia" "rado" "ecticut" ```
70,453,702
I am a trader, I want to use the XTB API to access the account,T try to learn Python I found XTBApi I install it Windows (python3 -m venv env) but when I enter the command (. \ venv \ Scripts \ activate) it doesn't work: The specified path could not be found. What do I have to do? Thanks How can i convert linux script...
2021/12/22
[ "https://Stackoverflow.com/questions/70453702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17330089/" ]
You may find this useful to rename columns. ```r library(dplyr) library(stringr) df %>% rename_with(str_sub, start = 5L) ``` If you don't want to do it for all of the columns, you can use the `.cols` argument. ```r # like this iris %>% rename_with(str_sub, start = 5L, .cols = starts_with("Sepal")) # or this...
This is not the best way but should be here for offering an alternative with `Base R`. ``` substr(state.name,5,nchar(state.name)) # [1] "ama" "ka" "ona" "nsas" "fornia" "rado" "ecticut" ```
36,730,812
I'm newbie for raspberry pi and python coding. I'm working on a school project. I've already looked for some tutorials and examples but maybe I'm missing something. I want to build a web server based gpio controller. I'm using flask for this. For going into this, I've started with this example. Just turning on and off ...
2016/04/19
[ "https://Stackoverflow.com/questions/36730812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6227347/" ]
Firstly it helps to run it in debug mode: `app.run(debug=True)` This will help you track down any errors which are being suppressed. Next have a look at the line where you are building the title string: `'title' : 'Status of Pin' + status` If you enable the debug mode, then you should see something saying that an ...
Your server was probably throwing an exception when trying to create your dictionary, therefore the templateData value was being sent as an empty value. Notice in this example, the TypeError which is thrown when trying to concatenate 2 variables of different type. Hence, wrapping your variable in the str(status) will...
53,480,646
I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do; Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the curre...
2018/11/26
[ "https://Stackoverflow.com/questions/53480646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8118659/" ]
Using jquery method as follows: ``` $("button[name^=t]").click(function(){ //process } ``` The above method will be invoked whenever a `button` whose name starts with `'t'` is clicked.
Run this snippet. You can read text using prev(). ```js $('.btn').on('click', function(){ alert($( this ).prev().val()); }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="post-comment"> <textarea class="comment-box" name="" id="" cols="8...
53,480,646
I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do; Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the curre...
2018/11/26
[ "https://Stackoverflow.com/questions/53480646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8118659/" ]
No need to add any identifier, Just grab the data of the previous element using Jquery using the following code. ``` $(document).on('click','.btnComment',function(){ var CommentText = $(this).prev().val(); alert(CommentText); }); ``` Check out the working fiddle [here](http://jsfiddle.net/goku...
Run this snippet. You can read text using prev(). ```js $('.btn').on('click', function(){ alert($( this ).prev().val()); }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="post-comment"> <textarea class="comment-box" name="" id="" cols="8...
53,480,646
I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do; Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the curre...
2018/11/26
[ "https://Stackoverflow.com/questions/53480646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8118659/" ]
Here how you can do it without jquery: ```js const buttons = document.querySelectorAll('.btn') buttons.forEach(button => button.addEventListener('click', (event) => { // init listeners for buttons const value = event.target.parentNode // get to the textarea through the parent (div) .querySelector('textare...
Run this snippet. You can read text using prev(). ```js $('.btn').on('click', function(){ alert($( this ).prev().val()); }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="post-comment"> <textarea class="comment-box" name="" id="" cols="8...
50,397,060
I have dataframe like this: ``` >>df L1 L0 desc_L0 4956 10 Hi 1509 nan I am 1510 20 Here 1511 nan where r u ? ``` I want to insert a new column `desc_L1` when value for `L0` is null and same time move respective `desc_L0` value to `desc_L1`. Desired output:...
2018/05/17
[ "https://Stackoverflow.com/questions/50397060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7566673/" ]
First copy your series: ``` df['desc_L1'] = df['desc_L0'] ``` Then use a mask to update the two series: ``` mask = df['L1'].isnull() df.loc[~mask, 'desc_L1'] = np.nan df.loc[mask, 'desc_L0'] = np.nan ```
You can try so: ``` df['desc_L1'] = df['desc_L0'] df['desc_L1'] = np.where(df['L0'].isna(), df['desc_L0'], np.NaN) df['desc_L0'] = np.where(df['L0'].isna(), np.NaN, df['desc_L0']) ``` Input: ``` L0 desc_L0 0 10.0 hi 1 NaN I am 2 20.0 Here 3 NaN where are u? ``` Outpu...
49,172,957
I'm learning python, I want to check if the second largest number is duplicated in a list. I've tried several ways, but I couldn't. Also, I have searched on google for this issue, I have got several answers to get/print 2nd largest number from a list but I couldn't find any answer to check if the 2nd largest number is ...
2018/03/08
[ "https://Stackoverflow.com/questions/49172957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6544266/" ]
Here is a *1-liner*: ``` >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(sorted(list1)[-2]) > 1 True ``` or using [heapq](https://docs.python.org/3/library/heapq.html#heapq.nlargest) ``` >>> import heapq >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(heapq.nlargest(2, list1)[1]) > 1 True ```
This is a simple algorithm: 1. Makes values unique 2. Sort your list by max value 3. Takes the second element 4. Check how many occurences of this elemnt exists in list Code: ``` list1 = [5, 6, 9, 9, 11] list2 = [8, 9, 13, 14, 14] def check(data): # 1. Make data unique unique = list(set(data)) # 2. Sort...
49,172,957
I'm learning python, I want to check if the second largest number is duplicated in a list. I've tried several ways, but I couldn't. Also, I have searched on google for this issue, I have got several answers to get/print 2nd largest number from a list but I couldn't find any answer to check if the 2nd largest number is ...
2018/03/08
[ "https://Stackoverflow.com/questions/49172957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6544266/" ]
Here is a *1-liner*: ``` >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(sorted(list1)[-2]) > 1 True ``` or using [heapq](https://docs.python.org/3/library/heapq.html#heapq.nlargest) ``` >>> import heapq >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(heapq.nlargest(2, list1)[1]) > 1 True ```
`collections.Counter` with `sorted` offers one solution: ``` from collections import Counter lst1 = [5, 6, 9, 9, 11] lst2 = [8, 9, 13, 14, 14] res1 = sorted(Counter(lst1).items(), key=lambda x: -x[0])[1] # (9, 2) res2 = sorted(Counter(lst2).items(), key=lambda x: -x[0])[1] # (13, 1) ``` The result is a tuple of ...
49,172,957
I'm learning python, I want to check if the second largest number is duplicated in a list. I've tried several ways, but I couldn't. Also, I have searched on google for this issue, I have got several answers to get/print 2nd largest number from a list but I couldn't find any answer to check if the 2nd largest number is ...
2018/03/08
[ "https://Stackoverflow.com/questions/49172957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6544266/" ]
Here is a *1-liner*: ``` >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(sorted(list1)[-2]) > 1 True ``` or using [heapq](https://docs.python.org/3/library/heapq.html#heapq.nlargest) ``` >>> import heapq >>> list1 = [5, 6, 9, 9, 11] >>> list1.count(heapq.nlargest(2, list1)[1]) > 1 True ```
Here is my proposal ``` li = [5, 6, 9, 9, 11] li_uniq = list(set(li)) # list's elements are uniquified li_uniq_sorted = sorted(li_uniq) # sort in ascending order second_largest = li_uniq_sorted[-2] # get the 2nd largest -> 9 li.count(second_largest) # -> 2 (duplicated if > 1) ```
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
You can play with some slicing through lists to gather elements from original list based on content in another list, sum it up and append to final list: ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] i = 0 for x in color: total.append(sum(vp[i:i+x])) i += x print(total) # [60, 90, 60] ```
``` total = [] index = 0 for c in color: inside = 0 for i in range(c): inside += vp[index + i] index += 1 total.append(inside) print(total) ```
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
This answer is not ideal for this example but it might be useful for other situations when you want to convert a dense representation to sparse representation. In this case, we convert the 1D array to 2D array with padding. For example, you want to be able to use `np.sum`: ``` total = [] vp = [10,20,30,40,50,60] color...
``` total = [] index = 0 for c in color: inside = 0 for i in range(c): inside += vp[index + i] index += 1 total.append(inside) print(total) ```
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
You can play with some slicing through lists to gather elements from original list based on content in another list, sum it up and append to final list: ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] i = 0 for x in color: total.append(sum(vp[i:i+x])) i += x print(total) # [60, 90, 60] ```
This answer is not ideal for this example but it might be useful for other situations when you want to convert a dense representation to sparse representation. In this case, we convert the 1D array to 2D array with padding. For example, you want to be able to use `np.sum`: ``` total = [] vp = [10,20,30,40,50,60] color...
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
You can play with some slicing through lists to gather elements from original list based on content in another list, sum it up and append to final list: ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] i = 0 for x in color: total.append(sum(vp[i:i+x])) i += x print(total) # [60, 90, 60] ```
Using List comprehensions - ``` vp = [10,20,30,40,50,60] color = [3,2,1] commu = np.cumsum(color) # Get the commulative sum - [3,5,6] commu = list([0])+list(commu[0:len(commu)-1]) # [0,3,5] and these are the beginning indexes total=[sum(vp[commu[i]:commu[i+1]]) if i < (len(range(len(commu)))-1) else sum(vp[com...
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
You can play with some slicing through lists to gather elements from original list based on content in another list, sum it up and append to final list: ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] i = 0 for x in color: total.append(sum(vp[i:i+x])) i += x print(total) # [60, 90, 60] ```
Other option build a list with slices then map to sum: Destructive: ``` slices = [] for x in color: slices.append(vp[0:x]) del vp[0:x] sums = [sum(x) for x in slices] print (sums) #=> [60, 90, 60] ``` Non destructive: ``` slices = [] i = 0 for x in color: slices.append(vp[i:x+i]) i += x sums = [sum(x) for...
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
This answer is not ideal for this example but it might be useful for other situations when you want to convert a dense representation to sparse representation. In this case, we convert the 1D array to 2D array with padding. For example, you want to be able to use `np.sum`: ``` total = [] vp = [10,20,30,40,50,60] color...
Using List comprehensions - ``` vp = [10,20,30,40,50,60] color = [3,2,1] commu = np.cumsum(color) # Get the commulative sum - [3,5,6] commu = list([0])+list(commu[0:len(commu)-1]) # [0,3,5] and these are the beginning indexes total=[sum(vp[commu[i]:commu[i+1]]) if i < (len(range(len(commu)))-1) else sum(vp[com...
53,569,854
I have two list. I want add values in vp based on the list color. So I want this output: ``` total = [60,90,60] ``` Because I want that the code runs what follows: `total = [10+20+30, 40+50,60]` ``` total = [] vp = [10,20,30,40,50,60] color = [3,2,1] ``` I don't know how to do. I began something like this in pyt...
2018/12/01
[ "https://Stackoverflow.com/questions/53569854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10532989/" ]
This answer is not ideal for this example but it might be useful for other situations when you want to convert a dense representation to sparse representation. In this case, we convert the 1D array to 2D array with padding. For example, you want to be able to use `np.sum`: ``` total = [] vp = [10,20,30,40,50,60] color...
Other option build a list with slices then map to sum: Destructive: ``` slices = [] for x in color: slices.append(vp[0:x]) del vp[0:x] sums = [sum(x) for x in slices] print (sums) #=> [60, 90, 60] ``` Non destructive: ``` slices = [] i = 0 for x in color: slices.append(vp[i:x+i]) i += x sums = [sum(x) for...
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
Don't use to much reflection.
For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI: ``` protected override System.Windows.Forms.CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle = cp.ExStyle...
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
Use a decent quality profiler and determine where your bottlenecks are. *Then* start asking how to improve performance. Anyone who makes any blanket statements like 'avoid reflection' without understanding both your performance profile and your problem domain should be shot (or at least reeducated). And given the siz...
NGEN will help with some code, but do not bank on it. Personally, if your design is bad/slow, there is not much you can do. The best suggestion in such a case, is to implement some form of caching of expensive tasks.
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
A lot of slowness is related to database access. Make your database queries efficient and you'll do a lot for your app.
I recomend you those books: [Effective C#](https://rads.stackoverflow.com/amzn/click/com/0321245660). [More Effective C#](https://rads.stackoverflow.com/amzn/click/com/0321485890)
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
Unfortunately, relatively few optimisations are language specific. The basics apply across languages: * Measure performance against realistic loads * Have clearly-defined goals to guide you * Use a good profiler * Optimise architecture/design relatively early * Only micro-optimise when you've got a proven problem Whe...
Use Ngen.exe (Should come shipped with Visual Studio.) <http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx> > > The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machi...
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
One simple thing is to ensure that your build configuration is set to "Release". This will enable optimizations and eliminate debugging information, making your executable smaller. More info [on MSDN](http://msdn.microsoft.com/en-us/library/ms173083.aspx) if needed.
A lot of slowness is related to database access. Make your database queries efficient and you'll do a lot for your app.
183,033
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: * **Firstly**: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization? * **Secondly**: When writing a program from scratch in C#, what are some ...
2008/10/08
[ "https://Stackoverflow.com/questions/183033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
One simple thing is to ensure that your build configuration is set to "Release". This will enable optimizations and eliminate debugging information, making your executable smaller. More info [on MSDN](http://msdn.microsoft.com/en-us/library/ms173083.aspx) if needed.
Caching items that result from a query: ``` private Item _myResult; public Item Result { get { if (_myResult == null) { _myResult = Database.DoQueryForResult(); } return _myResult; } } ``` Its a basic technique that is frequently overlooked by sta...