qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
28,542,083
I am currently working on a small project experimenting with different regions of python. I decided to make a multi-client TCP server in python, and wanted to be able to send a "packet" through the server, it be received by the other clients then parsed. However, I get an error if I try to send the packet, saying I mus...
2015/02/16
[ "https://Stackoverflow.com/questions/28542083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4410007/" ]
You could use pickle to serialize/deserialize objects to strings and back. <https://docs.python.org/2/library/pickle.html>
The simplest possible approach would be to send (gzipped?) JSON'd or [msgpack](https://pypi.python.org/pypi/msgpack-python/)'d objects. For example, using UDP, this could look something like the below code; note that you would want to reuse the socket object rather than instantiating a new one every time. ```py impor...
3,256
55,749,206
I've recently upgraded from `Ubuntu 18.04` to `19.04` which has `python 3.7`. But I work on many projects using `Python 3.6`. Now when I try to create a `virtualenv` with `Python 36` in PyCharm, it raises: ``` ModuleNotFoundError: No module named 'distutils.core' ``` [![enter image description here](https://i.stack...
2019/04/18
[ "https://Stackoverflow.com/questions/55749206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2607447/" ]
**Other Cases** This happened on my python3.7 installation but not my main python3 after i upgrade my ubuntu to 20.04 [Solution](https://github.com/pypa/get-pip/issues/43#issuecomment-621262469): ``` sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt install python3.7 ```
I still got error message after trying to install python3.9-distutils for python version 3.9 in pipenv. As I noticed [here](https://github.com/pypa/pipenv/issues/3890) python3.9-distutils is in conflict with earlier versions of that package and cannot be installed on Ubuntu18.04. I move on by using `python_version = "...
3,257
23,873,821
I'm not an experienced python coder, so be gentle. I have a very large (100s of Gb) binary file, that requires a particular command line tool (called parseTool here) to parse it. The format of the output of parseTool is simple raw text that I am doing some basic processing of (counting values, etc.). Before I think a...
2014/05/26
[ "https://Stackoverflow.com/questions/23873821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/295182/" ]
Your code is perfectly fine and will "stream" the data efficiently, assuming that the "parseTool" also streams properly and that the text output does not have really long lines. **If** it did have long lines (in particular, ones that scale as the input does, rather than having some upper bound) then you would want to ...
You say your file is in binary. If you use: ``` for line in proc.stdout: ... ``` Then the interpreter will read the binary data until it finds a new line character. Since you said "binary", this seams to be a bad solution. I would read in fixed chunks: ``` max_length=1024 while True: chunk=proc.stdout.r...
3,267
13,585,857
I'm using boto/python to launch a new EC2 instance that boots from an EBS volume. At the time I launch the instance, I'd like to override the default size of the booting EBS volume. I found no boto methods or parameters that might fit into my launch code: ``` ec2 = boto.connect_ec2( ACCESS_KEY, SECRET_KEY, region=re...
2012/11/27
[ "https://Stackoverflow.com/questions/13585857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856725/" ]
You have to create a block device mapping first: ``` dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType() dev_sda1.size = 50 # size in Gigabytes bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping() bdm['/dev/sda1'] = dev_sda1 ``` After this you can give the block device map in your `run_instances` call: `...
You can also use [CloudFormation](http://aws.amazon.com/cloudformation), which is used to document and automate your environment. You can check the template for the ESB definition at: <https://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2WithEBSSample.template> ``` "Resources" : { "Ec2Instance" : { ...
3,268
13,744,473
I'm calling a command line program in python using the `os.system(command)` call. How can I call this command passing a different folder for execution? There is a system call for this? Or I should save the current folder, and, after execution, change restore it.
2012/12/06
[ "https://Stackoverflow.com/questions/13744473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/329082/" ]
The [`subprocess`](https://docs.python.org/2/library/subprocess.html) module is a very good solution. ``` import subprocess p = subprocess.Popen([command, argument1,...], cwd=working_directory) p.wait() ``` It has also arguments for modifying environment variables, redirecting input/output to the calling program, et...
Try to `os.chdir(path)` before invoking the command. From [here](http://docs.python.org/2/library/os.html#os.chdir): > > os.chdir(path) Change the current working directory to path. > > > Availability: Unix, Windows > > > **EDIT** This will change the current working dir, you can get the current working by: ...
3,270
45,439,492
I would like be able to several layers together, but before specifying the input, something like the following: ``` # conv is just a layer, no application conv = Conv2D(64, (3,3), activation='relu', padding='same', name='conv') # this doesn't work: bn = BatchNormalization()(conv) ``` Note that I don't want to specif...
2017/08/01
[ "https://Stackoverflow.com/questions/45439492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/729288/" ]
Try this: ``` def create_shared_layers(): layers = [ Conv2D(64, (3,3), activation='relu', padding='same', name='conv'), BatchNormalization() ] def shared_layers(x): for layer in layers: x = layer(x) return x return shared_layers ``` Later, you can do someth...
What about using a Lambda layer. ```py import functools from typing import List from tensorflow import keras def compose_layers(layers: List[keras.layers.Layer], **kargs) -> keras.layers.Layer: return keras.layers.Lambda( lambda x: functools.reduce(lambda tensor, layer: layer(tensor), layers, x), **kargs, ...
3,273
64,320,386
I have a model which looks like this: ``` class InputTypeMap(models.Model): input_type = models.ForeignKey(InputType, on_delete=models.CASCADE) training = models.ForeignKey(Training, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) gender = models.ForeignKey(Ge...
2020/10/12
[ "https://Stackoverflow.com/questions/64320386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422005/" ]
most probably, that is a primary\_key problem, in my case i added to my model something like: ``` person_id = models.AutoField(primary_key=True) ``` adapt my views to it, and it solved it,
[Changing primary key int type to serial](https://stackoverflow.com/questions/23578427/changing-primary-key-int-type-to-serial) solved it for me. credit goes to [nishit chittora](https://stackoverflow.com/users/5081918/nishit-chittora).
3,276
39,483,862
Following examples and the numpy C-API (<http://docs.scipy.org/doc/numpy/reference/c-api.html>), I'm trying to access numpy array data in cpp, like this: ``` #include <Python.h> #include <frameobject.h> #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // TOGGLE OR NOT #include "numpy/ndarraytypes.h" #include "numpy/a...
2016/09/14
[ "https://Stackoverflow.com/questions/39483862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4121210/" ]
You could try using a higher-level library that wraps numpy arrays in C++ containers with proper container semantics. Try out `xtensor` and the `xtensor-python` bindings. * Numpy to xtensor cheat sheet <http://xtensor.readthedocs.io/en/latest/numpy.html> * The xtensor-python project <http://xtensor-python.readthedocs...
It is because `PyArray_DATA` expects a `PyArrayObject*`. You can try to change the type of `x_array`: ``` PyArrayObject* x_array = (PyArrayObject*) PyArray_FROM_OT(infobuffer, NPY_UINT32) ```
3,277
59,853,922
In python, how to generate a random number such that it is not a power of 2? The output needs to be a list of 8 random numbers. This should be done in a single statement (comprehension style) in python.
2020/01/22
[ "https://Stackoverflow.com/questions/59853922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778195/" ]
You can use array\_sum with array\_map like below, ``` $array1 = [1, 2, 2, 3]; $array2 = [10, 20, 30, 50]; $array_sum1 = []; foreach ($array1 as $key => $value) { $array_sum1[$value][] = $array2[$key]; } $array_sum1 = array_map("array_sum", $array_sum1); print_r($array_sum1); $array3 = [4, 4, 4, 6]; $a...
It is indirect to perform two iterations of your data to group & sum. Use the "id" values as keys in your output array. If a given "id" is encountered for the first time, then save the "val" value to the "id"; after the first encounter, add the "val" to the "id". Code: ([Demo](https://3v4l.org/fjINV)) ``` $ids = [1,...
3,278
74,320,720
I have some existing code that uses boto3 (python) DynamoDB Table objects to query the database: ```py import boto3 resource = boto3.resource("dynamodb") table = resource.table("my_table") # Do stuff here ``` We now want to run the tests for this code using DynamoDB Local instead of connecting to DynamoDB proper, to...
2022/11/04
[ "https://Stackoverflow.com/questions/74320720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734324/" ]
Yes, you can use the resource-level classes such as [Table](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#table) with both the real DynamoDB service and DynamoDB Local via the [DynamoDB service resource](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/service...
‎The other answers correctly told you that if you liked the "resource" API, you can still use it even with DynamoDB local (by the way, shameless plug: if you're looking for self-installable version of DynamoDB, you can also consider the open-source ScyllaDB project which has a DynamoDB API). I just wanted to add that ...
3,279
11,087,032
I have a XML file which contains values having unwanted characters like ``` \xc2d d\xa0 \xe7 \xc3\ufffdd \xc3\ufffdd \xc2\xa0 \xc3\xa7 \xa0\xa0 '619d813\xa03697' \xe9.com ``` input examples could be ``` name : John Hinners\xc2d email: abc@gmail\xe9.com and others .... ``` desired output should be ``` name : ...
2012/06/18
[ "https://Stackoverflow.com/questions/11087032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379235/" ]
In java it will not be as pretty. You can use a regexp but if you don't have a simple definition of your characters the best is probably to do this : ``` StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { if (((int)s.charAt(i))<128) sb.append(s.charAt(i)); } ...
``` String s = "WantedCharactersunwantedCharacters"; ``` If I want the remaining String to be "WantedCharacters", I simply write: ``` s = s.replaceAll("unwantedCharacters", ""); ``` [EDIT]: You could, of course, also write ``` private static String removeNonAscii(String s){ StringBuffer sb = new StringBuffer(...
3,280
62,333,071
I have been using a working Anaconda install (Python 3.7) for about a year, but suddenly I'm getting this warning when I run the interpreter: ```none > python Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 Warning: This Python interpreter is in a conda environment...
2020/06/11
[ "https://Stackoverflow.com/questions/62333071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8605685/" ]
If you receive this warning, you need to activate your environment. To do so on Windows, use the Anaconda Prompt shortcut in your Windows start menu. If you have an existing cmd.exe session that you’d like to activate conda in run: `call <your anaconda/miniconda install location>\Scripts\activate base.`
I have the same problem, by following this post [conda-is-not-recognized-as-internal-or-external-command](https://stackoverflow.com/questions/44515769/conda-is-not-recognized-as-internal-or-external-command), I am able to solve the problem. The reason may be that your default Python interpreter has been switch to the ...
3,283
43,110,228
I'm learning to use rpy2 in Jupyter notebook. I'm having troubles with the plotting. When I use this example from the rpy2 [docs](http://rpy2.readthedocs.io/en/version_2.8.x/interactive.html?highlight=ipython#ipython-magic-integration-was-rmagic) for interactive work: ``` from rpy2.interactive import process_revents f...
2017/03/30
[ "https://Stackoverflow.com/questions/43110228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2998998/" ]
It seems that this is the answer to your question: <https://bitbucket.org/rpy2/rpy2/issues/330/ipython-plotting-wrapper> ``` with rpy2.robjects.lib.grdevices.render_to_bytesio(grdevices.png, width=1024, height=896, res=150) as img: graphics.barplot(IntVector((1,3,2,5,4)), ylab="Value") IPython.display.display(IPyt...
This is slightly more sopthisticated version of Christian's answer which wraps the plotting and inline embedding into the same context manager: ```py from contextlib import contextmanager from rpy2.robjects.lib import grdevices from IPython.display import Image, display @contextmanager def r_inline_plot(width=600, he...
3,284
20,444,056
I have a list of tuples each with 5 pieces of information in it. I need a way to search the list for a result or range of results from a search parameter or parameters. So I'd like to search for an ID number (string) or name (string - only the whole name) or a range of salary so between (int - 10000-20000). I read on a...
2013/12/07
[ "https://Stackoverflow.com/questions/20444056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2080298/" ]
The Checked property is set right on the XAML loading, when you set IsChecked="True". The tag may be loaded only later when the XAML loading code decides to set this property. That's why you can see uninitialized properties.
simple Solution for all of these type bugs/errors: ``` 1- bool bFormLoaded;//=false ; 2- at [YourWinOrControlorWPF]_Loaded(object sender, RoutedEventArgs e) add this flag at end of function: bFormLoaded=true; 3-at UseDefaultFoldersCB_Checked(...) add this line if(bFormLoaded==false) return; ``` 100%
3,287
62,099,166
I am trying to send data from python server to android client but it is not accepting any data from the server. but it is showing that it is connected with the server. i cant recognize any error. here is my client code in android java. ``` package com.example.socketinput; import androidx.appcompat.app.AppCompatActiv...
2020/05/30
[ "https://Stackoverflow.com/questions/62099166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6938184/" ]
You should use fake content while testing a layout, **unless your fixed height can match together** *(left col is box1+box5 = 1600px and col right is 1300px so a 300px gap(s)/difference)* : White space are here because of the heights arbitrary given to children. Your grid woks fine and is fluid : **Tips** : For testin...
If you want to maintain the designated heights, you can wrap the column 2 `divs` into a `flex` wrapper: ``` <div class="container"> <div class="box box1">1</div> <div class="box box5">5</div> <div class = "flex"> <div class="box box2">2</div> <div class="box box3">3</div> <div class="box box4">4</div> <di...
3,288
5,166,488
python and Tkinter are processing Unicode characters correctly. But they are not able to display Unicode encoded characters correctly. I am using Python 3.1 and Tkinter in Ubuntu. I am trying to use Tamil Unicode characters. All the processing is done correctly. But the display is wrong? Here is the Wrong display a...
2011/03/02
[ "https://Stackoverflow.com/questions/5166488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/641040/" ]
I had faced similar problems and discovered I used the Zero Width Joiner (U+200D) to explicitly tell the rendering engine to join two characters. That used to work in 2010 but looks like there have been changes in the rendering engine (that I am now aware of) and now in 2011 I find that having the joiner creates the pr...
It looks like Tk is mishandling things like 'Class Zero Combining Marks', see: <http://www.unicode.org/versions/Unicode6.0.0/ch04.pdf#G124820> (Table 4-4) I assume one of the sequences that do not show correctly are the codepoints: 0BA9 0BC6 (TAMIL SYLLABLE NNNE), where 0BC6 is a reordrant class zero combining mark ac...
3,289
3,589,214
So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbin...
2010/08/28
[ "https://Stackoverflow.com/questions/3589214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433493/" ]
Generate 4 random numbers, compute their sum, divide each one by the sum and multiply by 40. If you want Integers, then this will require a little non-randomness.
Building on [@markdickonson](https://stackoverflow.com/a/3590105/75033) by providing some control over distribution between the divisors. I introduce a variance/jiggle as a percentage of the uniform distance between each. ``` def constrained_sum_sample(n, total, variance=50): """Return a random-ish list of n posi...
3,291
74,271,418
I'm pretty new at Power BI (so forgive my rough terminology), and I'm trying to create a bar chart from some existing financial data. Specifically, I'd like to know how to transform my data. I've looked at DAX and python, and can't quite figure out the right commands. My existing table looks like the following. The se...
2022/11/01
[ "https://Stackoverflow.com/questions/74271418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019700/" ]
1. Avoid Excel-style cross-tables in Power BI. In the PowerQuery Editor transform your table by selecting Categorie and then **Unpivot other columns** [![enter image description here](https://i.stack.imgur.com/UAHij.png)](https://i.stack.imgur.com/UAHij.png) 2. Back in the designer view you can directly use this data...
Here is the full M-Code to achieve your goal: Just change the source step with your source file: ``` let Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUTI0ABLmpkhErE60khOMb2oJl7EEyziD9ID4xkYgljFIDVyLEYhraATXgtBhDiQsLGASQANiYwE=", BinaryEncoding.Base64), Compression.Deflate)), let...
3,301
13,391,549
I try to use a Bixolon receipt printer with OE on Windows 7. I success to print directly from a small python module using win32print (coming with py32win) with the code below : win32print is not natively in OE so I paste win32print.pyd in OE server directory and put the code in a wizard of my OE module. I can see my ...
2012/11/15
[ "https://Stackoverflow.com/questions/13391549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1682857/" ]
Remember that the python code runs on the server. Is your printer connected to the server? Also, you don't have an `except` section in your `try`. That makes errors go by silently. Try removing the `try` block so that errors are raised. Looking at them you might figure out the issue.
Well, I don't know if you typed here incorrectly, but the way you imported the `win32print` module force you to attach it to module function calls and you haven't done this in your first line: ``` printer = OpenPrinter(win32print.GetDefaultPrinter()) ``` should be ``` printer = win32print.OpenPrinter(win32print.Get...
3,302
11,878,300
I would like to serialize on machine A and deserialize on machine B a python lambda. There are a couple of obvious problems with that: * the pickle module does not serialize or deserialize code. It only serializes the names of classes/methods/functions * some of the answers I found with google suggest the use of the l...
2012/08/09
[ "https://Stackoverflow.com/questions/11878300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/782529/" ]
Surprisingly, checking whether a lambda will work without its associated closure is actually fairly easy. According to the [data model documentation](http://docs.python.org/release/2.6.2/reference/datamodel.html), you can just check the `func_closure` attribute: ``` >>> def get_lambdas(): ... bar = 42 ... ret...
I'm not sure exactly what you want to do, but you could try [dill](https://github.com/uqfoundation/dill). Dill can serialize and deserialize lambdas and I believe also works for lambdas inside closures. The pickle API is a subset of it's API. To use it, just "import dill as pickle" and go about your business pickling s...
3,303
39,278,419
I am trying to POST a request to server side from android client side, using AsyncHttpClient : For now i just want to check whether the response is coming back or not , so i have not implemented anything to parse request parameters at server side and have just returned some json as response. ``` RequestParams param...
2016/09/01
[ "https://Stackoverflow.com/questions/39278419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820753/" ]
The way I found to do it is by using the token provider from the namespace manager. So: ``` var namespaceMngr = NamespaceManager.CreateFromConnectionString(namespaceConnString); MessagingFactorySettings mfs = new MessagingFactorySettings(); mfs.TokenProvider = namespaceMngr.Settings.TokenProvider; mfs.NetMessagingTran...
JordanSchillers answer fixes the token provider issue but my address was now using port 9355 instead of 9354. I ended using a mixture of the ServiceBusConnectionStringBuilder and the NamespaceManager: ``` var serviceBusConnectionString = new ServiceBusConnectionStringBuilder(connection.ConnectionString); ...
3,304
17,004,946
I have some logging in my application (it happens to be log4cxx but I am flexible on that), and I have some unit tests using the boost unit test framework. When my unit tests run, I get lots of log output, from both the passing and failing tests (not just boost assertions logged, but my own application code's debug log...
2013/06/08
[ "https://Stackoverflow.com/questions/17004946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99876/" ]
There are start of test and end of test hooks that you can use for this purpose. To set up these hooks you need to define a subclass of [boost::unit\_test::test\_observer](https://www.boost.org/doc/libs/1_70_0/libs/test/doc/html/boost/unit_test/test_observer.html), create an instance of the class that will persist thro...
According to the [Boost.Test documentation](http://www.boost.org/doc/libs/1_53_0/libs/test/doc/html/utf/user-guide/runtime-config/reference.html), run your test executable with `--log_level=error`. This will catch only failing test cases. I checked that it works using a `BOOST_CHECK(false)` on an otherwise correctly ...
3,305
16,092,153
I wish to create a 'find' procedure **myself**, which is capable of finding a sub-string in a string and it also should be able to read a string backward and give position of match- just like the original find function in python. I am unable to figure out what logic should I use- also I don't know how the original fi...
2013/04/18
[ "https://Stackoverflow.com/questions/16092153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050305/" ]
> > also I don't know how the original find functions > > > A good way to learn about functions without googling is to use [Ipython](http://ipython.org/)and especially the [notebook variant](http://ipython.org/notebook.html/). These allow you to write python code interactively, and have some special features. Typi...
There is a simple solution to this problem, however there are also much faster solutions which you may want to look at after you've implemented the simple version. What you want to be doing is checking each position in the string you're search over and seeing if the string you're searching for starts there. This is ine...
3,306
27,967,988
So I was dissapointed to find out that JavaScript's `for ( var in array/object)` was not equivalent to pythons `for var in list:`. In JavaScript you are iterating over the indices themselves e.g. ``` 0, 1, 2, ... ``` where as with Python, you are iterating over the values pointed to by the indices e.g. ``` "s...
2015/01/15
[ "https://Stackoverflow.com/questions/27967988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3581485/" ]
for an array the most similar is the forEach loop (of course index is optional) ``` [1,2,3,4,].forEach(function(value,index){ console.log(value); console.log(index); }); ``` So you will get the following output: ``` 1 0 2 1 3 2 4 3 ```
In the next version of ECMAScript (ECMAScript6 aka Harmony) will be [for-of construct](http://tc39wiki.calculist.org/es6/for-of/): ``` for (let word of ["one", "two", "three"]) { alert(word); } ``` `for-of` could be used to iterate over various objects, Arrays, Maps, Sets and custom iterable objects. In that sense...
3,312
66,650,626
Is there any to restore files from the recycle bin in python? Here's the code: ``` from send2trash import send2trash file_name = "test.txt" operation = input("Enter the operation to perform[delete/restore]: ") if operation == "delete": send2trash(file_name) print(f"Successfully deleted {file_name}") else:...
2021/03/16
[ "https://Stackoverflow.com/questions/66650626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14909172/" ]
It would depend on your operating system. **Linux** it's as simple as moving it from the trash folder to the original path. The location of the trash folder differs from distro to distro, but this is where it typically is. There is a [command line tool](https://github.com/andreafrancia/trash-cli) that you can use, o...
**Google Colab** (you are the `root` user) Import the shell utility for Python: ```py import shutil ``` Move the file from trash to a selected destination: ```py shutil.move('/root/.local/share/Trash/files/<deleted-file>', '<destination-path>') ```
3,315
54,207,540
I'm trying to find any python library or package which implements [newgrnn (Generalized Regression Neural Network)](https://www.mathworks.com/help/deeplearning/ref/newgrnn.html) using python. Is there any package or library available where I can use neural network for regression. I'm trying to find python equivalent ...
2019/01/15
[ "https://Stackoverflow.com/questions/54207540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5347207/" ]
I found the library neupy which solved my problem: ``` from neupy import algorithms from neupy.algorithms.rbfn.utils import pdf_between_data grnn = algorithms.GRNN(std=0.003) grnn.train(X, y) # In this part of the code you can do any moifications you want ratios = pdf_between_data(grnn.input_train, X, grnn.std) pre...
A more upgraded form is [pyGRNN](https://github.com/federhub/pyGRNN) which offers in addition to the normal GRNN the Anisotropic GRNN, which optimizes the hyperparameters automatically: ``` from sklearn import datasets from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn....
3,316
33,713,149
I have a text file containing CPU stats as below (from sar/sysstat) ``` 17:30:38 CPU %user %nice %system %iowait %steal %idle 17:32:49 all 14.56 2.71 3.79 0.00 0.00 78.94 17:42:49 all 12.68 2.69 3.44 0.00 0.00 81.19 17:52:4...
2015/11/14
[ "https://Stackoverflow.com/questions/33713149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247154/" ]
Here is a more dynamic version that would scale to more columns. But there isn't really anything bad about your implementation. ``` # build a dict of column name -> list of column values stats = {} with open('stats.txt') as F: header = None for idx, line in enumerate(F): # This is the header i...
First you could use `_` or `__` to represent ignored values (this is a common convention). Next you could store all values into a single list and then unpack the list into multiple lists using `zip`. ``` cpu_stats = [] with open('stats.txt') as stats_file: for line in stats_file: time, _, user, _, system,...
3,317
21,881,748
This may be a stupid question but I'm not sure how to phrase it in a google-friendly way... In a terminal if you type something like: ``` nano some_file ``` then nano opens up an edit window inside the terminal. A text based application. Ctrl+X closes it again and you see the terminal as it was. Here's another exa...
2014/02/19
[ "https://Stackoverflow.com/questions/21881748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742082/" ]
You probably need to use alternative screen buffer. To enable it just print '\0033[?1049h' and for disabling '\0033[?1049l' (Terminal Control Escape Sequences). <http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#The%20Alternate%20Screen%20Buffer> Example: ``` print('\033[?1049h', end='') print('Alternative scree...
This does the trick: <http://docs.python.org/2/howto/curses.html> Example: ``` import curses oScreen = curses.initscr() curses.noecho() curses.curs_set(0) oScreen.keypad(1) oScreen.addstr("Woooooooooooooo\n\n",curses.A_BOLD) while True: oEvent = oScreen.getch() if oEvent == ord("q"): break curses.end...
3,320
6,577,218
I have a python application where I want to start doing more work in the background so that it will scale better as it gets busier. In the past I have used Celery for doing normal background tasks, and this has worked well. The only difference between this application and the others I have done in the past is that I ...
2011/07/05
[ "https://Stackoverflow.com/questions/6577218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356788/" ]
I suspect that Celery bound to existing backends is the wrong solution for the reliability guarantees you need. Given that you want a distributed queueing system with strong durability and reliability guarantees, I'd start by looking for such a system (they do exist) and then figuring out the best way to bind to it in...
I've used Amazon SQS for this propose and got good results. You will recieve message until you will delete it from queue and it allows to grow you app as high as you will need.
3,321
21,669,632
I am trying to open a Windows Media Video file on a macintosh using OpenCV. To view this video in MacOS I had to install a player called Flip4Mac. I am assuming that this came with the codecs for decoding WMV. Is there something I can now do to get OpenCV to open the videos using the codec? In python/opencv2 opening a...
2014/02/10
[ "https://Stackoverflow.com/questions/21669632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391339/" ]
use split function. ``` var str = "Architecture, Royal Melbourne Institute of Technology"; console.log(str.split(",")[0]);// logs Architecture ``` output array after splitting your string by `,` would have the expected result at the zeroth index.
Its again a normal Javascript, all the methods can be used in nodeJS. var name = "any string"; For example: ``` var str = "Hi, world", arrayOfStrings = str.split(','), output = arrayOfStrings[0]; // output contains "Hi" ``` You can update the required field by directly replacing the string ie. ``` arrayOfStrings[0]...
3,330
7,020,630
I wish to run a long-running script in the background upon receiving a request. I read about `subprocess` but I require that the call is nonblocking so that the request can complete in time. ``` def controlCrawlers(request): if request.method == 'POST' and 'type' in request.POST and 'cc' in request.POST: ...
2011/08/11
[ "https://Stackoverflow.com/questions/7020630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357236/" ]
Yeah, don't do this, use [celery](http://docs.celeryproject.org/en/master/getting-started/introduction.html) instead. It makes running asynchronous tasks a lot easier, more reliable.
If you don't want to use asynchronous task queues with something like celery you can always just run a python script via cron. There are several options to do this. An example: * create a model which save the values which are needed by your process * write a standalone python/django script which get the values from th...
3,331
19,742,451
I'm trying to use Django with virtualenv. I actually got the Django hello world webpage to display with 127.0.0.1:8001. Later I had to do some minor tweaks and now its giving me this error when I try to launch it again (I ctrl-Z from the previous working gunicorn session so I don't think it is because of that). ``` ...
2013/11/02
[ "https://Stackoverflow.com/questions/19742451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1661745/" ]
`ctrl+z` halts the process, but does not close it. In consequence it does not release its ports. You can bring the process back with `fg` and then close it properly using `ctrl+c`.
The port 8000 was probably bound and thus unavailable for the connection.
3,332
62,295,863
I have this (python) list my\_list = [['dog','cat','mat','fun'],['bob','cat','pan','fun'],['dog','ben','mat','rat'], ['cat','mat','fun','dog'],['mat','fun','dog','cat'],['fun','dog','cat','mat'], ['rat','dog','ben','mat'],['dog','mat','cat','fun'], ... ] my\_list has 200704 elements Note here my\_...
2020/06/10
[ "https://Stackoverflow.com/questions/62295863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13717822/" ]
Your implementation is an n-squared algorithm, which means that the implementation time will grow dramatically for a large data set. 200,000 squared is a very large number. You need to convert this to an order n or n-log(n) algorithm. To do that you need to preprocess the data so that you can check whether a circularly...
@BradBudlong Brad Budlong's answer is right. Following is the implementation result of the same. My method (given in the question): Time taken: ~274 min Result: len(my\_list\_without\_circular\_duplicates) >> 50176 Brad Budlong's method: Time taken: ~12 sec (great !) Result: len(my\_list\_with...
3,335
58,909,624
While reading this [article](https://pbpython.com/pandas_transform.html), I came across this statement. ``` order_total = df.groupby('order')["ext price"].sum().rename("Order_Total").reset_index() ``` Other than `reset_index()` method call, everything else is clear to me. My question is what will happen if I don't...
2019/11/18
[ "https://Stackoverflow.com/questions/58909624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1465553/" ]
I think better here is use [`GroupBy.transform`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.transform.html) for new `Series` with same size like original DataFrame filled by aggregate values, so `merge` is not necessary: ``` df_1 = pd.DataFrame({ 'A':list('abcdef'), ...
A simplified explanation is that; `reset_index()` takes the current index, and places it in column 'index'. Then it recreates a new 'linear' index for the data-set. ``` df=pd.DataFrame([20,30,40,50],index=[2,3,4,5]) 0 2 20 3 30 4 40 5 50 df.reset_index() index 0 0 2 20 1 3 30 2 4 40 3...
3,336
55,276,170
I have been using Selenium and python to web scrape for a couple of weeks now. It has been working fairly good. Been running on a macOS and windows 7. However all the sudden the headless web driver has stopped working. I have been using chromedriver with the following settings: ``` from selenium import webdriver from ...
2019/03/21
[ "https://Stackoverflow.com/questions/55276170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9428990/" ]
You could try giving your svg an id (or class) and then styling it like so: ``` #test{ opacity:0; } #test:hover{ opacity:1; } ``` --- the id should be inside your svg: ``` <svg id="test" .............. > </svg> ``` Im not sure if this is what you exactly mean but its an easy way to do it
I would suggest taking a look at [ngx-svg](https://www.npmjs.com/package/ngx-svg) which allows to create containers and add multiple elements within those containers - in your case circles. It has other elements as well, and there is a documentation, which allows to understand what you have to do as well.
3,341
17,779,480
Recently, I've been attempting to defeat one of my main weaknesses in programming in general, random generation. I thought it would be an easy thing to do, but the lack of simple information is killing me on it. I don't want to sound dumb, but it feels to me like most of the information from places like [this](http://f...
2013/07/22
[ "https://Stackoverflow.com/questions/17779480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577669/" ]
The direct answer to your question is "No, you cannot do what you are asking", and the second answer is "Yes, you are thinking about this all wrong". The reason is that you are generating completely random noise. What you are asking for is coherent noise. They are two completely different animals and you cannot get co...
Rather use cellular automatons. The algorithm that you find [here](http://www.roguebasin.com/index.php?title=Cellular_Automata_Method_for_Generating_Random_Cave-Like_Levels) creates similar patterns that you you would like to see: ``` . . . . . . . . . . . . . . . . . . . . # # . . . . . # . . . . . . # # # # . . . # ...
3,342
48,166,183
I have a problem which my novice knowledge cannot solve. I'm trying to copy some python-2.x code (which is working) to python-3.x. Now it gives me an error. Here's a snippet of the code: ``` def littleUglyDataCollectionInTheSourceCode(): a = { 'Aabenraa': [842.86917819535, 25.58264089252], 'Aalborg': [...
2018/01/09
[ "https://Stackoverflow.com/questions/48166183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6551344/" ]
In your example `myDict` is a dictionary with strings as keys and lists as values. ``` key = data.kommune.encode("utf-8") ``` will be a bytes object, so there can't ever be any corresponding value for that key in the dictionary. This worked in python2 where automatic conversion was performed, but not anymore in pyth...
You are using `0` as a default value for `rd`, whereas the values in the dict are lists, so if the key is not found, `rd[0]` or `rd[1]` will fail. Instead, use a list or tuple as default, then it should work. ``` rd = myDict.get(key.strip(), [0, 0]) ```
3,344
6,493,681
I have a list of ids in python. For example: ``` x = [1,2,3,4,5,6] ``` And i want to select a list of records in my (mysql ) data-base under the condition that the ids of these records are in x. something like below: ``` SELECT * FROM mytable WHERE id IN x ``` but I don't know who I can do this in python. I have ...
2011/06/27
[ "https://Stackoverflow.com/questions/6493681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313245/" ]
Try something like this: ``` '(%s)' % ','.join(map(str,x)) ``` This will give you a string that you could use to send to MySql as a valid `IN` clause: ``` (1,2,3,4,5,6) ```
Well, if all of those are known to be numbers of good standing, then you can simply call ``` "SELECT * FROM mytable WHERE ID IN ({0})".format(','.join(x)) ``` If you know that they are numbers but *any* of them might have been from the user, then I might use: ``` "SELECT * FROM mytable WHERE ID IN ({0})".format(','...
3,347
11,360,161
I get this error while running a python script (called by ./waf --run): TypeError: abspath() takes exactly 1 argument (2 given) The problem is that it is indeed called with: obj.path.abspath(env). This is not a python issue, because that code worked perfectly before, and it's part of a huge project (ns3) so I doubt t...
2012/07/06
[ "https://Stackoverflow.com/questions/11360161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1502564/" ]
The documentation of the method [`Node.abspath()`](http://docs.waf.googlecode.com/git/apidocs_16/Node.html#waflib.Node.Node.abspath) states it does not take an additional `env` parameter, and I confirmed that it never did by checking the git history. I suggest replacing ``` if not (obj.path.abspath().startswith(launch...
You should have a file name and line number in the traceback. Go to that file and line and find out was "obj" and "obj.path.abspath" are. A simple solution would be to put the offending line in a try/except block to print (or log) more informations, ie: ``` # your code here try: whatever = obj.path.abspath(env) ex...
3,348
48,264,720
I am starting to learn the application of different types of classifiers in python sklearn module. The clf\_LR.predict(X\_predict) predicts the 'Loan\_Status' of the test data. In the training data it is either 1 or 0 depending on loan approval. But the predict gives a numpy array of float values around 0 and 1. I want...
2018/01/15
[ "https://Stackoverflow.com/questions/48264720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8380563/" ]
``` import numpy as np np.round(np.clip(clf_LR.predict(X_predict), 0, 1)) # floats np.round(np.clip(clf_LR.predict(X_predict), 0, 1)).astype(bool) # binary ``` * [numpy.clip](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.clip.html) * [numpy.round](https://docs.scipy.org/doc/numpy-1.13.0/referen...
As said in @Pault comment what you need is a classifier, sklearn has many classifiers! The choice of a classifier to use depend on many factors: The following picture from [sklearn](http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html) can help you to choose : [![The following picture ](https://i.st...
3,350
36,427,747
I'm using Ipython Notebook to my research. As my file grows bigger, I constantly extract code out, things like plot method, fitting method etc. I think I need a way to organize this. Is there any good way to do it?? --- Currently, I do this by: ``` data/ helpers/ my_notebook.ipynb import_file.py ``` I store data...
2016/04/05
[ "https://Stackoverflow.com/questions/36427747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1794744/" ]
There are many ways to organise ipython research project. I am managing a team of 5 Data Scientists and 3 Data Engineers and I found those tips to be working well for our usecase: This is a summary of my PyData London talk: <http://www.slideshare.net/vladimirkazantsev/clean-code-in-jupyter-notebook> **1. Create a sh...
You should ideally have a library hierarchy. I would organize it as follows: Package wsautils ---------------- Fundamental, lowest level package [No dependencies] stringutils.py: Contains the most basic files such string manipulation dateutils.py: Date manipulation methods Package wsadata --------------- * Parsing...
3,351
54,292,049
I play to HackNet game and i have to guess a word to bypass a firewall. The key makes 6 characters long and contains the letters K,K,K,U,A,N. What is the simplest way to generate all possible combinations either in bash or in python ? (bonus point for bash)
2019/01/21
[ "https://Stackoverflow.com/questions/54292049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10945277/" ]
Git uses a tree organization that is only allowed to be added new nodes (commits). If you really want to delete a wrongly pushed commit you must update your repository locally and than force push to the according remote. I found an issue talking about it. [How to undo the initial commit on a remote repository in git?]...
use `git revert <commit_id_to_be_reverted>`
3,361
1,265,078
I want to used python to get the executed file version, and i know the [pefile.py](http://code.google.com/p/pefile/) how to used it to do this? notes: the executed file may be not completely.
2009/08/12
[ "https://Stackoverflow.com/questions/1265078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/154106/" ]
This is the best answer I think you can find: ``` import pefile pe = pefile.PE("/path/to/something.exe") print hex(pe.VS_VERSIONINFO.Length) print hex(pe.VS_VERSIONINFO.Type) print hex(pe.VS_VERSIONINFO.ValueLength) print hex(pe.VS_FIXEDFILEINFO.Signature) print hex(pe.VS_FIXEDFILEINFO.FileFlags) print hex(pe.VS_FIXE...
I'm not sure that I understand your problem correctly, but if it's something along the lines of using pefile to retrieve the version of a provided executable, then perhaps (taken from [the tutorial][1]) ``` import pefile pe = pefile.PE("/path/to/pefile.exe") print pe.dump_info() ``` will provide you with the version...
3,364
62,017,437
I am new to programming. I have made a python script. It runs without errors in pycharm. Using pyinstaller i tried to make an exe. When i run the exe in build or dist folder or even through command prompt, it gives me the error 'Failed to execute Script Main' I am attaching the warnings file link: <https://drive.goog...
2020/05/26
[ "https://Stackoverflow.com/questions/62017437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13605404/" ]
There is one pip script for each virtual environment. So when you install a python module it get installed into the projectname\venv\Lib\site-packages directory. When you run pyinstaller from terminal to make the executable, pyinstaller checks for dependencies in Sys.path . But that path does not include the projectna...
I know I write this 10 months after but i run into the same problem and i know the solution. so, maybe some people who have the same problem could get help. If your script has any additional files such as db,csv,png etc. you should add this files same directory. in this way you could solve the problem i guess. at leas...
3,365
48,021,748
I have two mysql database one is localhost and another is in server now, am going to create simple app in python using flask for that application i would like to connect the both mysql DB (local and server). Any one please suggest how to connect multiple DB into flask. ``` app = Flask(__name__) client = MongoClient()...
2017/12/29
[ "https://Stackoverflow.com/questions/48021748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5483189/" ]
I had the same issue, finally figured it out. Instead of using ``` client = MongoClient() client = MongoClient('localhost', 27017) db = client.sampleDB1 ``` Delete all that and try this: ``` mongo1 = PyMongo(app, uri = 'mongodb://localhost:27017/Database1') mongo2 = PyMongo(app, uri = 'mongodb://localhost:27017/Da...
create model.py and separate instances of 2 databases inside it, then in app.py: ``` app = Flask(__name__) app.config['MODEL'] = model.my1st_database() app.config['MODEL2'] = model.my2nd_database() ``` works for me :)
3,366
57,010,207
I want to use R to split some chat messages, here is an example: ``` example <- "[29.01.18, 23:33] Alice: Ist das hier ein Chatverlauf?\n[29.01.18, 23:45] Bob: Ja ist es!\n[29.01.18, 23:45] Bob: Der ist dazu da die funktionsweise des Parsers zu demonstrieren\n[29.01.18, 23:46] Alice: ‎PTT-20180129-WA0025.opus (Datei a...
2019/07/12
[ "https://Stackoverflow.com/questions/57010207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6039913/" ]
You could add a negative lookahead `(?!^)` to assert not the start of the string. Your updated line might look like: ``` chat <- strsplit(example,"(?!^)(?=\\[\\d\\d.\\d\\d.\\d\\d, \\d\\d:\\d\\d\\])",perl=TRUE) ``` [R demo](https://ideone.com/KlRaFp) Result ``` [1] "[29.01.18, 23:33] Alice: Ist das hier ein Chatv...
You can use `stringi` and extract the info you want by slightly modifying the end of your pattern (i.e., matching everything until the next `[`). You could include more of your pattern to ensure there aren't any false-matches but this should get your started. Good luck! ``` library(stringi) stri_extract_all(example, ...
3,369
25,567,791
I've been trying for several days now to send a python array by i2c. ``` data = [x,x,x,x] # `x` is a number from 0 to 127. bus.write_i2c_block_data(i2c_address, 0, data) bus.write_i2c_block_data(addr, cmd, array) ``` In the function above: addr - arduino i2c adress; cmd - Not sure what this is; array - python arra...
2014/08/29
[ "https://Stackoverflow.com/questions/25567791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3866306/" ]
The function is the good one. But you should take care of some points: * bus.write\_i2c\_block\_data(addr, cmd, []) send the value of cmd AND the values in the list on the I2C bus. So ``` bus.write_i2c_block_data(0x20, 42, [12, 23, 34, 45]) ``` doesn't send 4 bytes but 5 bytes to the device. I doesn't know how t...
It took me a while,but i got it working. On the arduino side: ``` int count = 0; ... ... void receiveData(int numByte){ while(Wire.available()){ if(count < 4){ byteArray[count] = Wire.read(); count++; } else{ count = 0; byteArray[count] = Wire.read(); } ...
3,370
12,758,591
Are there any libraries in Python that does or allows Text To Speech Conversion using Mac Lion's built in text to speech engine? I did google but most are windows based. I tried pyttx. I tried to run ``` import pyttsx engine = pyttsx.init() engine.say('Sally sells seashells by the seashore.') engine.say('The quick br...
2012/10/06
[ "https://Stackoverflow.com/questions/12758591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1657827/" ]
Wouldn't it be much simpler to do this? ``` from os import system system('say Hello world!') ``` You can enter `man say` to see other things you can do with the `say` command. However, if you want some more advanced features, importing `AppKit` would also be a possibility, although some Cocoa/Objective C knowledge ...
If you are targeting Mac OS X as your platform - PyObjC and NSSpeechSynthesizer is your best bet. Here is a quick example for you ``` #!/usr/bin/env python from AppKit import NSSpeechSynthesizer import time import sys if len(sys.argv) < 2: text = raw_input('type text to speak> ') else: text = sys.argv[1] n...
3,373
53,622,737
I have a Pandas Dataframe which has columns which look something like this: ``` df: Column0 Column1 Column2 'MSC' '1' 'R2' 'MIS' 'Tuesday' '22' '13' 'Finance' 'Monday' ``` So overall, in these columns are actual strings but also numeric values (integers) which are in string format....
2018/12/04
[ "https://Stackoverflow.com/questions/53622737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10027078/" ]
100% agree with the comments—mixing dtypes in columns is a terrible idea, performance wise. For reference, however, I would do this with `pd.to_numeric` and `fillna`: ``` df2 = df.apply(pd.to_numeric, errors='coerce').fillna(df) print(df2) Column0 Column1 Column2 0 MSC 1 R2 1 MIS Tuesday ...
I would apply `pd.to_numeric` with `errors='coerce'`, and `update` the original dataframe according to the results (see caveats in comments): ``` # show original string type: df.loc[0,'Column1'] # '1' df.update(df.apply(pd.to_numeric, errors='coerce')) >>> df Column0 Column1 Column2 0 MSC 1 R2 1 ...
3,376
7,504,129
I have a variable, `fulltext`, which contains the full text of what I want the description of a new changelist in P4V to be. There are already files in the default changelist. I want to use python to populate the description of a new changelist (based on default) with the contents of `fulltext`. How can this be done....
2011/09/21
[ "https://Stackoverflow.com/questions/7504129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343381/" ]
If you're trying to write Python programs that work against Perforce, you might find P4Python helpful: <http://www.perforce.com/perforce/doc.current/manuals/p4script/03_python.html>
It is easiest if you have the changelist numbers that you know you are going to change. ``` #changeListIDNumber is the desired changelist to edit import P4 p4 = P4.connect() cl = p4.fetch_changelist(changeListIDNumber) cl['Description'] = 'your description here' p4.save_change(cl) ``` If you...
3,379
45,406,847
I use Django to send email,everything is OK when running on development environment, which uses command "python manage.py runserver 0.0.0.0:8100". But in the production environment which deployed by nginx+uwsgi+Django do not work. Here is the code: ``` #Email settings EMAIL_HOST='smtp.exmail.qq.com' EMAIL_PORT='465'...
2017/07/31
[ "https://Stackoverflow.com/questions/45406847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6133601/" ]
You could wrapping the check in a `setTimeout`: ``` $(".menu-toggle").first().click(function () { setTimeout(function() { if (!$("#wrapper").hasClass("menu-active")) { $("#wrapper").find("div:first").addClass("overlay"); } if ($("#wrapper").hasClass("menu-active")) { ...
Make the following, ``` <link rel="preload" href="path-to-your-script.js" as="script"> <script> var scriptPriority = document.createElement('script'); scriptPriority.src = 'path-to-your-script.js'; document.body.appendChild(scriptPriority); </script> ``` About: Link rel Preload Link rel preload is m...
3,382
71,461,517
We have just updated our jenkins (2.337) and the python console output has gone weird: [![enter image description here](https://i.stack.imgur.com/n2Yxn.png)](https://i.stack.imgur.com/n2Yxn.png) I've searched the jenkins settings (ANSI plugin etc) and I can change the inner colours but the gray background and line br...
2022/03/13
[ "https://Stackoverflow.com/questions/71461517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325752/" ]
We had a similar problem ... we had an almost Black Background with Black Text We found that the Extra CSS in the Theme section of the Jenkins Configuration has changed. After putting it through a code formatter (there are no new lines or whitespace in the field) we had the following for the console-output: ``` .con...
When you have broken console colors (black font on black screen) after jenkins update, * Go to Manage Jenkins -> configure system * scroll to theme * click add -> extra CSS put this in the new field: ``` .console-output{ color:#fff!important; } ``` You can also add any other CSS to please your eye.
3,383
14,081,949
How to turn off collisions for some objects and then again turn it on using pymunk lib in python? Let me show you the example, based on the code below. I want all red balls to go through first border of lines and stop on the lower border. Blue balls should still collide with upper border. What needs to be changed in...
2012/12/29
[ "https://Stackoverflow.com/questions/14081949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/789021/" ]
Chipmunk has a few options filtering collisions: <http://chipmunk-physics.net/release/ChipmunkLatest-Docs/#cpShape-Filtering> It sounds like you just need to use a layers bitmask though. ex: ``` # This layer bit is for balls colliding with other balls # I'm only guessing that you want this though. ball_layer = 1 # T...
In Pymunk you can use the [ShapeFilter](http://www.pymunk.org/en/latest/pymunk.html#pymunk.ShapeFilter) class to set the categories (layers) with which an object can collide. I put the upper and lower lines into the categories 1 and 2 and then set the masks of the balls so that they ignore these layers. You need to und...
3,384
44,705,385
I have this BT speaker , with in built mic , <http://www.intex.in/speakers/bluetooth-speakers/it-11s-bt> i want to build something like google home with it , using python .Please guide me.
2017/06/22
[ "https://Stackoverflow.com/questions/44705385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071763/" ]
Try with that : ``` function cari($d,$p) { $this->db->select('cf_pakar,gejala'); $this->db->from('gejalapenyakit'); $this->db->where('id_penyakit',$p); $this->db->where_in('id_gejala',$d); return $this->db->get()->result(); } ``` And your `$d = ('1','2','3','4','5')` should be `$d = ['1','2','3','4...
You need to send ',' seperated values in query. $d = implode(",",$d); This will work.
3,385
64,902,105
I have a requirement below but I am getting some error: Write a separate Privileges class. The class should have one attribute, privileges, that stores a list of strings.Move the show\_privileges() method to this class. Make a Privileges instance as an attribute in the Admin class. Create a new instance of Admin and u...
2020/11/18
[ "https://Stackoverflow.com/questions/64902105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14179096/" ]
As stated in the related questions, the easiest thing to do is to use an index instead as it requires no unsafe code. I might write it like this: ``` pub fn insert<'a, K: Eq, V>(this: &'a mut Vec<(K, V)>, key: K, val: V) -> &'a mut V { let idx = this .iter() .enumerate() .find_map(|(i, (k, ...
Safe alternative ---------------- Firstly, here is what I would suggest instead. You can iterate over the `Vec` once to get the index of the target value via `position(|x| x == y)`. You are then able to match the now owned value and continue like before. This should have very similar performance to your previous versi...
3,387
44,913,971
I'm coding a little python program for ROT13. If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'. A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front. This means I ne...
2017/07/04
[ "https://Stackoverflow.com/questions/44913971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7637737/" ]
[Vertically concatenate](https://www.mathworks.com/help/matlab/ref/vertcat.html) the matrices inside the cell arrays and use `intersect` with the [`'rows'`](https://www.mathworks.com/help/matlab/ref/intersect.html#btcnv0p-12) flag. i.e. ``` Q1={[1 2 3 4], [3 2 4 1], [4 2 1 3]}; Q2={[2 4 3 1], [1 2 3 4], [1 2 4 3]}; Q...
You can do it by using two loops and check all off them. ``` q1=[1 2 3 4; 3 2 4 1; 4 2 1 3]; q2=[2 4 3 1; 1 2 3 4; 1 2 4 3]; %find the size of matrix [m1,n1] = size(q1); [m2] = size(q2,1); for (ii=1:m1) for (jj=1:m2) %if segments are equal, it will return 1 %if sum of same segment = 4 it means t...
3,388
44,092,459
Undertaking a task to Write a function power that accepts two arguments, a and b and calculates a raised to the power b. Example ``` power(2, 3) => 8 ``` Note: Don't use ``` 2 ** 3 ``` and don't use ``` Math.pow(2, 3) ``` I have tried this ``` def power(a,b): return eval(((str(a)+"*")*b)[:-1]) ``` And ...
2017/05/21
[ "https://Stackoverflow.com/questions/44092459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173798/" ]
You can use a for loop ``` x=1 for i in range(b): x=x*a print(x) ```
``` def power(a, b): if b == 0: return 1 else: return a ** b ```
3,389
898,091
I have previously read Spolsky's article on character-encoding, as well as [this from dive into python 3](http://diveintopython3.org/strings.html). I know php is getting Unicode at some point, but I am having trouble understanding why this is such a big deal. If php-CLI is being used, ok it makes sense. However, in th...
2009/05/22
[ "https://Stackoverflow.com/questions/898091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Well, for one thing you need to somehow generate the strings the browser displays :-)
There's an awesome FAQ section on Unicode and the Web [here.](http://unicode.org/faq/unicode_web.html) See if it answers some of your questions.
3,394
42,512,141
I have written the following simple program which should print out all events detected by `pygame.event.get()`. ``` import pygame, sys from pygame.locals import * display = pygame.display.set_mode((300, 300)) pygame.init() while True: for event in pygame.event.get(): print(event) if event.type ==...
2017/02/28
[ "https://Stackoverflow.com/questions/42512141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4191155/" ]
If you're working in a virtualenv, don't use the `virtualenv` command. Use `python3 -m venv`. Then install pygame (*e.g.* `pip3 install hg+http://bitbucket.org/pygame/pygame`). See [this thread](https://bitbucket.org/pygame/pygame/issues/203/window-does-not-get-focus-on-os-x-with#comment-32656108) for more details o...
Firstly i doubt you are but pygame only registers inputs when your focused on the pygame screen so there's that. I don't have a direct answer to your question so sorry but i do have my solution or work around to it. Because i dislike the normal event system i use pygame.key.get\_pressed() (<https://www.pygame.org/docs/...
3,399
1,206,215
In python I can use os.getpid() and os.name() to get information about the Process ID and OS name. Is there something similar in C++? I tried GetProcessId() but was told that this is undeclared... I am using Cygwin under windows. Thank you
2009/07/30
[ "https://Stackoverflow.com/questions/1206215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Standard C++ has no such functionality. You need to use OS specific features to get this. In your case, you need to look up POSIX/UNIX functions such as [getpid()](http://www.opengroup.org/onlinepubs/009695399/functions/getpid.html). Note that if you actually do want to call the Windows functions to get process ID etc...
To use [GetProcessId](http://msdn.microsoft.com/en-us/library/ms683215(VS.85).aspx) you need to include Windows.h and link to Kernel32.lib. See [Process and Thread Functions](http://msdn.microsoft.com/en-us/library/ms684847(VS.85).aspx) for more information. I use [MSYS/mingw](http://www.mingw.org/) instead of [cygwin...
3,402
24,435,697
Python 3.4: From reading some other SO questions it seems that if a `moduleName.py` file is outside of your current directory, if you want to import it you must add it to the path with `sys.path.insert(0, '/path/to/application/app/folder')`, otherwise an `import moduelName` statement results in this error: ``` Import...
2014/06/26
[ "https://Stackoverflow.com/questions/24435697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3462076/" ]
Python adds the directory where the initial script resides as first item to [`sys.path`](https://docs.python.org/3/library/sys.html#sys.path): > > As initialized upon program startup, the first item of this list, `path[0]`, is the directory containing the script that was used to invoke the Python interpreter. If the ...
I have faced same problem when running python script from Intellij Idea. There is a script in a ``` C:\Users\user\IdeaProjects\Meshtastic-python\meshtastic ``` It uses ``` from meshtastic import portnums_pb2, channel_pb2, config_pb2 ``` and fails. I have realized that it looks for ``` C:\Users\user\IdeaProjects\...
3,405
29,333,578
From work i got a job to make a python script which will click for testing the product of a "secret application" for windows 8.1. The problem is that i can make it move the cursor but it can't click and i searched for win32 documentation on the internet but with no luck. Anyone who had this problem? This is the click ...
2015/03/29
[ "https://Stackoverflow.com/questions/29333578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2984950/" ]
`body` is a string. You have to parse it as JSON first: ``` res.json(JSON.parse(body)._links.self); ```
This question is little old, yet, the following also seems more helpful. In request, you can pass `json: true` and request library returns you the json object. replace following line, > > > ``` > request('https://api.twitch.tv/kraken/streams/' + req.params.user, function ( error, response, body) { > > ``` > > w...
3,406
12,578,943
I'm writing a program to get a video feed from a web cam and display it in a Tkinter window. I wrote the following code which I ran on Ubuntu 12.04. ``` #!/usr/bin/env python import sys, os, gobject from Tkinter import * import pygst pygst.require("0.10") import gst # Goto GUI Class class Prototype(Frame): def _...
2012/09/25
[ "https://Stackoverflow.com/questions/12578943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1696565/" ]
It looks like your Prototype class is a Tkinter Frame but you don't seem to have packed/placed it anywhere. ``` ... app = Prototype(root) app.pack(expand=YES, fill=BOTH) root.mainloop() ```
I finally came up with a solution to the question. I realised that the error was in the line imagesink.set\_xwindow\_id(self.movie\_window.window.xid) which I changed to imagesink.set\_xwindow\_id(self.movie\_window.winfo\_id()) The mistake is that I had used window.xid which is an attribute for gtk widgets. In tki...
3,407
28,422,787
Using python 3, how would you change this code to print the sum of all numbers from 1 to 20? ``` n = 20 i=0 sum = 0 for i in range (1,n+1): sum =+ i i = i+1 print(sum) ```
2015/02/10
[ "https://Stackoverflow.com/questions/28422787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4548170/" ]
The simplest way I can think about is: ``` sum(range(1, 21)) # includes 20 ``` You can also use a loop: ``` s = 0 for i in range(21): s += i ```
``` n = 20 # this isn't needed, the for loop sets i: i = 0 sum = 0 for i in range (1, n+1): sum += i # Remove this line: i = i+1 # for i in range already increments i print(sum) ``` You shouldn't use the variable name `sum` because there is already a builtin function `sum` which you can even use instead.
3,408
24,213,905
I have account in Openshift. I use Django and Mysql in this account. <https://github.com/ogurchik/pullover/tree/master/wsgi/openshift>. I created models for a new table in the Mysql database. When I execute the command `python manage.py sqlall MY_APP`, it renders this log: ``` BEGIN; CREATE TABLE `books_publisher` ( ...
2014/06/13
[ "https://Stackoverflow.com/questions/24213905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966342/" ]
Correct. The timestamp is a UNIX timestamp. That is - the number of whole seconds since Jan 1, 1970 UTC, not accounting for leap seconds. You can verify the timestamp using a site like [epochconverter.com](http://www.epochconverter.com/) ``` 1388613600 = 2014-01-01T22:00:00Z ``` Then you can check the time zone det...
As Marc B mentioned, `date('r', 1388613600)` returned a formatted version of the date including the timezone offset which was set to `+0000`. The output is in fact UTC. Thanks Marc!
3,409
32,046,360
I'm using wxpython with wx.Grid... I have a general grid with many columns -created with `SetColumn(self, column)` , I want to be able to show and hide specific columns based on user security permission. I read that `self.SetColMinimalAcceptableWidth(0)` might be useful? How do I use it on specific column? How do I re...
2015/08/17
[ "https://Stackoverflow.com/questions/32046360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2131325/" ]
The Grid manual has the following entry: HideCol(self, col) ``` Hides the specified column. To show the column later you need to call SetColSize with non-0 width or ShowCol to restore the previous column width. If the column is already hidden, this method doesn’t do anything. Parameters: col (int) – The column ind...
Under wxPython 2.8: ``` grid.SetColMinimalAcceptableWidth(0) grid.SetColSize(col, 0) grid.ForceRefresh() ```
3,410
15,904,973
Say i store a password in plain text in a variable called `passWd` as a string. How does python release this variable once i discard of it (for instance, with `del passWd` or `passWd= 'new random data'`)? Is the string stored as a byte-array meaning it can be overwritten in the memoryplace that it originally existed o...
2013/04/09
[ "https://Stackoverflow.com/questions/15904973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/929999/" ]
Unless you use custom coded input methods to get the password, it will be in many more places then just your immutable string. So don't worry too much. The OS should take care that any data from your process is cleared before the memory is allocated to another process. This may of course fail if the page is copied to ...
I finally whent with two solutions. ld\_preload to replace the functionality of the string handling of Python on a lower level. One other option which is a bit easier was to develop my own C library that has more functionality then what Python offers through the standard string handling. Mainly the C code has a shread...
3,411
3,422,775
I have written a small Django App, that executes an interactive program based on user input and returns the output as the result. But for some reason, the subprocess hangs. On verification of the logs I found that a place where a '\n' has to be given as response to a challenge, the response seems to have never been mad...
2010/08/06
[ "https://Stackoverflow.com/questions/3422775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/412888/" ]
This is because code is JITted on a per-method basis, so when you first try to invoke `CheckCrystal()`, .NET first tries to compile it, subsequently loading all required and not-yet-loaded assemblies. .NET allows you to intercept a moment when assembly resolution fails. To do so, subscribe to `AppDomain.AssemblyResolv...
You would probably want to handle the `AppDomain.AssemblyResolve` event. More information [here](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve(VS.71).aspx). A quick and dirty example: ``` AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; private static Assembly Cu...
3,412
65,942,206
![My code](https://i.stack.imgur.com/QMrBx.png) ![the output](https://i.stack.imgur.com/r5kqL.png) can anyone help me? im pretty new to python and im trying to generate 10 files, each with increasingly harder questions. this code is for difficult 2. I dont want the answers in dif. 2 to be negative so whenever i get a...
2021/01/28
[ "https://Stackoverflow.com/questions/65942206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15100687/" ]
Your issue is that you're casting your random numbers to a string **before** comparing their mathematical values. You need to compare them as integers then cast them to strings.
I believe this is because you are checking for comparison between 2 strings not 2 integers. This will give bad results for this type of program num1 = str(r.choice(numbers)) num2 = str(r.choice(numbers)) Here you are storing strings and not integers. and then below this you are checking if num1 <= num2. Convert them...
3,414
38,657,109
I am using *Python 3.4*. I have a Python script `myscript.py` : ``` import sys def returnvalue(str) : if str == "hi" : return "yes" else : return "no" print("calling python function with parameters:") print(sys.argv[1]) str = sys.argv[1] res = returnvalue(str) target = open("file.txt", 'w') ta...
2016/07/29
[ "https://Stackoverflow.com/questions/38657109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013429/" ]
Have you looked at these? They suggest different ways of doing this: [Call Python code from Java by passing parameters and results](https://stackoverflow.com/questions/27235286/call-python-code-from-java-by-passing-parameters-and-results) [How to call a python method from a java class?](https://stackoverflow.com/ques...
calling python from java with Argument and print python output in java console can be done with below simple method: ``` String pathPython = "pathtopython\\script.py"; String [] cmd = new String[3]; cmd[0] = "python"; cmd[1] = pathPython; cmd[2] = arg1; Runtime r = Runtime.getRuntime(); Process p = r.exec(cmd); Buffer...
3,415
50,268,691
I am trying to train my binary classifier over a huge data. Previously, I could accomplish training via using fit method of sklearn. But now, I have more data and I cannot cope with them. I am trying to fitting them partially but couldn't get rid of errors. How can I train my huge data incrementally? With applying my p...
2018/05/10
[ "https://Stackoverflow.com/questions/50268691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9079119/" ]
A `Pipeline` object from scikit-learn does not have the `partial_fit`, as seen in [the docs](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html). The reason for this is that you can add any estimator you want to that `Pipeline` object, and not all of them implement the `partial_fit`. [Here...
I was going through the same problem as `SGDClassifier` inside pipeline doesn't support the incremental learning (i.e. partial\_fit param). There is a way we could do incremental learning using sklearn but it is not with `partial_fit`, it is with `warm_start`. There are two algorithms in sklearn `LogisticRegression` an...
3,417
15,930,203
I am using **zbarimg** to scan bar codes, I want to redirect the output to a python script. How can I redirect the output of the following command: ``` zbarimg code.png ``` to a python script, and what should be the script like? I tried the following script: ``` #!/usr/local/bin/python s = raw_input() print s ```...
2013/04/10
[ "https://Stackoverflow.com/questions/15930203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1251851/" ]
Using the pipe operator `|` from the command is correct, actually. Did it not work? You might need to explicitly specify the path for the python script as in ``` zbarimg code.png | ./in.py ``` and as @dogbane says, reading from stdin like `sys.stdin.readlines()` is better than using `raw_input`
Use [`sys.stdin`](http://docs.python.org/2/library/sys.html#sys.stdin) to read from stdin in your python script. For example: ``` import sys data = sys.stdin.readlines() ```
3,420
45,430,966
why are function considered data type in lua? you can assign functions to variables and pass them as arguments in python too but there is no function data type in python.
2017/08/01
[ "https://Stackoverflow.com/questions/45430966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4931135/" ]
I think you are mistaken. If you take a look into <https://docs.python.org/2/reference/datamodel.html#types> You'll find that Python even has multiple function types. Callable types: * user defined function * user defined methods * generator functions * built-in functions * built-in methods * ... There are further...
Python does actually have a function type, its just called `lambda`. In both of these programming languages, functions are first-class values which is just a fancy way of saying you can pass them around to functions just like numbers or strings. It makes it possible to use [functional programming](https://en.wikipedia....
3,422
53,863,318
First, I was able to fix the ImportError. I figured out that it was because the Django version of pythonanywhere is not updated, So I upgraded Django on pythonanywhere from 1.x.x to 2.0.9. The error came out like this: > > ImportError at / > cannot import name 'path' > > > ``` django version: 1.x.x python versi...
2018/12/20
[ "https://Stackoverflow.com/questions/53863318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10665552/" ]
The problem as I see has to be with the database and django migrations. The `Post` object inside the blog has the attribute that django's trying to find. The migrations haven't been correctly applied to the database. Now considering the history of migrations, I do not know what's going wrong unless I can look aroun...
Don't forget to refresh your production server after every migration if you want the changes to take effect
3,423
11,226,252
Is there a way to loop in `while` if you start the script with `python -c`? This doesn't seem to be related to platform or python version... **Linux** ``` [mpenning@Hotcoffee ~]$ python -c "import os;while (True): os.system('ls')" File "<string>", line 1 import os;while (True): os.system('ls') ...
2012/06/27
[ "https://Stackoverflow.com/questions/11226252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/667301/" ]
Multiline statements may not start after a statement-separating `;` in Python – otherwise, there might be ambiguities about the code blocks. Simply use line breaks in stead of `;`. This "works" on Linux: ``` $ python -c "import os while True: os.system('ls')" ``` Not sure how to enter this on Windows, but why not si...
Don't know about windows, if all you want is to be able to type in one-liners, you could consider line breaks inside quotes: ``` % python -c "import os; while (True): os.system('ls')" ```
3,424
52,119,496
I am trying to write code to solve this python exercise: **I must use** the 'math' library, sqrt and possibly pow functions. > > "The distance between two points x and y is the square root of the sum > of squared differences along each dimension of x and y. > > > "Create a function that takes two vectors and out...
2018/08/31
[ "https://Stackoverflow.com/questions/52119496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10265759/" ]
``` import math def distance (x,y): value= math.sqrt ((x[0]-y[0])**2 + (x[1] - y[1])**2) print (value) distance((0,0), (1,1)) ```
Thanks so much for those ideas! I figured it out. So happy. ``` for (a,b) in x,y: dis = math.sqrt((y[0] - x[0])**2 + (y[1] - x[1])**2) print(dis) ```
3,429
64,260,105
I want to read all parquet files from an S3 bucket, including all those in the subdirectories (these are actually prefixes). Using wildcards (\*) in the S3 url only works for the files in the specified folder. For example using this code will only read the parquet files below the `target/` folder. ``` df = spark.read...
2020/10/08
[ "https://Stackoverflow.com/questions/64260105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1771155/" ]
If you want to read all parquet files below the target folder ``` "s3://bucket/target/2020/01/01/some-file.parquet" "s3://bucket/target/2020/01/02/some-file.parquet" ``` you can do ``` df = spark.read.parquet("bucket/target/*/*/*/*.parquet") ``` The downside is that you need to know the depth of your parquet file...
This worked for me: ``` df = spark.read.parquet("s3://your/path/here/some*wildcard") ```
3,431
40,446,084
Running Selenium locally on flask. Im using the PhantomJS driver. I previously had a path error: ``` selenium.common.exceptions.WebDriverException: Message: 'phantomjs' executable needs to be in PATH. ``` But after finding out from another StackOverflow question, I learned that I have to pass the environment path a...
2016/11/06
[ "https://Stackoverflow.com/questions/40446084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7121239/" ]
I think the true reason for you problem is that: **The phantomjs which webdrive needs is not the one under `selenium/webdriver` fold**. When you use anaconda to install this package, it's really confusing (at least for me). * First install it with `conda install -c conda-forge phantomjs`, test it with `phantomjs --ver...
Strangely, for me it was fixed by putting phantomjs in `/usr/local/share` and adding some symbolic links. I followed [these steps](https://stackoverflow.com/questions/8778513/how-can-i-setup-run-phantomjs-on-ubuntu): * move the phantomjs folder to `/usr/local/share/`: + `sudo mv phantomjs-2.1.1-linux-x86_64.tar.bz2 /...
3,432
58,460,780
**using python 3.7** Hi. I am trying to get the the selected treeview item and want to print it once i click left menu item. This is my treeview list. When I right click a menu appeas with stop process command. I am trying to get the selected item and print it but its giving me error ``` AttributeError: 'str' object...
2019/10/19
[ "https://Stackoverflow.com/questions/58460780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12241800/" ]
No, there is nothing like that, but there are tools, that try to mimic this behavior, for example lombok. Using `@Data` annotation we're getting default constructor, getters, setters, `toString`, `equals`, `hashCode`. We can fine-tune it by using annotations like `@Getter`, `@NoArgsConstructor` etc.
Neither Java nor Kotlin have anything similar to those Swift types you are talking about. Assignment *always* copies references to an object, rather than the object itself. What Kotlin's data classes do is that they create a `copy` method (among other things) that allows you to explicitly make a copy of an object, but ...
3,442
29,943,146
I am new to python, trying to port a script in 2.x to 3.x i am encountering the error TypeError; Must use key word argument or key function in python 3.x. Below is the piece of code: Please help ``` def resort_working_array( self, chosen_values_arr, num ): for item in self.__working_arr[num]: data_node = s...
2015/04/29
[ "https://Stackoverflow.com/questions/29943146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4846265/" ]
Looks like the problem is in this line. ``` self.__working_arr[num].sort( key = lambda a,b: cmp(a.weights, b.weights) ) ``` The `key` callable should take only one argument. Try: ``` self.__working_arr[num].sort(key = lambda a: a.weights) ```
The exact same error message appears if you try to pass the *key* parameter as a positional parameter. Wrong: ``` sort(lst, myKeyFunction) ``` Correct: ``` sort(lst, key=myKeyFunction) ``` Python 3.6.6
3,444
64,620,456
I'm a beginner in python and I want to use comprehension to create a dictionary. Let's say I have the below two list and want to convert them to a dictionary like `{'Key 1':['c','d'], 'Key 2':['a','f'], 'Key 3':['b','e']}`. I can only think of the code below and I don't know how to change the value of the key and the f...
2020/10/31
[ "https://Stackoverflow.com/questions/64620456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This should do it: ``` value = ['a','b','c','d','e','f'] key = [2, 3, 1, 1, 3, 2] answer = {} for k, v in zip(key, value): if k in answer: answer[k].append(v) else: answer[k] = [v] print(answer) {2: ['a', 'f'], 3: ['b', 'e'], 1: ['c', 'd']} ``` EDIT: oops, jumped the gun. Apologies. Here's...
You could do it with dictionary comprehension *and* list comprehension: ``` {f"Key {k}" : [value for key,value in zip(key,value) if key == k] for k in key} ``` Your lists would yield the following: ``` {'Key 2': ['a', 'f'], 'Key 3': ['b', 'e'], 'Key 1': ['c', 'd']} ``` As requested.
3,447
35,697,643
I have a `Frame` with two columns of `String`, ``` let first = Series.ofValues(["a";"b";"c"]) let second = Series.ofValues(["d";"e";"f"]) let df = Frame(["first"; "second"], [first; second]) ``` How do I produce a third column as the concatenation of the two columns? In `python` `pandas`, this can be achieved with...
2016/02/29
[ "https://Stackoverflow.com/questions/35697643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569058/" ]
It sounds like what you want is to have something that returns something like: ``` Series.ofValues(["ad"; "be"; "cf"]) ``` Then I think you need to define an addition operator with something like this: ``` let additionOperator = (fun (a:string) (b:string) -> (a + b)) ``` And then you can add them like this: ``` ...
I come across this after facing the same issue, the trick is to get the values as seq and use Seq.map2 to concat the two seqs, my solution is ``` let first = Series.ofValues(["a";"b";"c"]) let second = Series.ofValues(["d";"e";"f"]) let df = Seq.map2 (fun x y -> x+y) first.Values second.Values |> Series.ofVal...
3,452
62,030,549
I have a directory filled with '.tbl' files. The file set up is as follows: \STAR\_ID = "HD 74156" \DATA\_CATEGORY = "Planet Radial Velocity Curve" \NUMBER\_OF\_POINTS = "82" \TIME\_REFERENCE\_FRAME = "JD" \MINIMUM\_DATE = "2453342.23249" \DATE\_UNITS = "days" \MAXIMUM\_DATE = "2454231.60002" .... I need to re...
2020/05/26
[ "https://Stackoverflow.com/questions/62030549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13622725/" ]
This error occurs because of `first_line.split('"')` is returning a list with less of 2 items. you can try ``` first_line_ls = first_line.split('"') if len(first_line_ls) > 1: system = first_line_ls[1] else: #other method ``` This code can help you prevent the error and handle cases the file\_line str hav...
It looks like these `.tbl` files are not as uniform as you might have hoped. If this line: ``` ----> 5 system = first_line.split('"')[1] ``` fails on some files, it's because their first line is not formatted as you expected, as @Leo Arad noted. You also want to make sure you're *actually* using the `STAR_ID...
3,455
48,675,435
In a personal project, I am trying to use Django as my front end and then allow data entered by users in a particular form to be copied to google sheets. Google's own docs recommend using <https://github.com/google/oauth2client> which is now deprecated, and the docs have not been updated. With this, I have started att...
2018/02/08
[ "https://Stackoverflow.com/questions/48675435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6883167/" ]
It's true that `python-social-auth` will use some bits of the Google+ platform, at least the API to retrieve details about the user to fill in the account. From your settings, I see you have `associate_by_email` at the bottom, at that point, at that point it has no use since the user is already be created, if you real...
Just provide this in your `settings.py`: `SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'hd': 'xyzabc.com', 'approval_prompt':'force' }` remeber there is `{'approval_prompt' : 'force'}` which will force the user to select the gmail account, this way you will get refresh token.
3,456
67,519,212
I have written a simple caesar cipher code to take a string and a positional shift argument i.e cipher to encrypt the string. However, I have realized some of the outputs won't decrypt correctly. For example: `python .\caesar_cipher.py 'fortuna' 6771 --encrypt` outputs `☼↑↔▲↨` `python .\caesar_cipher.py '☼↑↔▲↨' 67...
2021/05/13
[ "https://Stackoverflow.com/questions/67519212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9169087/" ]
I think the problem is after the encryption in copy and pasting the value. When I tested this code, what I found and you mentioned that too, directly transferring the encrypted value to the decrypt function by storing in a variable, doesn't cause any problem, but when directly pasting it is causing problem. To overcom...
As @KnowledgeGainer mentioned, there is no problem with your code. The issue arises because you copied the output of your encryption from the terminal, and used that as your input for decryption. The terminal you're using is trying its best to interpret some potential non-printable control characters - `fortuna` has se...
3,459
34,284,737
This is a part of my code for a hangman game. it is used for all four difficulties, but when it is used on my "insane" difficulty (which uses words from a word file) it adds an extra symbol to the end of the word meaning you can't win the game. it does this for every word in the .txt file. This code works when using an...
2015/12/15
[ "https://Stackoverflow.com/questions/34284737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653652/" ]
You have a `\n` at the end of every word. You should strip the word of the `\n` before adding it: ``` INSANEWORDS = open("create.txt", "r+") words = [] for item in INSANEWORDS: words.append(item.strip('\n')) ``` **Before:** [![enter image description here](https://i.stack.imgur.com/d6mOJ.png)](https://i.stack.i...
If my guess is correct when you are reading a line from your text file you also reading the new line character **\n** at the end of the word, which you can remove using: ``` word = word.strip('\n') ```
3,461
10,589,933
I've been trying to learn python recently, and ran across something that I'm having a hard time understanding exactly how it works. Primarily, it is the design of a list. The list in question is from this security article talking about a simple fuzzing tool: <http://blog.securestate.com/post/2009/10/06/How-a-simple-py...
2012/05/14
[ "https://Stackoverflow.com/questions/10589933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1298775/" ]
This ``` """ 00 00 00 90 ff 53 4d 42 72 00 00 00 00 18 53 c8 00 00 00 00 00 00 00 00 00 00 00 00 ff ff ff fe 00 00 00 00 00 6d 00 02 50 43 20 4e 45 54 57 4f 52 4b 20 50 52 4f 47 52 41 4d 20 31 2e 30 00 02 4c 41 4e 4d 41 4e 31 2e 30 00 02 57 69 6e 64 6f 77 73 20 66 6f 72 20 57 6f 72 6b 67 72 6f 75 70 73 20 33 2e 31 61 ...
The ``` """ content """ ``` format is a simple way to define multiline string literals in python. This is **not** a comment block. The `[chr(int(a, 16)) for a in "00 00 00...".split()]` is a list comprehension. The large string is split into an array (split by spaces), and for each item in the array, it convert...
3,462
36,461,925
I am not even sure how to word my question due to me being quite new to python. The basic concept of what I want to accomplish is to be able to search for something in a 2D array and retrieve the right value as well as the values associated with that value (sorry for my bad explanation) e.g. `array=[[1,a,b],[2,x,d],...
2016/04/06
[ "https://Stackoverflow.com/questions/36461925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6168984/" ]
I am not sure if I understood the question correctly, but from what I got, I think you can create a model instance with initial values (place holders), and allow your component to initialise with this model, and then, when your data is ready, change the model instance values, which will reflect to your component. This...
What version of Angular are you with? Not sure if you're copy-pasting the redacted code, but it seems as if you're missing the `implements` keyword there in your Class. `*ngIf` works good in this [plunker](https://plnkr.co/edit/jXsRvHZ33A1KrRxROGAK?p=preview). From what I gather, something like \*ngIf is the proper w...
3,471
39,816,500
I've recently began work on a Python program as seen in the fragment below. ``` # General Variables running = False new = True timeStart = 0.0 timeElapsed = 0.0 def endProg(): curses.nocbreak() stdscr.keypad(False) curses.echo() curses.endwin() quit() # Draw def draw(): stdscr.addstr(1, 1, ">...
2016/10/02
[ "https://Stackoverflow.com/questions/39816500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6911375/" ]
Install mocha and its types: ```sh npm install mocha --save-dev npm install @types/mocha --save-dev ``` Then, simply import mocha in your test files: ```js import 'mocha'; describe('my test', () => { it('does something', () => { // your test }); }); ```
Since TypeScript 2.0, you can add `mocha` to the `types` configuration of your `tsconfig.json` and it will always be loaded: ``` { "compilerOptions": { "types": [ "mocha" ] } } ```
3,474
34,756,978
I am trying to download py2exe but every time that run the setup program it says "no python installation found in registry" but I have downloaded python 3.4 and have it on my computer working? please help. I'm using a 64 bit computer with the 64 bit py2exe, I downloaded python from the python website. And i'm on windo...
2016/01/13
[ "https://Stackoverflow.com/questions/34756978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5781821/" ]
Try to use [cx\_Freeze](https://pypi.python.org/pypi/cx_Freeze) instead py2exe.
I assume that you have installed everything properly. In your install settings you can choose if you want to assign the **system variable** python.as you can see from the [point 3.3 of the documentation](https://docs.python.org/3.4/using/windows.html#configuring-python), you should: > > 3.3.1. Excursus: Setting envir...
3,477
31,256,397
I have data of the following form: ``` #@ <abc> <http://stackoverflow.com/questions/ask> <question> _:question1 . #@ <def> <The> <second> <http://line> . #@ <ghi> _:question1 <http#responseCode> "200"^^<http://integer> . #@ <klm> <The> <second> <http://line1.xml> . #@ <nop> _:question1 <date> "Mon, 23 Apr 2012 13:4...
2015/07/06
[ "https://Stackoverflow.com/questions/31256397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4360034/" ]
Keep a boolean hashtable of hash codes of lines already seen. For each line: * if line hash()es to something you have already seen, you have a potential match: scan the file to check if it really is a duplicate. * if line hash()es to a new hash, just mark the hash for the first time. Dedicate as much memory you can ...
One fairly straightforward way - make a version of your data such that each line includes a field with its line number. Use unix 'sort' to sort that new file, excluding the line number field. The sort utility will merge sort the file even if it exceeds the size of available memory. Now you have a new file in which the ...
3,478
48,964,181
I am currently trying to load a pickled file from S3 into AWS lambda and store it to a list (the pickle is a list). Here is my code: ``` import pickle import boto3 s3 = boto3.resource('s3') with open('oldscreenurls.pkl', 'rb') as data: old_list = s3.Bucket("pythonpickles").download_fileobj("oldscreenurls.pkl", d...
2018/02/24
[ "https://Stackoverflow.com/questions/48964181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6327717/" ]
Super simple solution ```py import pickle import boto3 s3 = boto3.resource('s3') my_pickle = pickle.loads(s3.Bucket("bucket_name").Object("key_to_pickle.pickle").get()['Body'].read()) ```
As shown in the documentation for [`download_fileobj`](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.download_fileobj), you need to open the file in binary *write* mode and save to the file first. Once the file is downloaded, you can open it for reading and unpickle. ``` import pickle impo...
3,480
66,144,386
I have a large list of numbers (4,718,515 of them) and I need to run a method with each of them. I have a method `Check(number)` that needs to be ran with the items in `numbers`. I don't know the most efficient way to go about this in c# Here are some examples of how I was able to do it in other languages if it helps...
2021/02/10
[ "https://Stackoverflow.com/questions/66144386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10252192/" ]
There should not be any joining since the information is available in that table. Instead of selecting all the columns you can select only DebtAccountReferences as required. ``` select DebtAccountReferences from DebtPayment_DL where PaymentStartDate > '01/01/2021' and CloseDate is null; ```
Based on the information you have given, you do not need a join statement. All of the information you need is stored in the table 'DebtPayment\_DL' Your code is therefore correct and should generate the correct output.
3,486
21,361,281
I'm trying to modify a list in a tuple, the `append` method works, while `+=` operator works yet with an exception raised saying tuple could not be modified. I know a tuple is immutable, but I'm not trying to mutate it. Why this happen? ``` In [36]: t=([1,2],) In [37]: t[0].append(123) In [38]: t Out[38]: ([1, 2, 12...
2014/01/26
[ "https://Stackoverflow.com/questions/21361281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150712/" ]
Because `t[0] += [4,5,]` is interpreted as: ``` t[0] = t[0].__iadd__([4,5,]) ``` `t[0]__iadd__([4,5])` succeed, while `t[0] = ..` fail. --- `list.__iadd__` extend the list, and return itself. ``` >>> lst = [0] >>> lst2 = lst.__iadd__([1]) >>> lst [0, 1] >>> lst2 [0, 1] >>> lst is lst2 True ```
In fact you **do** change the tuple: The `+` operator for lists creates a new list and you try to mutate your tuple by replacing the old list by the new one. `append`modifies the list in the tuple, therefore it works.
3,487
50,314,242
I want to save floating-point numbers as pixels in an image file. I am currently working in OpenCV-python, but I had also tried it with Pillow (PIL). Both packages convert `float` pixel data to integer before writing them to the file. I want to save pixel values such as: ```none (245.7865, 123.18788, 98.9866) ``` B...
2018/05/13
[ "https://Stackoverflow.com/questions/50314242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5256558/" ]
Most likely your are looking for: ``` lapply(seq_along(x), function(i){ quantile(x[1:i], probs = 0.95) }) ``` for each index `i` in `x`, subset `x` from `1` to `i` and return `quantile`. The output will be a list, you can convert it to vector: ``` unlist(lapply(seq_along(x), function(i){ quantile(x[1:i], probs...
Using `rollapply` would be something like the following. ``` library(xts) rollapply(x[, "random"], width = list(seq(-length(x[, "random"]), 0)), FUN = quantile, probs = 0.95, partial = 0) ```
3,492
68,873,535
I've a large MPEG (.ts) Binary file, usually a multiple of 188 bytes, I use python3,when I read 188 byte each time and parse to get required value, I found it really slow. I must traverse through each 188 bytes packet to get the value of the PID (binary data). * On the same time when I use any MPEG offline professiona...
2021/08/21
[ "https://Stackoverflow.com/questions/68873535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8014376/" ]
It's already been copied. A `c_char_p` return is automatically converted to an immutable Python `bytes` object. If the return type was `POINTER(c_char)` *then* you would have a pointer to the actual memory. Sometimes you need the explicit type if you need to pass that pointer to a function to free the memory later. A ...
`c_char_p` by default returns bytes object. So it will print with `b'` bytes. If need to print as string, we can do with `.decode('utf-8')` **Example:** ``` print(b2) # prints b'hello, world!' as bytes print(b2.decode('utf-8')) # prints 'hello, world!' as string ```
3,494
38,736,872
I am trying to understand more about `__iter__` in Python 3. For some reason `__getitem__` is better understood by me than `__iter__`. I think I get somehow don't get the corresponding **next** implemention followed with `__iter__`. I have this following code: ``` class Item: def __getitem__(self,pos): re...
2016/08/03
[ "https://Stackoverflow.com/questions/38736872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2126725/" ]
In general, a really good approach is to make `__iter__` a generator by `yield`ing values. This might be *less* intuitive but it is straight-forward; you just yield back the results you want and `__next__` is then provided automatically for you: ``` class Item: def __iter__(self): for item in range(0, 30, 10)...
Iter returns a iterator, mainly a generator as @machineyearning told at the comments, with next you can iterate over the object, see the example: ``` class Item: def __init__(self): self.elems = range(10) self.current = 0 def __iter__(self): return (x for x in self.elems) def __...
3,495
68,019,978
I am building an Ada boost model with Sklearn. Last year I made the same model with the same data, and I was able to access the feature importances. This year when I build the model with the same data the feature importance attribute contains NaNs.I have read some other stuff where people have has the same problem and ...
2021/06/17
[ "https://Stackoverflow.com/questions/68019978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8684167/" ]
Make an AJAX call to the specific endpoint and update the DOM accordingly.
Laravel is A PHP framework, PHP framework, PHP request data from server and return to client in which it must refresh the page. To archive interchange of data you have few option. **option one** use jquery ajax, it works well and fine with laravel and bootsrtap. Get started [here](https://jquery.com/) on offical websi...
3,496
50,735,626
Am trying to make a simple post api in flask-python but am getting this error : ``` TypeError: list object is not an iterator ``` but when i revise my code seems fine what could be the problem. My function which specifically has the problem: ``` def post(self,name): #return {'message': name} item =...
2018/06/07
[ "https://Stackoverflow.com/questions/50735626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6687699/" ]
Try using `iter()` **Ex:** ``` item = next(iter(filter(lambda x: x['name'] == name, items)), None) ```
To elaborate on @Rakesh's answer, lists aren't iterators, and the output of `filter()` in Python 2 is a list. To fix this, you can use the `iter()` function to output an iterator corresponding to the problematic list so that `next()` can be called appropriately. The same code then should solve your problem: ``` item =...
3,497
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
No, 3.x is largely incompatible with 2.x (that was actually a major motivation for doing it). In fact, you probably shouldn't be using 3.0 at all-- it's rather unusable at the moment, and is still mostly intended for library developers to port to it so that it can be usable.
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
3,498