dimanche 31 juillet 2016

How to send automatic email notification by checking with date in odoo

I have a calendar module there I have fields like start date and end date. I want to sent an email if the current date is more that end date of calendar to attendees of calendar module i.e calendar.event. Any ideas how this can be done?

Python: Given a link, how to save locally if the link is an image and do not save if it is not an image?

I am currently using

import urllib

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

Is there a way to see if the link contains a pic or not, if not then no need to download, if so, then download.

Thanks!

How to Python prettyprint a JSON file

I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work.

Find the maximum sum of list values in dictionary

I need help trying to find the student who has the highest total scores.

s1= {'A': [100, 95, 100], 'B': [100, 100, 100], 'C': [95, 95, 80], 'D': [100, 100, 80]}
def wrtd2():
  for k, v in s1.iteritems():
     total = 0
     for i in v:
      total = total + i
     print total

wrtd2()

But it is printing the total for all students.

How to compare one employee to all employees salary in django model?

emp = Employee.objects.filter(id=1)

Persons =  Employee.objects.extra(select={'difference':(emp.values_list("Salary",flat=True)[0]-float('Salary'))})

But it give Error :

Exception Type: ValueError

Exception Value:could not convert string to float: 'Salary'.

How can i solve this Error.

How can I tell whether my Django application is running on development server or not?

How can I be certain that my application is running on development server or not? I suppose I could check value of settings.DEBUG and assume if DEBUG is True then it's running on development server, but I'd prefer to know for sure than relying on convention.

Find numpy array values bounding an input value

I have a value, say 2016 and a numpy array: [2005, 2010, 2015, 2020, 2025, 2030]. What is the pythonic way to find the 2 values in the array that bound 2016. In this case, the answer will be an array [2015, 2020].

Not sure how to do it other than loop, but hoping for a more numpy based solution

How to read a binary file of type complex64 values in Python

I have a binary file that contains several complex numbers of type complex64? (i.e. four bytes of type float for the real part and another four bytes for the imaginary part). The real and imaginary parts are multiplexed so that the real part is stored first and followed by the imaginary part.

Jquery Append or Insert Text After Specific Words

How to append word "THIRD" after these two words "FIRST SECOND" but before word "FOURTH".

This appends after "FOURTH": https://jsfiddle.net/bagn96ee/

<p id="para">FIRST SECOND FOURTH</p>
$('#para').append('THIRD');

how to avoid simple quote in MySQLdb python

How to avoid simple quotes when I pass two variables into the query

import sys

first_arg = sys.argv[1]
second_arg = sys.argv[2]



with con:
        def alter (var1=first_arg, var2=second_arg):
                cur = con.cursor()
                cur.execute("alter table joinit ALTER s SET DEFAULT 'TEST', ALGORITHM = %s, LOCK = %s", (var1,var2))

E-mail my g-mail contacts with python

Is it possible to have a python script which uses my already logged in gmail(via chrome) to send an email to all of my contacts? And also is it be possible to attach a file to the email?

I wouldn't be surprised if this isn't possible but I thought I would ask anyway.

How to organize a relatively large Flask application?

I'm building my first Flask app and I can't figure out a good, clean Pythonic way of organizing my application. I don't want to have everything in a single .py file as in their example. I would like to have each part of my app in a separate module. What would be a good way to organize things?

How can I get a parent window's height from within iFrame using jQuery?

Within an iFrame, we need to get the parent's window/document height.

Is there a way to get this using jQuery?

I know we can use $(document).height() to get a page's height. I just can't figure out how to get the parent's value from within the iFrame.

Please help!

Are there default icons in PyQt/PySide?

I'm reading a tutorial on PySide and I was thinking , do I need to find my own icons for every thing or is there some way to use some built in icons . That way I wouldn't need to find an entire new set of icons if I want my little gui to run on another desktop environment .

how can i make click enabled at owl-carousel slider?

enter image description here

I customize jQuery owl-carousel and make this slider.Now i want to add another options. The option is when I clicked any images then it have to go center.

Get value from jquery object

I want to get value of description from jQuery object. my object something like this. enter image description here

I am using JSON.parse but with this, I am getting undefined.

what's the typeof(jQuery)

i just tried this code console.log(typeof(jQuery)) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> It alerts function, which means the typeof jQuery is function. My question is, what's the exact type of jQuery? If it's function, how come it has properties like jQuery.browser and jQuery.ajax?

Fixed seed random number between 0 and 1

I want to generate list of fixed random numbers by giving a seed between 0 and 1 in python. For example, l = [0.1, 0.5, 0.6, 0.9, 0.75]. I can get this by using random.random(). But every time it gives a new random number list. I want to fix it by giving some some seed.

How can I do that. Thanks in advance!

matplotlib 2D slice of 3D data

I haven't been able to find anything on this, maybe because I don't have the right nomenclature (i.e. I don't know exactly how to ask for it), but anyway, I have a 3D numpy array "a". I would like to identify and plot the 2D surface where a=0. Does matplotlib have a ready-made routine for doing this?

TD/IDF in scikit-learn

Is there a complete Python 2.7 example about how to use TfidfTransformer (http://scikit-learn.org/stable/modules/feature_extraction.html) to generate TF/IDF for n-grams for a corpus? Look around scikit-learn pages and it only have code snippet (not complete samples).

regards, Lin

Disable Esc close for colorbox

I'm using the colorbox plugin for jQuery.

I know I don't have to have a close button, and overlayClose: false will prevent the window from being closed by clicking the overlay.

Is there a way to remove the Esc key-listener event?

Trying to assign values to keys in dictionary gives type error

dict["north-west"]=(south+width_NS,west) TypeError: 'type' object does not support item assignment class Building: def __init__(self, south, west, width_WE, width_NS, height=10): keys=("north-west","north-east","south-west","south-east") dict.fromkeys(keys) dict['north-west']=(south+width_NS,west) dict["north-east"]=(south+width_NS,west+width_WE) dict["south-west"]=(south,west) dict["south-east"]=(south,west+width_WE) self.corners=dict

JQuery and JavaScript methods

In majority of JavaScript method(iterator) callback first argument is element and second is index. But in case of jQuery always second argument is element and first one is index. Why they formatted differently? Is that for avoiding confusion between them, since both contains methods like map, filter, etc. Is there any special meaning behind that? I'm just curious to know.

In getorgchart jquery plugin how to remove the getorgchart hyperlink present at the bottom of the screen

I am trying to use getorgchart jquery plugin. And I want to remove the 'GetOrgChart' hyprlink which is showing in the bottom of the screen. I have tried removing it from getorgchart.js file but it is still showing up. Is it part of the theme? How Can I stop showig it on my webpage???

Please help..

samedi 30 juillet 2016

What is the difference between "window.location.href" and "window.location.hash"?

I learned "window.location.hash" new and tried in my jquery code instead of "window.location.href" and both of them gave same results.

Code is here :

window.location.href = ($(e.currentTarget).attr("href"));
window.location.hash = ($(e.currentTarget).attr("href"));

What is the difference between them?

Form a big 2d array from multiple smaller 2d arrays

The question is the inverse of this question. I'm looking for a generic method to from the original big array from small arrays:

array([[[ 0,  1,  2],
        [ 6,  7,  8]],    
       [[ 3,  4,  5],
        [ 9, 10, 11]], 
       [[12, 13, 14],
        [18, 19, 20]],    
       [[15, 16, 17],
        [21, 22, 23]]])

->

array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

I am currently developing a solution, will post it when it's done, would however like to see other (better) ways.

unpack tuple containing datetime

I have a function f(date, level), I want to unpack arguments from a numpy.record or a tuple

print(tuple(row))
(datetime.datetime(2016, 6, 17, 18, 57, 00), 123)

but

print(*tuple(row))
2016-06-17 18:57:00 123

which is 3 arguments to my function, so error.
how to keep first tuple element as datetime object ?

Can jQuery nextUntil perform my function

I can do this

        $("#id")
            .closest("div")
            .nextUntil("div.stop-class")
            .addClass("new-class");

What I want to do is this

        $("#id")
            .closest("div")
            .nextUntil("div.stop-class")
            .myFunction(someParameter);

I can extend jQuery, but is there another way?

Unsupported operands for range and float, what am I doing wrong?

I'm trying to pass a range of numbers to a function and have that function then give me an array of numbers back. This is my code and the error I've received. I'm brand new to python, so this might be a silly question. This is my snippet of code

How to create multiple mysql tables with MySQLdb in python?

This is what i am trying to do:

cursor.execute("CREATE DATABASE testing")
cursor.execute("USE testing")
cursor.execute("CREATE TABLE Contract(mEnd varchar(7))")    
cursor.execute("CREATE TABLE User(uName varchar(15)")

When I run the python script using MySQLdb it only creates the first table and it ignores all the other lines of code.

can't get rid of 1e-5 while formatting in python 3 programming

I am creating a length calculator and need to format it so it doesn't show 1e-5 from going to mm to km. i have tried '{:.6}'.format() but doesn't seem to work as still outputs it as 1e-5.

Any help on what to do to get rid of this?

Key bindings for interrupt execution in Python Sublime REPL

I'm using REPL extension for Sublime text 3 for my python projects. Currently when I want to interrupt a running script I have to close to close the REPL window to stop execution and all computations are so far are lost. I was wondering if anybody knows how to interrupt an execution and have a short cut or key bindings for that

how to save a scikit-learn pipline with keras regressor inside to disk?

I have a scikit-learn pipline with kerasRegressor in it: estimators = [ ('standardize', StandardScaler()), ('mlp', KerasRegressor(build_fn=baseline_model, nb_epoch=5, batch_size=1000, verbose=1)) ] pipeline = Pipeline(estimators) After, training the pipline, I am trying to save to disk using joblib... joblib.dump(pipeline, filename , compress=9) But I am getting an error: RuntimeError: maximum recursion depth exceeded How would you save the pipeline to disk?

How to increment a numeric string by +1 with Javascript/jQuery

I have the following variable: pageID = 7 I'd like to increment this number on a link: $('#arrowRight').attr('href', 'page.html?='+pageID); So this outputs 7, I'd like to append the link to say 8. But if I add +1: $('#arrowRight').attr('href', 'page.html?='+pageID+1); I get the following output: 1.html?=71 instead of 8. How can I increment this number to be pageID+1?

New to flask and Flask-Login - ImportError: No module named login

It appears that installation of flask-login has issues. Despite a successful install using the below

 pip install flask-login

My app.py file:

 from flaskext.login import LoginManager
 lm = LoginManager()

I get this error :

ImportError: No module named login

So how do I resolve

Indexing one array by another in numpy

Suppose I have a matrix A with some arbitrary values:

array([[ 2, 4, 5, 3],
       [ 1, 6, 8, 9],
       [ 8, 7, 0, 2]])

And a matrix B which contains indices of elements in A:

array([[0, 0, 1, 2],
       [0, 3, 2, 1],
       [3, 2, 1, 0]])

How do I select values from A pointed by B, i.e.:

A[B] = [[2, 2, 4, 5],
        [1, 9, 8, 6],
        [2, 0, 7, 8]]

How do I create sub arrays from a JSON object

I have a JSON object as show here:

[
{
    "ID": "1",
    "Country": "India",
    "Value1": "100",
    "Value2": "200"
},
{
    "ID": "2",
    "Country": "China",
    "Value1": "230",
    "Value2": "800"
}
]

This is the result that I am looking for:

[
        ['India', 100],
        ['China', 230],
    ]

I tried using Jquery $.map function but was unable to get what exactly I wanted. Any pointers would be appreciated.

Prevent ipython from storing outputs in Out variable

I'm currently working with pandas and ipython. Since pandas dataframes are copied when you perform operations with it, my memory usage increases by 500 mb with every cell. I believe it's because the data gets stored in the Out variable, since this doesn't happen with the default python interpreter.

How do I disable the Out variable?

replace semicolon by newline in python code

I would like to parse Python codes that contain semicolons ; for separating commands and produce code that replaces those by newlines n. E.g., from

def main():
    a = "a;b"; return a

I'd like to produce

def main():
    a = "a;b"
    return a

Any hints?

Close popup with key Esc

I try to close popup when I press Esc but it only works while video isn't on play.

$(document).bind('keydown', function (e) {
    if(e.which === 27){
        $('#youmax-video-lightbox').attr('src', '');
        $('#youmax-lightbox').hide();
    }
});

U can see in: http://www.vigerm.com/videos

How to create a navigation bar which on hover, slidedown the entire length size of navigation bar and has other options? As shown in the pictures

Click here to see the image that shows what a want to accomplish

As shown in the pictures.

Click here to see the image that shows what a want to accomplish

Bootstrap data-toggle="toggle" checked,unchecked by jquery

I'm using bootstrap checkbox with data-toggle="toggle" attribute. I want to set it checked and unchecked with jquery. I tried many ways but it didn't work. Here is my code. <input type="checkbox" data-toggle="toggle" data-size="small" id="checkbox1"> for button click: $("#checkbox").attr('checked',true); But it's working when I remove data-toggle="toggle" attribute. Any help is greatly appreciated! Thanks.

Disable focus outside the page

I'm making a web-page based application which would have keyboard (a joystick) only navigation. I use tabindex, but I also need to disable focus on the address bar, search bar or anything else outside the page.

This app would be run only on one specific device, so it's okay (actually needed) to disable some functionality.

Is it possible?

How to translate entire .txt file using Google Translate API in Python?

I am trying to translate an entire .txt file using Google Translate API in Python.

The default code is:

print(service.translations().list(source='zh',
                                  target='en',
                                  q=['上海熙缘节能环保科技服务有限公司',
                                     '广东宏德科技物业有限公司']).execute())

if __name__ == '__main__':
    main()

How can I modify this code so it can translate a .txt file?

Pass info from plot to function

I want to write interactive simulation using graph-tool. What I would like to do is first to visualize the graph, then pick nodes as an input for later actual simulation. How do I pass information from plot to function?

What I did so far - I looked through documentation and examples which do not provide such info.

Thanks!

convert sql from multiple tables with subquery IN to django orm.

How can I convert this sql to django orm? Effectively.

select * from friend where party_id IN(select party_id from party where venue=venue123)


class Friend(models.Model):
    party = models.ForeignKey(Party, related_name='partyid')


class Party(models.Model):
    venue = models.ForeignKey(Venue, related_name='venueid')


class Venue(models.Model):
    venue_name = models.CharField(max_length=33, default='')

add variable to PATH when activateing conda virtual env

assume you want to add/remove a variable to your PATH variable whenever you (de)activate a virtual environment in conda.

I'm working with PyQt5 and by default it doesn't recognize pyuic5 as a command. So I would want to add the location of this command to the PATH env. variable, but only for the time the virtual env. is activated.

Change text (html) with .animate

I am trying to animate the html part of a tag ( <font id="test" size="7">This Text!</font> ) using jQuery's Animate function, like so:

$("#test").delay(1500).animate({text:'The text has now changed!'},500);

However nothing happens, it does not change the text.

How can I do this? Thanks!

vendredi 29 juillet 2016

Python palindrome code not working

I just write a program for checking palindrome in python. I don't know why it is not working. Any help will be greatly appreciated.

def palindrome(word):
    rev_palindrome = []
    for i in word[::-1]:
        rev_palindrome.append(i)
        " ".join(rev_palindrome)
    if word == rev_palindrome:
        print "It is a palindrome"
    else:
        print "It is not a palindrome"
palindrome(mom)

How to make all AJAX calls sequential?

I use jQuery. And I don't want parallel AJAX calls on my application, each call must wait the previous before starting. How to implement it? There is any helper?

UPDATE If there is any synchronous version of the XMLHttpRequest or jQuery.post I would like to know. But sequential != synchronous, and I would like an asynchronous and sequential solution.

gender input loop keeps repeating even if I enter "m" or "f"

If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why?

gender = input('m/f? ')

while gender != 'm' or gender != 'f': 
    print("Type 'm' or 'f'") 
    gender = input('m/f? ') 
if gender == 'm': 
    gender = 'him' 
elif gender == 'f': 
    gender = 'her' 

print("It read {}".format(gender))

Set border using Python xlwings

Is there a way to set border lines for an Excel file from Python using xlwings? I was looking at the documentation but cannot figure out.

I want to create a file like this using xlwings enter image description here

Data undefined in a library initialisation Javascript

I use dropzone library, when I load the page the item-id attribute is null, but after a click get a new value but in the initialisation remains null. How can I update the value in dropzone initialisation?

    $("div#client_documents").dropzone({
        url: '/clients/' + $('#rootwizard').attr('item-id') + '/documentsUpload', // $('#rootwizard').attr('item-id') is null 
        maxFilesize: 20,
        paramName: 'file',

     ...................

Parsing html for specific script type

In the html code, Vine has <script type="application/ld+json"> with links to all the videos on the page, how would I got about accessing this JSON?

import requests
from bs4 import BeautifulSoup

url = 'https://vine.co/tags/funny'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')

Python Saving long string in text file

I have a long string that I want to save in a text file with the code:

taxtfile.write(a)

but because the string is to long its save it like it print it as:

"something something ..... something something"   

how do I make sure it will save the entire string without truncating it ?

Add a prefix to all Flask routes

I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically?

PREFIX = "/abc/123"

@app.route(PREFIX + "/")
def index_page():
  return "This is a website about burritos"

@app.route(PREFIX + "/about")
def about_page():
  return "This is a website about burritos"

List of pairs, find those who are not

I read a list of pairs in the filesystem (Linux)... UniqueDocument.xml UniqueDocument.pdf

I need to find the entries that does not have a xml file, then I need to fetch it.

Been trying with os.list and regex but havent found a sutible solution and Dir() in Ruby. But I cant get to the end... my mind blocks me.

What does PuLP LpStatus=Undefined actually mean?

When I add a particular constraint to my problem, the LpStatus of the problem after solving changes to "Undefined" (without this constraint, it was "Optimal"). At the top of this page, the possibilities of the return status are shown, but it doesn't seem to explain what they mean. Can anyone explain what an "undefined" status means? It it something like a syntax error in specifying the constraint?

saving list values when terminating

I am doing some test, running time functions and appending values to a list.

I am not really sure what to receive. I am thinking to cancel shell over some time, however I would like to see what values were appended to a list. Is there any pythonic way to do this? Or is it really best to save data to some txt file?

Jquery css transform scale centered

Hello guys i've got this code:

(jQuery)

$("#chart1").css({transform:'scale(1,10)'})

with this css code

#chart1{
    position:absolute; 
    bottom:0px;

    width:166px;
    height:10px;

    background-color:purple;
}

It works actually very good, but it scales the hight from the middle. And i want it to scale from the bottom to the top.

Jquery Bootstrap version conflict

Previously I have used bootstrap for opening a pop up and it was working fine but now I am trying to implement Grid.Mvc and for this I need to install Bootstrap version 3.x.x When I did this I got following exception on page inspector on my pop up page

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3

Parse XML file python

I have an XML file (made with ONIXEDIT) with doctype :

<!DOCTYPE ONIXMessage SYSTEM "http://www.editeur.org/onix/2.1/reference/onix-international.dtd>

the file contains XHTML entities, when i try to parse using xml.etree.ElementTree, it gives this error :

xml.etree.ElementTree.ParseError: undefined entity &nbsp;

How can i solve this ?

On Icon Hover Draw Icon

I'm trying to create this Icon Animate effect for my personal work. As they are using images to draw icon on hover. Any other trick to use this one. Please advise

Live Working Link

http://puu.sh/pAksc/8c81c44718.png

Python2.7 Read a file and use it for if in

So what I'm trying to do is use the below code to read a .txt file, and then use that in a if in statement. window is event.WindowName from pyHook.

try:
    with open("log.txt") as f:
        data = f.read().split()
except:
    print "Failed.1"
try:
    if data in window:
        #do stuff

It prints the data as ['foo', 'bar']... Any ideas?

what is d braceopening 4 braceclosing in python?

I am learning python and views in Django. What represents this d in the following code url(r'^articles/(?Pd{4})/(?Pd{2})/$','list_articles'), # views for year and months

I think it 's d4 for 2016 for example and d2 for 06 , but what is the d with those braces. Thanks.

ps : sorry for the title, it was not accepting the { and } characters

jQuery bvalidator Phone Number Validation

I'm using bValidator for form validation. Form fields are generated dynamically from a json file and loaded into an angularJS view on the fly. I'm trying to validate a phone number input field using regex, I don't want user's to enter 9999999999 as phone number.Below is the regex expression data-bvalidator="number,required,regex[!(9999999999)]" I also tried data-bvalidator="number,required,regex[^(9999999999)]" and many others. But not getting the desired result

How can I show json data after select dropdown?

How can I show json data after select dropdown? I Get this json data.

{
"london": {
    "shop1": {
        "address": "address1",
        "phone": "0123456"
    },
    "shop2": {
        "address": "address2",
        "phone": "2223456"
    }
},
"liverpool": {
    "shop1": {
        "address": "address3",
        "phone": "3123456"
    },
    "shop2": {
        "address": "address4",
        "phone": "4223456"
    }
},
"manchester": {
    "shop1": {
        "address": "address5",
        "phone": "5123456"
    }}

I want to do like this

enter image description here

pandas DataFrame - find max between offset columns

Suppose I have a pandas dataframe given by import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,2)) df 0 1 0 0.264053 -1.225456 1 0.805492 -1.072943 2 0.142433 -0.469905 3 0.758322 0.804881 4 -0.281493 0.602433 I want to return a Series object with 4 rows, containing max(df[0,0], df[1,1]), max(df[1,0], df[2,1]), max(df[2,0], df[3,1]), max(df[3,0], df[4,1]). More generally, what is the best way to compare the max of column 0 and column 1 offset by n rows? Thanks.

Convert Arabic Characters (Eastern Arabic Numerals) to Arabic Numerals in Python

Some of our clients submit timestamps like ٢٠١٥-١٠-٠٣ ١٩:٠١:٤٣ which Google translates to "03/10/2015 19:01:43". Link here.

How can I achieve the same in Python?

Python intersection with custom equality

I want to build the intersection of two python sets, but i need to have a custom equality to do this. Is there a way to specify "equaliy" directly when doing the intersection? For example due to a lambda-expressions?

I know there is way by overriding eq, but i have to do several intersections on the same classes with different "equalities".

Thanks!

How do we know customer is logged or not

I am new to Volusion, I am planning to create menu like options sign in, create account etc. So here If customer logged in to website I need to change sign in as Log out and disable the Create Account option. if Logged out I need to revert sign in and create account in menu.

I don't know how to do this. If any answers Appreciate.

How to check/uncheck radio button on click?

I want to be able to uncheck a radio button by clicking on it.

So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.

This does not work:

$('input[type=radio]:checked').click(function(){
    $(this).attr('checked', false);
});

I am not able to check a radio button now.

jeudi 28 juillet 2016

Restarting Interval not working after clearing

I am getting num1 and num2 value from service call. I am trying reset interval after clearing it but it does not work this way. I have also tried other ways mentioned in stackoverflow. Nothing works.

function func(){    
     if (num1 > num2 ) {
          console.log(" gt greater than lt");
          clearInterval(interval);
          flag = true;
          setInterval(func,1800000);
          $('.class').trigger('point');
          return;

        }
//do something
}

var interval = setInterval(func,10);

plotting a sequence results in: "ValueError: x and y must have same first dimension"

I'm a beginner here and I'm experiencing a problem when I'm trying to plot a sequence:

My code gives me this error message: "ValueError: x and y must have same first dimension"

hold(True)
x=[0.5]
for r in arange(2,4,0.1):
    for i in range(170):
        xn= x[-1]
        xnp1 = r*xn*(1-xn)
        x.append(xnp1)
        xa=array(x)   
        rplot=0*xa+r
plot (rplot, xn,".")
show()

How to make string interpreted as bytes?

Python 2 str compatable with bytes, but on Python 3 str is unicode.

I working on porting some project to Python3, but with support Python2.7. This prodject has tests with many string constants. Also there is few '...'.join(...) and '...'.format(...).

How to make Python3 to b'123' == '123' ?

Application shows error context out of request in flask in ibmqradar

I want to know the best practices used by the QRadar developers community to run the process in background. Like QRadar provides the SDK for building the apps which is in Python and used Flask Web application framework now I want to create an app that poll the data from the server and update the QRadar Reference sets. I come to know there are 3 options. Threads(which throws error ) flask-celery Crontab

framework7 load external jquery script

I am trying to load an external jquery script to my Framework7 app. I am using the following code which loads the javascript successfully, however it is currently just adding that JS code into my Div as HTML. How do I load the JS and also have it compile as JS?

myApp.onPageInit('about', function (page) {
  $$.get('js/sc-player.js', {}, function (data) {
    $$('#sc-js').html(data);
  });
});

How can i get a image related to a given Text

I am working on a project in Artificial Intelligence, Where I need to get Image Media related to a given Phrase. For example, if I give "Tiger Woods", it should give me Image of Tiger Woods golfer, and if I give "Tiger in Woods", it should give me an Image of a tiger in woods.

Any Script in python, or any link to a website would help me.

How to link element to slider move?

I downloaded one of the free sliders (http://flexslider.woothemes.com)

How can I slide an element outside the actual slider? is there any command to act as a short in slider but targeting the something outside the slider?

Please take look at attached image

Pygame inflate not working

So I'm making a game using python and I'm looking to make a rectangle grow.

I saw on the pygame website that you use the inflate method and saw a demo of it and tried it but it does not work.

Here is my code:

# defining statement
player = Rect(300, 100, 50, 50)
grow = player.inflate(100, 100)

# calling statement
if player.colliderect(food):
    foods.remove(food)
    grow

Fill the outside of contours OpenCV

I am trying to color in black the outside region of a contours using openCV and python language. Here is my code :

contours, hierarchy = cv2.findContours(copy.deepcopy(img_copy),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
# how to fill of black the outside of the contours cnt please? `

Converting a log file into a csv file using Python

I have the following problem at work - I need to take a log file with items arranged as follows:

A1
B1
C1
A2
B2
C2
.
.
.
An
Bn
Cn

I need a complete csv file like so:

A1,B1,C1
A2,B2,C2
A3,B3,C3
...
An,Bn,Cn

How can I do this using a python script?

Making animations like those on apple web site

I want to make animations like those on apple web site:

http://www.apple.com/iphone/

or if above link is not working http://www.youtube.com/watch?v=05WEIWZvw2Q

Is there some productive framework (eg jquery plugin) dedicated to this kind of job?

How to set request.body in django Request factory post request?

trying to set request.body in python unit test as

        self.factory = RequestFactory()
        self.request = self.factory.get(reverse('get_associations'))
        self.request.user = self.auth_user
        self.request.body = json.dumps(self.post_data)

but it gives error:

self.request.body = json.dumps(self.post_data)
AttributeError: can't set attribute

can anybody help me to fix this?

can't understand python set operation

I can't understand a simply python code. Below, 'blobs' is a list of ndarray and 'end' is explained to be 'optional name of layer'.

   if end is not None:
        end_ind = list(self._layer_names).index(end)
        outputs = set([end] + blobs)     # <== this line.
    else:
        end_ind = len(self.layers) - 1
        outputs = set(self.outputs + blobs)

What does the statement 'set([end] + blobs) mean?

Jquery event not working

I've made this Jquery event and want to apply opacity on my button but it's not working.Please help!

<button type="button" id="btn-opacity" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Sign-Up
</button>
button#btn-opacity {
    background-color: aqua;
    border: hidden;
}
$(document).ready(function() {
    $('#btn-opacity').mouseenter(function(event) {
        /* Act on the event */
        $(this).fadeTo('slow', 0.3);
    });
}); 

how to add content-type with $.post method in ajax call

Hi i want to add contentType:"application/json" to $.post method I don't want to use $.ajax as

$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json",
  dataType:"json",
  success: function(){
    //success code
}

but I want to use $.post method

$.post(url,data,function(result){
    //success code
});

Please any one help me to specify contentType with $.post method

setState in $.get

Uncaught TypeError: undefined is not a function is throw when this.setState is use within the $.get scope, it works fine when I place the code outside the scope. How do you deal with it?

$.get(APIURL, function (data) {
   this.setState({resdata: "This is a new state"});
});

I'm not sure what is the best practice to replace JQuery AJAX to other small AJAX libraries. Please advice.

PIL - apply the same operation to every pixel

I create an image and fill the pixels:

img = Image.new( 'RGB', (2000,2000), "black") # create a new black image
pixels = img.load() # create the pixel map

for i in range(img.size[0]):    # for every pixel:
    for j in range(img.size[1]):
      #do some stuff that requires i and j as parameter

Can this be done more elegant (and may be faster, since theoretically the loops are parallelizable)?

Create a mapping from a file in awk or shell script or python

I have a file which contains airport code like below

ATQ 
HYD 
BLR
GOI 
AMD
CCJ
TRV

from the same file i have to create source destination mapping like below in gawk.

 src dest
 ATQ HYD
 ATQ BLR
 ATQ GOI
 ATQ AMD
 ATQ CCJ
 ATQ TRV
 HYD ATQ
 HYD BLR
 HYD AMD
 ....
 ...

can anyone help me here,thanks in advance

Bootstrap(2.3.2) modal popup visibility check

I need to insert a class name to body tag when the bootstrap pop up is opened. I have tried adding using jquery but unfortunately it is not working. Any help would be appreciated.

Here is my code

if(!$('.modal-backdrop').is(':visible'))
{
$(body).addClass("test");
}

Demo

Why do identical strings return false with ==?

This is the simplified version of my problem.

QA = open('Qestions and answers.txt')
Q = []
A = []

for line in QA:
  (first,second) = line.split(';')
   Q.append(first)
   A.append(second)

QA.close()

print(A[0], A[1])
print(A[0] == '1981')
print(A[1] == 'Feb')
print(str(A[0]) == '1981') # I even tried str
print(str(A[1]) == "Feb")

Output:

1981
 Feb

False
False
False
False

Rename Files in Python

I'm trying to rename some files in a directory using Python.

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE

I'm trying to use the os.path.split but it's not working properly. I have also considered using string manipulations, but have not been successful with that either.

TensorFlow Setup Issue

I just setup TensorFlow on my MacBook Pro (El Capitan) and ran the installation test suggested on the website. This is what shows up:

hello = tf.constant('Hello, TensorFlow!')

sess = tf.Session()

print(sess.run(hello))

b'Hello, TensorFlow!'

Are the "b" and quotations around Hello, TensorFlow a result of something wrong done during installation?

Thanks!

How to change the background color of a coloumn in a jQuery DataTable?

Im new to jQuery and JavaScript, I want to change the background color of a specific column if the if statement is true.

$('#myTable').DataTable({
    "ajax": {
        "url": "/project/loadClientData",
        "type": "GET",
        "datatype": "json"
    },
    "columns" : 
    [
        { "data": "name", "autoWidth": true, "bSortable": true},
        {
            "data": "active", "autoWidth": true, "bSortable": true, "mRender": function (data, type, full, meta)
            {
                if (full.active == true) {
                    // i wanna make this cell background green.
                    return 'Ja';
                }   
                else {
                    return 'Nej';
                }
            }
        }
    ]
});

'Time to go offline' what is the best technologies to start? [on hold]

If I am familiar with 'angularjs','jQuery' and chrome features like push notifications and service worker.Is it necessary to use a framework or we can use native HTML5 and CSS3. The best way to get is with service worker a chrome features . Here are some questions that might help you to answer my question: What makes offline applications different from online application? What technologies are used for this approach? Does using framework increases efficiency?

mercredi 27 juillet 2016

html change text based on input field

I have an <h3> that I want the value of to change based on what is typed in the input field. Here is the code I currently have:

<input id="Medication" name="Medication" size="50" type="text" value="">
<script>
$(document).ready(function () {
  $('#Medication').change(function () {
    $('#myAnchor').text($(this).val());
  });
});
</script>
<h3 id="myAnchor"></h3>

Saving a key from a dictionary without value

I am representing a weighted graph as a dictionary where the key represents a vertex and the following lists, the links that are connecting the vertex (first number weight and second number linked vertex): wGraph = { 1 : [[2, 2],[3, 4],[3, 3]], 3 : [[3, 2],[5, 4],[7, 5]], 2 : [[2, 1],[4, 4],[3, 6]], 4 : [[3, 1],[4, 2],[1, 6],[5, 3]], 6 : [[3, 2],[1, 4],[8, 5]], 5 : [[7, 3],[8, 6],[9, 7]], 7 : [9, 5]} I would like to save a random key without its value from the dictionary to a list called visited. random_num = random.randrange(len(wGraph)) visited = [] How can I get the key from the dictionary according to the random number?

How to change the order of DataFrame columns?

I have the following DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

I add more column(s) by assignment:

df['mean'] = df.mean(1)

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

set c# label visible by JQUERY

Is there any way to set asp label visible by Jquery?

I have a label like this:

<asp:Label runat="server" ID="lblCheckboxesError" Text="test" visible="false"></asp:Label>

and in *.js file a have this:

$("[id*=lblCheckboxesError]").show();

but nothing happened :( I have tried some next solutions, but nothings works for me :( any idea? thanks :)

Python pass more than one arguments to tcl proc using Tkinter tcl.eval

how to pass more than one arguments to tcl proc using Tkinter. i want to pass 3 args to tcl proc tableParser from python proc validate_op which has 3 args...

from Tkinter import Tcl
import os

tcl = Tcl()

def validate_op(fetch, header, value):
    tcl.eval('source tcl_proc.tcl') 
    tcl.eval('set op [tableParser $fetch $header $value]') <<<<< not working



proc tableParser { result_col args} {

  ..
..
..

}

Send ipynb to server and open it

I monitor a bunch of Python scripts each of them representing a trading strategy. In a database I store for each script the entire source code + results. I can convert my scripts into valid ipynb json documents (on the fly). Ideally I would like to send those documents to an existing Jupyter server (without going through saving them on disc). So is there a chance to post json documents to an Jupyter server? Thomas

Global variable in python function doesn't work for my code

This works.

a = [2,5,3,7,9,12]
def mean_list(x):
      b = 0
      for i in x:
            b=b+i
            c = b/len(x)
      return c
print(mean_list(a))

but this doesn't work, even though I have declared my list as global. Why?

def mean_list(x):
      global a
      a = [2,5,3,7,9,12]
      b = 0
      for i in x:
            b=b+i
            c = b/len(x)
      return c
print(mean_list(a))

Execute onclick of ESC Key

Briefly, my problem is that I would like to execute the effect of Esc button by a line of javascript, for example execute an effect onclick of the Esc button. How can I do It ?

[ What I have is an upload in a jQuery box, so I would like that when the upload will finish, the escape function will be executed automatically to close the box]

Why does "import ctask as task" fail in pyinvoke?

When I try to use ctask as defined in the getting started guide, it fails with the following error:

>>> from invoke import ctask as task
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name task

What happened to the ctask module?

Lexicographic comparison of two numpy ndarrays

I couldn't find a straightforward way to compare two (multidimensional in my case) arrays the in a lexicographic way.

Ie.

a = [1,2,3,4]
b = [4,0,1,6]

For a < b I want to get true where I get [true, false, false, true]
For a > b I want to get false where I get [false, true, true, false]

Pandas - count if multiple conditions

Having a dataframe in python:

CASE    TYPE
1          A
1          A
1          A
2          A
2          B
3          B
3          B
3          B

how can I create a result dataframe which would yield all cases and either an "A" if the case had only "A's" assigned, "B" if it was only "B's" or "MIXED" if the case had both A and B?

Result would be then:

Case     Type
1        A
2        MIXED
3        B

check username exists using ajax

I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.

$(document).ready(function() {
    $('#username').keyup(function() {
        $.post('adm/chk_uname_avail.php', { 
            uname : changeuser.username.value 
        }, function(result){
            $('#available').html(result);
        })
    })
})

Call a python function from one class in another

I am new to Python and I have difficulties in the basics of functions

a.py

import b
from ConfigParser import SafeConfigParser

class A:
  def method1():
    config = SafeConfigParser()
    b = B()
    b.method2(config)

b.py

class B:
  def method2(config)
    config.
    # The editor does not show the inbuilt methods of config here

I am using IntelliJ IDE

Get unique values from a list in python

I want to get the unique values from the following list:

[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']

The output which I require is:

[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']

I tried the following code:

for x in trends:
    if x not in output:
        output.append(x)
        print output

but it didn't work. Any help would be appreciated.

Trying to identify the errors and provide the python code that accomplishes the task

if n is an integer, write the expression that will determine if n is odd and between 200 and 2000, exclusive?

I have no idea what odd/even and exclusive/inclusive means in an expression like this, can someone give me a briefing of it. Below is what I have got so far

n >= 200 and n <= 2000

Please help me understand exclusive/inclusive and even/odd. Thank You.

how to used objloader in three.js to load an object or image from blob link?

Hello I need Help on this.

This is my code for showing an object

but the object that I need to show is not display.

   var loader = new THREE.OBJLoader( manager );
    loader.load('https://twportal.blob.core.windows.net/ecardbackground/scenes1.obj', function ( object ) {

        object.traverse( function ( child ) {

            if ( child instanceof THREE.Mesh ) {

                child.material.map = texture;

            }

        } );

please let me know what is my error.

matplotlib: AttributeError: 'AxesSubplot' object has no attribute 'add_axes'

Not sure exactly sure how to fix the following attribute error:

AttributeError: 'AxesSubplot' object has no attribute 'add_axes'

The offending problem seems to be linked to the way I have set up my plot:

gridspec_layout = gridspec.GridSpec(3,3)
pyplot_2 = fig.add_subplot(gridspec_layout[2])

ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
pyplot_2.add_axes(ax)

Does anybody know how to solve this? Many thanks.

How to get similarity from LSA

I am working on latent semantic analysis, i am trying to get similarity from 2 documents. I run my code of latent semantic analysis on Python and when i run it i get :

Here are the singular values
[ 0.7376057   0.4596623   0.25422212]
Here are the first 3 columns of the U matrix
[[ 0.98465137 -0.172792   -0.02458864]
[ 0.15675976  0.81362269  0.55986114]
[ 0.07673365  0.55512255 -0.82822153]]
Here are the first 3 rows of the Vt matrix
[[ 0.08861949  0.02992777  0.36751379  0.9253024 ]
[ 0.78716383  0.34742637  0.43792207 -0.26056147]
[ 0.29462756 -0.93722956  0.17407106 -0.06704194]]

How i will find similarity from this numbers ?

How to get the index of the element by class that is clicked

I have this code:

<button class="remove" value="1" />
<button class="remove" value="2" />
<button class="remove" value="3" />
$(document).on('click', ".remove", function(e) {
    alert($(this).index());
});

It is always alerting 0. If the user clicked the button that has a value of 2, it must alert 1 but in my code it alerts 0.

Convert Pandas DataFrame to dictionary

I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of other columns in same row be values.

Dataframe:

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9  

Output should be like this:

Dictionary:

{'p': [1,3,2],'q': [4,3,2],'r': [4,0,9]}

Animating HTML Text Change jQuery

I am attempting to change the text of a HTML element using javascript and jquery. This is my code so far, and I can't seem to get it to work. I have googled it and can't seem to find anything on it.

$("div#title").hover(
    function() {
        $(this).stop().animate({
            $("div#title").html("Hello")
        }, "fast");
    },
    function(){
        $(this).stop.animate({
            $("div#title").html("Good Bye")
        }, "fast");
    }
);

Any help would be greatly apreciated.

Replace text of element that start with specific text

I have html like bottom code

<table>
    <tr>
        <td>
            {name length='100'}
        </td>
        <td>
            {otherText length='100'}
        </td>
        <td>
            {otherText2 length='100'}
        </td>
    </tr>
</table>

I want to change tds text that start with {name.

How can i do this?

Add form with scripts in WP

I am trying to add code to my WPpost page, but I don't know how to add it.

I tried to add to the child theme, but it didn't work:

global $allowedposttags;
$allowedposttags['script'] = array(
 'type' => array(),
 'src' => array()
);

I have to add this source code to a classic WordPress page. How do I do that?

updating prior rows of dataframe conditionally upon current

I have a dataframe (ev), and I would like to read it and whenever the value of the 'trig' column is 64, I need to update the value of the critical column that is 4 rows above, and change it to 999. I tried the code below but it does not change anything, though seems it should work.

for i in range(0,len(ev)):  
    if ev['trig'][i] == 64:
        ev['critical'][i-4] == 999

mardi 26 juillet 2016

lutorpy for shared memory between python and torch

I am trying to install lutorpy to load a network trained in torch and use it in python code. I get the following error:

lutorpy/_lupa.c:299:17: fatal error: lua.h: no such file or directory

I do have lua.h in torch/install/include folder.

I'm following the instructions here and get this error: https://github.com/imodpasteur/lutorpy

Spark Matrix multiplication with python

I am trying to do matrix multiplication using Apache Spark and Python.

Here is my data

from pyspark.mllib.linalg.distributed import RowMatrix

My RDD of vectors

rows_1 = sc.parallelize([[1, 2], [4, 5], [7, 8]])
rows_2 = sc.parallelize([[1, 2], [4, 5]])

My maxtrix

mat1 = RowMatrix(rows_1)
mat2 = RowMatrix(rows_2)

I would like to do something like this:

mat = mat1 * mat2

POS tagging in German

I am using NLTK to extract nouns from a text-string starting with the following command:

tagged_text = nltk.pos_tag(nltk.Text(nltk.word_tokenize(some_string)))

It works fine in English. Is there an easy way to make it work for German as well?

(I have no experience with natural language programming, but I managed to use the python nltk library which is great so far.)

Python - How to Compare a column value of one row with value in next row

I want to compare the S.No. of different rows, if it is same then I want to calculate the datetime difference and print details.(If datetime difference is not possible then only date difference would also be fine.)

Input

S.No.   Datetime    Details

1    2010/6/7 19:01 asd 

1    2010/6/8 4:00  dfg 

2    2010/6/9 0:00  dfg 

2   2010/6/10 0:00  gfd 

2   2010/6/11 0:00  gfd 

3   2010/6/12 0:00  gfd 

3   2010/6/13 0:00  abc 

4   2010/6/14 0:00  abc 

4   2010/6/15 0:00  def 

Expected output

1   0.3 asd dfg

2   1   dfg gfd

2   1   gfd gfd

3   1   gfd abc

4   1   abc def

Search Multiple Strings (from File) in a file and print the line

Again apologies for been noob here ; trying below code for searching multiple strings read from keywords and search in f and printing the line. it works if i have only one keyword but not if i have more then one

keywords = input ("Please Enter keywords path as c:/example/ n :")
 keys = open((keywords) , "r").readline()        
        with open("c:/saad/saad.txt") as f:
                         for line in f:
                                if (keys) in line:
                                        print (line)

Bitshifting with and without leading zero [duplicate]

This question already has an answer here:

I wonder why adding one or multiple leading zeros to an integer in Python leads to different results when using the bitshift-operators:

In:  10<<1
Out: 20

Adding a "0" in front of the integer:

In:  010<<1
Out: 16

Series of instructive pop-up on page, how to handle the mark up with Jquery?

I'm bulding an intranet which required pop-ups when users first use the site. What really concern me though, is how to generate the mark up into html when there are so much content to be loaded. Should i do it manually or generate the content automically ? is there good approach (pattern, method...) for either of them ? For the record, i'm a front-end developer who know a little about back-end stuff such as PHP and MySQL, hope that helps.

Create a questionnaire? Where to start? [on hold]

I'm looking for guidance on how to create a questionnaire using python?

Essentially this is what I would be looking to do:

  1. Enter subejct information (name + number)
  2. Instruction page
  3. Question 1: Pick form 1-5
  4. Upon click, goes to next frame (question 2)... ect

and the values would be output to a CVS file.

Any advice on where to start would be helpful. Thank you!

How to get the text/html value from event.target using jQuery

I'm using Clipboard.js and am trying to get the text in a <td> node using the following:

$('.clipboard').click(function(evt) {
    clipboard.copy(evt.target.val()).then(
      function(){console.log("success");},
      function(err){console.log("failure", err);}
    );
});

Obviously .val() is not a valid method on evt.target. What's the correct way of getting the nodes text value using evt here?

Adding values associated with the same key in two different dictionaries

I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{'A': 25 , 'B': 41, 'C': 32}

and dict2

{'D':21, 'A': 12, 'B':62}

I'm writing a program where I need to add the values associated with the same key. So like this:

{'A': [25 + 12], 'B': [41 + 62], 'C': [32], 'D': [21]}

Pandas Series: Log Normalize

I have a Pandas Series, that needs to be log-transformed to be normal distributed. But I can´t log transform yet, because there are 1 < values < 1. Therefore I want to normalize the Series first. I heard of StandardScaler(scikit-learn), Z-score standardization and Min-Max scaling(normalization). I want to cluster the data later, which would be the best method? StandardScaler and Z-score standardization use mean, variance etc. Can I use them on "not yet normal distibuted" data?

Stop channel.basic_consume if the connection is idle/Not consuming from long time

I am having a use case in which i want get the last idle time(last message processed time) of a pika consumer(pika.BlockingConnection).
Usecase:
If the last processed time is greater than Threshold time(ex: 1 hr). I want the consumer to get exited or have a callback method to decide on what i need to do? Like sending a notification to a user.

Is there any way to do this?

Unable to detect the JAVA_HOME path in mac El Capitan

import os
import sys

print os.environ.get('JAVA_HOME') #Output:: printing None

Unable to detect the JAVA_HOME path in mac El Capitan for python. But when I print the environment variables it is showing in the list.

enter image description here

How to fix this issue?

Find specific values inside array

I'm trying to insert conditioned values in an array into an empty array in exact position.

empty_array = np.zeros([40,100])
for x in range (1,24):
    array[x,:,:] #which is also sized 40x100
    if the_values_in_the_array < 0.25:
         the_values_in_the_array = 0
    empty_array = empty_array + array [x,:,:]

Which syntax should I use for this logic? And how should I scan the_values_in_the_array to find the conditioned values?

How create animated emoticons for Hybrid App

I am developing a chat app (Hybrid app) for android and IOS. I intend to use some animated emoticons to add spice to chat.

I have 2 questions here:

  1. How to create custom animated emoticons that I could integrate into my chat app and user could use to chat.

  2. Will animated emoticons impact the app performance, especially if I attach sound to them?

Thanks alot!

How to show data stored (sql server database) in a 'select option' with json or/and javascript?

I'm new in the mvc world, so, I don't understand a couple of things. I'm working with c#, javascript and sql server to do a webservice. The point is that I need to show data from a table by populating a 'select option' (created with javascript) and I would like to do this with javascript, json or jquery, without php. Please, I need you to be specific for me to understand. Thank you for your attention and help!

Ways to implement hooks in Python

I recently learnt the concept hooks. I understand the concept that hooks are a way for third party developers to modify an api. I wanted to know the different ways of implementing hooks in Python(Currently I can think none other than plain inheritance). Are there specific design patterns for implementing hooks. Examples would be nice or can some one point to projects where they have been implemented. I want to know different ways to implement hooks. Thanks in advance.

Python, copy only directories

I have a program that has a list of some files. I have to copy only the directories and the subdirectories from the list to a specified directories and don't need to copy the files. I tried this, but it doesn't work. def copiarDirs(): items = list.curselection() desti = tkFileDialog.askdirectory() for dirs in os.walk(items, topdown=False): for name in dirs: #for i in items : aux=root+"/"+list.get(i) tryhard=("cp "+str(aux)+" "+str(desti)) os.system(tryhard)

How to calculate a TCP packet checksum using Python?

I'm using Scapy (the below code) to capture the IP/TCP packets on network:

sniff(iface='ens33', prn=call_back, filter="ip and dst host 10.0.0.12", store=0)

def call_back(packet):
    ip_packet = packet['IP']
    tcp_packet = ip_packet['TCP']

When I got 'ip_packet', I need to change its source address to another one, and send it out.

How can I re-calculate its checksum in IP header and TCP header?

Browser side CSS abstract syntax tree generator. (Javascript but Not node)

I'm looking for a client-side standalone javascript library (if it runs on node then i can't use it) that consumes a string of text (that has valid CSS) and produces a css Abstract Syntax Tree. Something like JavaScript AST visualizer: http://jointjs.com/demos/javascript-ast but for css.

It has to be client side standlone javascript, not NODE.

Thanks in advance for all your answers!!

typehead.js JSON AJAX BASIC SETUP

I cant get anything to load or error from typehead.js

This is the script. I check the console and it wont error or get anything I want to load in api data from json format.

$(document).ready(function() {      
        $('input.typeahead').typeahead({        
          source: function (typeahead,query) {
            $.ajax({
              url: '/api/location',
              type: 'POST',
              dataType: 'JSON',
              data: 'sstr=' + query,
              async: true,
              success: function(data) {         
                console.log(data);
                alert("I am an alert box!");

              }
            });
          }
        });
      });

How to read dictionaries in python?

I have a file of name "input.txt". In this text file a lot of dictionaries are stored. I have to iterate through these dictionaries. How do read the file? Whenever I read the file using open(), file.read() it coverts the whole text into a string type. How to read this file as collection of dictionaries?

Contents of input.txt:

{"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}

Video.js Show play button only when paused

I am currently using video.js on my website.

I have made controls false, which also hides the play button.

I am looking to have the play button display only when the video is paused, and not display whilst the video is playing.

I tried the following , but it doesn't work.

videojs("myPlayer").ready(function(){
  var myPlayer = this;
  myPlayer.on("paused", function(){
    myPlayer.bigPlayButton.show();
  });
});

Thank you!

What is the best jquery/js plugin to build a drag & drop form builder?

i am building a system like http://www.youtube.com/watch?feature=player_embedded&v=cIjADcI37oE#! http://wufoo.com/

which provide a function of building a input form and building the workflow model using drag & drop interface.

hope someone can suggest the plugins that is most suitable.

lundi 25 juillet 2016

How can I convert a tensor into a numpy array in TensorFlow?

I know how to convert an numpy array into a tensor object with the function tf.convert_to_tensor(img.eval()).

My problem is that after I apply some preprocessing to this tensors in terms of brightness, contrast, etc, I would like to view the resulting transformations to evaluate and tweak my parameters.

How can I convert a tensor into a numpy array so I can show it as an image with PIL?

Jquery combine click and change

Is it possible listen click and change for one code?

$(document).on("click", "button.options_buy",function(event) {

//   same code
}


$(document).on("change", "select.options_buy",function(event) {

//   same code
}

I try this

$(document).on("click change", "button.options_buy,select.options_buy",function(event) { }

It works but I want 'click' only for 'button.options_buy' and 'change' for 'select.options_buy'

is it possible?

print one time uniqe variable in if or while statement python

Is there a way to see / print looping variables which have unique values?

for an example:

while random.randint(0,15) != 7:

If I do:

while random.randint(0,15) != 7:
     print (random.randint(0,15))

I won't get the same result as it was produced in while loop It can happen while statement generates seven, but print statement would produce different number. So how to see through what variables were you really looping?

'import module' or 'from module import'

I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any gotchas down the road.

How to change the order of python unit test cases in 'tests' directory

I have flask project. I want to run unit test cases which are in tests directory using test suite. As we know that python modules in the tests directory get executed alphabetically. Can I change that order of execution?

Suppose I have a directory structure like:

/tests
     test_add.py
     test_delete.py
     test_get.py
     test_put.py

But I want to run add, get, delete then put. Is that possible?

jQuery: Find word and change every few seconds

How can I change a word every 2-3 seconds using jQuery?

For example:

I have this:

<div>
    <span>This is so</span>
    <span>awesome</span>
</div>

... and I want the awesome to change into cool,fantastic,incredible and keep cycling with loop using fadeOut/fadeIn effect maybe?

Is it possible?

Thanks alot

NetworkError: 404 Not Found IIS Windows 2008 R2

I have dedicated windows 2008 R2 server where I have IIS website in html website. Every thing is working fine but on some of the pages when I go to firebug I can see that some css and jQuery files are showing NetworkError: 404 not found

But when I go to the directory on the server physically files are there then why it is showing not found !!!

can somebody tell me what can be the issue!!

'ManyToManyDescriptor' object has no attribute 'add', why?

So I refer to another model :

 subscriptions = models.ManyToManyField(Season)

So I use :

@api_view(['POST'])
def buy_season(request):
    _id = 1
    season = Season.objects.get(id = _id)

    a = ExtUser.subscriptions.add(season)

    a.save()

    return Response({'status': 'success'}, status=status.HTTP_200_OK)

I get an error object 'ManyToManyDescriptor' does not attribute the "Add" Do many to many directly , and not through the " throw " , why there is this error ?

Showing dynamic rates for all dates using jquery ui calendar

In a Car Rental Website Reservation System, i am using jquery ui calendar as a date range picker for "From Date" and "To Date" selection.

I want to show dynamic rates for different dates as shown in figure. Please let me know how i can do that ?

dynamic rates for different dates

Python sqlite3 delete not doing anything

I am a noob about sqlite (but somewhat experienced as Pythonista), but I am deeply confused why this (Python 2.7, DBPATH is the path to the database)...

import sqlite3

connection = sqlite3.connect(DBPATH)
conn = connection.cursor()
query = "SELECT * from jobs"
conn.execute(query)
print(conn.fectchall)
query = "DELETE from jobs"
conn.execute(query)

...Outputs the contents of the table (thus the name of the table is right) without altering it. Could someone point out the obvious?

Python and Matplotlib: Plot multiple graphs on the same figure fast

Is there a faster way of plotting multiple curves over the same x range than the following?

import numpy as np
import matplotlib.pyplot as plt

N = 100
x = np.linspace(0, 2*np.pi, 1e5)
y = [np.sin(x)**i for i in range(N)]

color = iter(plt.cm.rainbow(np.linspace(0, 1, N)))
[plt.plot(x, y[i], c=next(color)) for i in range(N)]
plt.show())

This code takes considerable time when plotting many trajectories :(

alternate button text automatically without click

I would like alternate between 2 pieces of text on a button in 2 sec intervals. This is NOT a click event. I just want the button to rotate between 'click here' and 'download'. This is what Im trying with no luck:

<div class="assetClass customButton1_1Div" id="download_btn1">
<input type="button" class="customButton1_1" name="button1_1" value="click here" title="download_btn1" />
</div>

setInterval(toggle, 2000);
function toggle() {
document.getElementByName("button1_1").value = "download";
}

Installing SciPy with pip

It is possible to install NumPy with pip using pip install numpy.

Is there a similar possibility with SciPy? (Doing pip install scipy does not work.)


Update

The package SciPy is now available to be installed with pip!

How to pass hidden field value as parameter to action method

How do I pass a hidden field value as parameter to action method from kendo grid action method?

.Selectable(s => s.Mode(GridSelectionMode.Single))
 .Events(e => e.Change("UtilitySelected"))
  //.ClientDetailTemplateId("utility-detail")
   .DataSource(dataSource => dataSource
   .Ajax()
   .ServerOperation(false)
   .Group(groups => groups.Add(p => p.ISO))
   .Read(operationBuilder => operationBuilder
   .Action("SearchResultJson", "Flash", new { historyType=$("#HistoryName")})

Need to pass $("#HistoryName") value to the controller

Any way to do that?

Python sum 2D list column coincident

I'm looking for the most efficient method to do the following calculation:

I have three matrix, like this:

[[Brand1, operationCost], [Brand2, operationCost],...]

[[Brand1, maintenanceCost],[Brand2, maintenanceCost]...]

[[Brand1, replacementCost],[Brand2, replacementCost]...]

and I need to calculate the total cost, operation+maintenance+replacement, of each of the brands. It is posible that same of the marks are not in all the matrix. And obtain another matrix like this:

[[Brand1, totalCost],[Brand2, totalCost]...]    

How can I track number of downloads for images in website

I have a <img download> tag in my page. Every time a user clicks on it, file will download.

I can track number of clicks on this <img> tag and store in db for track number of downloads.

But what if user cancel the download file prompt (Select location for downloading file),

How can I track whether user is actually downloading file or not?

Generating random value for given cdf

Depending on sample of values of random variable I create cumulative density function using kernel density estimation.

cdf = gaussian_kde(sample)

What I need is to generate sample values of random variable whose density function is equal to constructed cdf. I know about the way of inversing the probability distribution function, but since I can not do it analitically it requires pretty complicated preparations. Is there integrated solution or maybe another way to accomplish the task?

Auto it click exception: access violation reading 0x00000083

My code should open a window from taskbar and then click a control from it. The problem is that after it opens the window I get the error : "exception: access violation reading 0x00000083".I am new to Python (and in programing) and I have no ideea what that means or how to solve it.My code looks like this : import autoit, time autoit.win_activate("KOPLAYER 1.3.1040") time.sleep(2) autoit.mouse_click(131, 507) It opens (activates) the window but after that I get that exception error.

Jquery checking if user scrolled to bottom works reversed

I have got this code in three different js files var sd=0;

$(window).scroll(function() {
               if($(window).scrollTop() + $(window).height() == $(document).height()) {
                sd++;
                          $.ajax({
                            url: '../connect.php',
                            type: 'GET',
                            cache: false,
                            contentType: false,
                            processData: false,
                            data:"SMu=true&&sd="+sd,                         
                            success: function(d)
                            {    
                                $(".upfile").append(d);
                                $(".ShowMoreUpl").remove();
                            }   
                        });
               }
            });

In one file it works quintessentially while in other it works when i scroll to the apex.What may be the reason that causes this problem?

Proper initialization of flot.time with timezone-js (Angular & require.js)

Could someone tell me what is correct configuration of require.js to draw timezone-specific graps with flot.time.js on Angular app? My current rconfig.js looks like this:

paths: {
     ...
    'angular':                      '../bower_components' + '/angular/angular.min',
     ...
    'jQuery':                       '../bower_components' + '/jquery/dist/jquery',
     ...
    'timezone-js':                  '../bower_components' + '/timezone-js/src/date'
},
shim: {
     ...
    'flot': { deps: ['jQuery','timezone-js']},
    'flot-pie': { deps: ['flot']},
    'flot-time': { deps: ['flot']},
 ...
},

But with this config timezoneJS is undefined when flot.time is loading

[JavaScript][jQuery Datatables] Hiding rows with class "hidden" after change the checkbox

I'm using jQuery datatables. I'd like to hide all rows with class="hidden".

This code:

var table = $('#table1').DataTable();
table.rows('.hidden').hide();

It's not working (rows are not hidden), and I see this text in console:

table.rows(...).hide is not a function

How can I use class="hidden" to hide all rows?

python, tcpServer tcpClient, [WinError 10061]

when I try to run tcpServer and tcpClient on the same local network, it works, but I can't run them on the external network. The OS refuses the connection.

''Main builtins.ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it''

  • I checked whether tcpServer is running or not using netstat, and it is in the listening state.

What am I supposed to do?

Thanks

Save the state of the menu in the Simple Sidebar

In this example: http://startbootstrap.com/template-overviews/simple-sidebar/

What is needed so that the menu does not return to be visible when the page is refreshed?

Because what happens is that when:

(1) menu visible / refresh page / menu visible
(2) menu hidden / refresh page / menu visible

1, is ok, but 2 it's wrong. The correct would be:

(2) menu hidden / refresh page / menu hidden

I have file where at start of line tabs are for tree level, how to count tabs in start of lines

I want to count tabs in the start
of lines and create tree levels

$(".importTree").on("change", function(e) {

    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function(progressEvent){
           var tree = this.result.split('n');
           var tabLvl = [] ;
           for (line in tree) {
                tabLvl.push(tree[line].split(/[^t]/)[0].length)
                console.log(tabLvl);
           };
          //after I split file into lines tabs are disappeared
      };
      reader.readAsText(file);
   };
});

after I split file into lines tabs are disappeared

dimanche 24 juillet 2016

jQuery auto background color transition

I tried many ways I found it very simple for me but one thing I can't figure it out. Changing background automatically is working well but it happens very quickly. I wonder is there a solution to make it slow transition now it is very sharp and not user friendly.

<script>

$("body").css("transition","all 3s");
var colors = ["#c11733","#c0392b","#66cc99","#27ae60","#745380"];
function changeBgColor(){
   $("body").css({
        backgroundColor : colors[parseInt(Math.random() * 3)]
      });
}
//changeBgColor();
setInterval(changeBgColor, 3000);

</script>

Blur() doesn't work for this situation?

Here's my code:

<input id="m" autocomplete="off"/>

and I put the following lines in script

$('#m').on('blur', alert('blurred'););
$('#m').on('focus', alert('focused'););

The result is, it will pop up 'blurred' when the page starts. But afterward, it no longer fires the alert('blurred').

More interesting is, the focus() works well.

Thanks for any suggestion or help.

javascript file local import is not working

-projectName
  --Web Pages
    ---web.jsp
  --js

In the console I got something like this

enter image description here

and this my import stament, i download the dataTables and other jquery file in the js folder.

<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>

Jquery autocomplete response and pushing UI[style] content to JSP

i need a solution to my below problem.i want to push on response of Jquery. on pushing the content it must have style in it. please let me know the solution>>>>>>> anyone.

response : function(event, ui) {
            var a = $("#photo").val();
            ui.content.push({
                label : "<i class='fa fa-plus-circle'></i>"+" "+a,
            });

this fontawesome Icon [i class='fa fa-plus-circle'] is not getting
affected in my jsp page.

How to remove noise from a white region, without losing the shape of the white region

Here's the image:

enter image description here

I want to remove the noise within the white region without losing the shape of the white region. I've tried dilation, but that effects the shape of the white region. I've also tried dilation followed by erosion, and it's the same problem - the shape of the white region gets affected.

Can I use more than 26 letters in `numpy.einsum`?

I am using np.einsum to multiply probability tables like:

np.einsum('ijk,jklm->ijklm', A, B)

The issue is that I am dealing with more than 26 random variables (axes) overall, so if I assign each random variable a letter I run out of letters. Is there another way I can specify the above operation to avoid this issue, without resorting to a mess of np.sum and np.dot operations?

Python element-wise tuple operations like sum

Is there anyway to get tuple operations in Python to work like this:

>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(4,4,4)

instead of:

>>> a = (1,2,3)
>>> b = (3,2,1)
>>> a + b
(1,2,3,3,2,1)

I know it works like that because the __add__ and __mul__ methods are defined to work like that. So the only way would be to redefine them?

Remove delete button on select2 3.5 tag?

I'm referring to Select2 3.5.

I want to hide the close/delete button on one of the tags so that it can't be removed.

I can prevent a specific tag from being removed via the select2-removing event, and calling ev.preventDefault(), however, I also want to visually indicate that it can't be removed.

Is there a way to remove the 'X' beside the tag?

WebKit2.JavascriptResult.get_value() throws exception "TypeError: Couldn't find foreign struct converter for 'JavaScriptCore.Value'".

I am writing a python3 + webkit2 + gtk3 based GUI. Everything works fine, but when I tried to use WebKit2.WebView.run_javascript_finish() in a callback function, getting the return (a WebKit2.JavascriptResult objetc), e extrat the value with WebKit2.JavascriptResult.get_value(), I received a "TypeError: Couldn't find foreign struct converter for 'JavaScriptCore.Value'".

I have a "from gi.repository import JavaScriptCore" on the imports, and I dont know why this error is occuring.

ps: Sorry about my terrible english.

Issue with reading an object binary file in python

I am working on binary files in python for the first time. I managed to write an object to a file, but now as I try to read from the file I get this error.

enter image description here

Here is my code:

import pickle 
with open("Account/10000000.obj",'rb')as fp:
    banana = pickle.load(fp);
print banana.balance;

Thanks for an answer in advance!

GAE Python - MySQL ImportError: dynamic module does not define init function (init_mysql)

I'm using MySQLdb to connect to CloudSQL, it's working on localhost but once I deploy it to server this error is thrown:

ImportError: dynamic module does not define init function (init_mysql)

I'm using MySQLdb within my libs folder, I cannot specify it on my app.yaml because I'm using flexible environments (vm: true).

I've been googling for a long time I've seem some related questions but nothing related specifically to CloudSQL

Thanks a lot!.

next used in a loop python

I am a beginner to python and while examining a piece of a code I found the next() function used in a loop as, I presume a variable.However, when I try to implement a different variable an error occurs. So how could this be and what does this do.

P.S. I am working with generators

for next in graph[vertex] - set(path):
        if next == goal:
            yield path + [next]

        else:
            stack.append((next,path+ [next]))
            print(stack)

How to store the return value of os.system that it has printed to stdout in python?

I am writing a python script which checks for number of active connections for a particular IP / port. For this I use os.system( 'my_command') to grab the output. os.system returns the exit status of the command I've passed it (0 means the command returned without error). How can I store this value which os.system throws to STDOUT in a variable ? So that this variable can used later in the function for counter. Something like subprocess, os.popen can help. Can someone suggest ?

IDLE won't open

I am very new to programming and I am trying to use Python on my computer. I downloaded and installed the program, but when I try to open IDLE, the Windows blue loading circle pops up and then disappears and nothing else happens. I'm using Windows 10 and Python version 3.4.3. I've tried downloading it from different sources, changing the path in environmental variables, repairing Python, and googling answers, but nobody seems to have the answer or even a similar problem. I would greatly appreciate any help.

Pip error when trying to install module

I'm trying to install PyDrive [a wrapper library of the google drive api for python] and pip is giving me this error. It did the same thing when trying to install things like matplotlib or mega.py [a mega.nz api for python].

Here's the error: enter image description here

Anyone got a clue what's going on?

Cheers

Pip error when trying to install Python module

I'm trying to install PyDrive [a wrapper library of the google drive api for python] and pip is giving me this error. It did the same thing when trying to install things like matplotlib or mega.py [a mega.nz api for python].

Here's the error: enter image description here

Anyone got a clue what's going on?

Cheers

Python logger not printing out 'extra' dictionary info

In my python code I pass a dictionary into the logger for example.

extra_info = {"test":"data"}
logger.info("",extra=extra_info)    

My hope is to get the extra info to print and I assumed it was in the message but when I use this format

format=%(asctime)s %(levelname)s %(name)s: %(message)s

The extra_info content are not being printed. I just get the following

2016/06/17 13:10:47 INFO test:

python can't retrieve feed from https in planetplanet

so I recently tried to install planetplanet as a website to aggregate interesting blogpost. and it works fine for blog that uses http, but when it come to https, the feeds doesn't work. and I want to know are there any workaround to enable python to retrieve feeds from sites that uses HTTPS? since planetplanet uses python script to functions so I guess there must be some code that need to be added to make it recognize https feeds and retrieve it. any help would be appreciated. thanks.

How can I parse a log file to JSON

I have a log file (called preprocstats.log) and i would like to know how parse it to a JSON format file using Python 2.6.

The input of the log file is:

Preprocessor Profile Statistics (all)
==========================================================
Num            Preprocessor Layer     Checks      Exits  
===            ============ =====     ======      =====  
 1              httpinspect     0          1          1  
 2                   detect     0         33         33   
... (and more rows)

And i want to parse it to JSON, for example with this output:

{"Num": 1, "Preprocessor": "httpinspect", "Layer": 0, "Checks": 1,   "Exits": 1}
{"Num": 2, "Preprocessor": "detect", "Layer": 0, "Checks": 33, "Exits": 33}
... (and the rest of rows)

Google Bigquery API: How to get the name of temporary table

I know that: The result of query will save in a temporary table. But how to get its name to use in other query. from googleapiclient.discovery import build from googleapiclient.errors import HttpError from oauth2client.client import GoogleCredentials def test(): project_id = "598330041668" credentials = GoogleCredentials.get_application_default() bigquery_service = build('bigquery', 'v2', credentials=credentials) # [START run_query] query_request = bigquery_service.jobs() query_data = { 'query': ( 'SELECT * ' 'FROM [test.names];') } query_response = query_request.query( projectId=project_id, body=query_data).execute() # [END run_query]

Getting percentage complete of an md5 checksum

I am currently getting an md5 checksum as follows: >>> import hashlib >>> f = open(file) >>> m = hashlib.md5() >>> m.update(f.read()) >>> checksum = m.hedxigest() I need to return the checksum of a large video file, that will take several minutes to generate. How would I implement a percentage counter, such that it prints the percentage complete for each percentage while it is running. Something like: >>> checksum = m.hedxigest() 1% done... 2% done... etc.

Possible to resize an image (client side) on an html form before upload?

I have a standard html input form that includes a field for uploading a file (image).

I unfortunatly cannot edit the backend php that processes the file, but I need to resize the images to a certain size.

I was thinking I could pull off this trick by having the images resized by jquery or alternative client side methods, on the form, before the actual submission to the PHP form.

Is this possible? Anyone know of a good method?

Thanks!!!

Change background color on mouseover and remove it after mouseout

I have table which class is forum. My jquery code:

<script type="text/javascript">
    $(document).ready(function() {
        $('.forum').bind("mouseover", function(){
            var color  = $(this).css("background-color");

            $(this).css("background", "#380606");

            $(this).bind("mouseout", function(){
                $(this).css("background", color);
            })    
        })    
    })
</script>

It perfectly works, but is it possible to do it in more efficient way without var color = $(this).css("background-color");. Just after mouseout leave the previous background-color and remove #380606? Thank you.

Python Linear Regression Error

I have two arrays with the following values:

>>> x = [24.0, 13.0, 12.0, 22.0, 21.0, 10.0, 9.0, 12.0, 7.0, 14.0, 18.0,
...      1.0, 18.0, 15.0, 13.0, 13.0, 12.0, 19.0, 13.0]

>>> y = [10.0, 9.0, 22.0, 7.0, 4.0, 7.0, 56.0, 5.0, 24.0, 25.0, 11.0, 2.0,
...      9.0, 1.0, 9.0, 12.0, 9.0, 4.0, 2.0]

I used the scipy library to calculate r-squared:

>>> from scipy.interpolate import polyfit
>>> p1 = polyfit(x, y, 1)

When I run the code below:

>>> yfit = p1[0] * x + p1[1]
>>> yfit
array([], dtype=float64)

The yfit array is empty. I don't understand why.

samedi 23 juillet 2016

Access several columns in an array in Python

I'm new to python and numpy. Suppose I have an array A = np.random.rand(10,100) , how do i access some of its columns easily?

In Matlab I would write something like B = A(:,[2,4,6:10,50:80]). What is the equivalent of this line of code in Python?

I've looked at the examples in http://scipy.github.io/old-wiki/pages/NumPy_for_Matlab_Users.html but none of them answer my question.

Creating a Pandas dataframe from elements of a dictionary

I'm trying to create a pandas dataframe from a dictionary. The dictionary is set up as

nvalues = {"y1": [1, 2, 3, 4], "y2": [5, 6, 7, 8], "y3": [a, b, c, d]}

I would like the dataframe to include only "y1" and "y2". So far I can accomplish this using

df = pd.DataFrame.from_dict(nvalues)
df.drop("y3", axis=1, inplace=True)

I would like to know if it is possible to accomplish this without having df.drop()

Condensing a list of lists in python by duplicates in a certain column

So, I have a list of lists in python like so:

[[a, foo, bar], [a, dog, cat], [b, foo, bar], [c, foo, bar]]

And I want to condense it in to the following:

[[a, bar, cat], [b, bar], [c, bar]]

Where the last two indexes of the 'a' object are the 3rd columns from the first and second instances of the 'a' object in the original list.

How could I go about doing this?

Is it possible to supply a custom objective function of categorical data to xgboost in python?

I have categorical data and an objective function that I'm trying to optimize. In xgboost docs, it's mentioned that you can supply your own objective function but it must return the gradient and hessian. I'm not sure what the hessian or gradient means when I have categorical data. The objective function looks somewhat like this

sum_{all classes i} ((number of correct predictions in class_i) / (number in class i))

Is it possible to create a custom objective function in this case?

Ability to sort plots in a seaborn violin plot?

I created a long violin plot (just for fun) using seaborn, the top of which looks like this:

enter image description here

I would like to sort these violins by their median. Is this possible?

The code:

sns.set(font_scale=2.5)
f, ax = plt.subplots(figsize=(22, 66))
sns.violinplot(x=inspect['SCORE'], y=inspect['CUISINE DESCRIPTION'])

Best GUI for python?

I want to create GUI applications in python.

i searched in google , it returned some results. I read this post and liked Kivy , because with it you can create cross-platform GUI applications, but i can't install it to my distro.

My os Linux Fedora 23, I tried all of the ways but whatever it didn't work, maybe I did something wrong? what can you advice? how to install Kivy or any examples? or another GUI framework?

Python and opencv

I am getting an error that says : Camera component couldnt be enabled: Out of resources (other than memory) or Incorrect buffer length for resolution when I run the following code:

from picamera.array import PiRGBArray
from picamera import PiCamera
import io
import picamera
import cv2
import numpy as mp
import math

camera=PiCamera()
camera.resolution=(640,480)
camera.framerate=1
cap=PiRGBArray(camera,size=(640,480))
for frame in camera.capture_continuous(cap,format="bgr",use_video_port=True):
    img=frame.array
    cv2.imshow('input',img)

How do I use seaborns color_palette as a colormap in matplotlib?

Seaborn offers a function called color_palette, which allows you to easily create new color_palettes for plots.

colors = ["#67E568","#257F27","#08420D","#FFF000","#FFB62B","#E56124","#E53E30","#7F2353","#F911FF","#9F8CA6"]

color_palette = sns.color_palette(colors)

I want to transform color_palette to a cmap, which I can use in matplotlib, but I don't see how I can do this.

Sadly just functions like cubehelix_palette,light_palette,… have an as_cmap paramater. color_palette doesn't unfortunately.

finding values under list python

Below is an example of my JSON file (which is pretty huge). I need to append multiple things. For key2, key3 I have appended easily since it a pretty easy thing, but when I am trying to append value1 and value2 from key1. it gives me TypeError: list indices must be integers, not str.

[
    {
    "key1": [
        {
            "value1": int, 
            "value2": "string", 
            "value3": "string", 
            "value4": "string", 
            "value5": "string", 
            "value6": int
        },
     ],
    "key2": some value,
    "key3": some value,
    },
],    

How to put lines from a text file into paragraphs with python-docx?

So I have a text file with lines of text. I want to iterate through each line and write each one to a paragraph for a Word Document. I've been trying to use python-docx, which is amazing so far, but putting the string into the add_paragraph function makes it output exactly what was copied, including newline code, square brackets, and quotes and all this other stuff.

Is there any way to get rid of this stuff and just send the text to the add_paragraph function?

Bootstrap datepicker display month & year menus

In Bootstrap datepicker, I would like to have the Month & year menus as in jquery Ui datepicker enter image description here

But in Bootstrap date picker, there is no month & year menus and we have to click the month to change the year.

Is it possible to display both Month and Year Menus in the Bootstrap date picker?

django - validate char field as email

Lets say i have model:

class Subscription(models.Model):
    address = models.CharField(max_length=255)

then i create form:

class SubscriptionForm(ModelForm):
    class Meta:
        model = Subscription
        fields = ['address']
    def clean_address(self):
        email = self.cleaned_data['address']
        #VALIDATE HERE IF IT IS EMAIL
        return email

How can i apply email validator to my field without changing model?

EDIT: Is this even possible?

jquery datatables child rows on multiple tables

I've been searching around but can't find any solutions for this problem. If I have multiple tables on a page (tables are generated by code so I have no idea how many of them I'm dealing with) and I initiated datatables as suggested here: https://www.datatables.net/examples/basic_init/multiple_tables.html

how do I get child rows to display hidden rows on each row for all tables?

thanks,

A For Loop to Multiply a Number Repeatedly Python

I want to start with x = 100, then multiply it by 1.1 and get the result (110 in this case) then do the same again with the result.

I want the output to look something like

1.) 100
2.) 110
3.) 121
.
.
.
150.) Result.

I have no idea how to do this; I tried defining x = 100 and y = 1.1x and setting x equal to y at the end of each loop, but I can't get it to work.

Timer for button clicks

We are preparing a "game" button with class function that you click as often as possible to generate (at this time) an increasing random number. However, we want it to stop functioning after a set time period, 10 seconds.

The click code below is for the number generation, but not sure how to create the timer to stop the button, and for testing purposes, display an alert.

$('.click-button').click(function()
{$('.score').html(function(i, val)
{return val - Math.floor(Math.random()* -11);});
});

How to print date in a regular format in Python?

This is my code:

import datetime
today = datetime.date.today()
print today

This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist

This prints the following:

[datetime.date(2008, 11, 22)]

How on earth can I get just a simple date like "2008-11-22"?

Send form elements and array through $.ajax()

I need to pass through $.ajax() method some form elements and an array too. How can i send serialize and array by ajax?

my code bellow:

function loadgraficosajax(){
		var arr = ['331234','142323','327767'];
  
    	var data = $('#p-form').serialize;
  
        $.ajax({
            type: "POST",
            url: "/page/show",
            data: data,
            dataType : 'html',
            success: function (msg) {
                $(document).ajaxComplete(function (event, request, settings) {
                    $('.has-error').removeClass('has-error');

                    $(document).off('ajaxComplete').off('ajaxSend');
                    $('#addajax').html(msg);
                 });
            }
        });
	}

How can you find the most common sets using python?

I have a pandas dataframe where one column is a list of all courses taken by a student. The index is the student's ID.

I'd like to find the most common set of courses across all students. For instance, if the dataframe looks like this:

ID    |     Courses
1           [A, C]
2           [A, C]
3           [A, C] 
4           [B, C]
5           [B, C]
6           [K, D] 
...

Then I'd like the output to return the most common sets and their frequency, something like:

{[A,C]: 3, [B,C]: 2}

Calculate (add up) with dot / comma

I'm trying to add +20,2 to this sum with dot 9990.95 or this sum with comma 9990,95 with js or jquery

<span class="sum">9990.95</span>

var price = $( '.sum' ).text(),
    calc  = parseInt( price, 10 ) + 20,
    total = calc.toFixed( 2 );

Return me 9990 without decimal

I tried like this too

var price = $( '.sum' ).text(),
    calc  = 20,
    total = price + calc;

The output was 9990.9920, which is not correct either.

Is there a way how to do that?

Group django objects under a common date on the template

I have a django model that stores the orders placed by a user on a particular day. On his home page, I need to display the upcoming orders and group the orders which have the same date under one table/div tag.

For eg: All his orders for 15th june 2016 should come as

Order date: 15 june 2016
Order 1 details
order 2 details
...

I have a field order_date in my user-log model but how do i keep those with the same date together?

Comparing password to encrypted passwork using bcryt in Django

I am trying to compare a user entered password field to a password that has been encrypted. I have looked at the documentation and have not been able to find what I have been looking for. I encrypt the password using

pw_bytes = password.encode('utf-8')
hashed = bcrypt.hashpw(pw_bytes, bcrypt.gensalt())

If I re-encrypt the password, it gives me a different hash. How do I deencrypt the password from my db, or re-encrypt the password the user provided so that they match?

Ideas, tools, frameworks to extract ( user, questions, answers) from different online forums? [on hold]

I am good in java. But R, Python is completely new for me. Moreover, this is my graduation project and have limited time left of 3 months. Please suggest me the best way that i can implement fast :

-download forums q & a data for X months (extract user, question , answers )

-do clustering analysis (categorize by topics, most contributors, high scored answers....).

I started by implementing a simple web crawler, but the HTML tag for q & a data changes for each forum /=.

Thanks !!!

Install PIL/Pillow for ubuntu python 2.7

I have successfully installed PIL/Pillow for python 3.4 but I want it for python 2.7. I thought it might be automatically downloaded for 2.7 as well but when I tried the python shell from the terminal, it keeps saying No module named PIL and No module named PILLOW. What can I do? When I try all the installation commands as given in other answers, it says:

Requirement already satisfied (use --upgrade to upgrade): pillow in ./.local/lib/python3.4/site-packages