jeudi 30 juin 2016

Decorator to pass pandas Series into one-column DataFrames

I want to write a decorator that I can use on functions that are written for Pandas DataFrame, so that when they receive an input that is actually a Series (or maybe even an array) it first transforms that input into a one-column Pandas DataFrame out of generality. That way I can make every function work for both DataFrames and series writing functions only for DataFrames.

Something like

@wraps
def does_smt(df, **kwargs):
    for c in df.columns:
        df[c] = do_something(df[c], df.index)
    return df

does_smt(series) # and it also works

I'm not too good with python decorators yet, but judging by Pint's ureg.wraps decorator I'm thinking it can be done. I checked that decorator but, then again, since I'm having trouble understanding decorators, I couldn't figure out how to adapt that. I also searched for a decorator like that already defined in Pandas but there seems to be none.

First question: How can I do that?

Second: Is that recommended, or is there a better way?

Cheers

Scrapy process.crawl() to export data to json

This might be a subquestion of Passing arguments to process.crawl in Scrapy python but the author marked the answer (that doesn't answer the subquestion i'm asking myself) as a satisfying one.

Here's my problem : I cannot use scrapy crawl mySpider -a start_urls(myUrl) -o myData.json
Instead i want/need to use crawlerProcess.crawl(spider) I have already figured out several way to pass the arguments (and anyway it is answered in the question I linked) but i can't grasp how i am supposed to tell it to dump the data into myData.json... the -o myData.json part
Anyone got a suggestion ? Or am I just not understanding how it is supposed to work..?

Here is the code :

crawlerProcess = CrawlerProcess(settings)
crawlerProcess.install()
crawlerProcess.configure()

spider = challenges(start_urls=["http://www.myUrl.html"])
crawlerProcess.crawl(spider)
#For now i am just trying to get that bit of code to work but obviously it will become a loop later.

dispatcher.connect(handleSpiderIdle, signals.spider_idle)

log.start()
print "Starting crawler."
crawlerProcess.start()
print "Crawler stopped."

Visual Studio 2013 MVC - jquery datepicker

I have just begun to create an application in Visual Studio 2013 using MVC. I am trying to use jquery datapicker. I want it to show a datepicker where ever there is a DateTime field. I am creating my controllers using scaffolding (templates).

  1. I have imported the JQuery UI (combined Library).
  2. In the BundleConfig.css I added "~/Content/themes/base/all.css" to the bundles.Add(new StyleBundle("~/Content/css").Include
  3. Additionally added a new bundle --

    bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
           "~/Scripts/jquery-ui-{version}.js));
    
  4. In the _Layout.cshtml I added 2 new Scripts.Render

    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/Scripts/AQB_MON.js")
    
  5. I created my AQB_MON.js with the following

    $(document).ready(function(){
       $(".input[type='datetime']").each(function(){
        $(this).datepicker();
       });
    })
    

All seems to have no affect on any datetime field. Is this due to using scaffolding to create my Controllers/Views? As I was trying to use ToShortDateString() when displaying my datetime fields and came across an issue due to having scaffolding build them.

Tensor Flow all predictions are 0

I'm running the following code for TensorFlow and all the probabilities are NaN and all the predictions are 0. The accuracy works, however. I have no idea how to debug this. Any and all help is appreciated.

x = tf.placeholder("float", shape=[None, 22])
W = tf.Variable(tf.zeros([22, 5]))

y = tf.nn.softmax(tf.matmul(x, W))
y_ = tf.placeholder(tf.float32, [None, 5])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
#cross_entropy = -tf.reduce_sum(tf_softmax_correct*tf.log(tf_softmax  + 1e-50))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init)

for i in range(100):
    batch_xs, batch_ys = random.sample(allTrainingArray,100), random.sample(allTrainingSkillsArray,100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

#test on itself
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print "accuracy", sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys})

probabilities = y
print "probabilities", probabilities.eval(feed_dict={x: allTrainingArray}, session=sess)

prediction=tf.argmax(y,1)
print "predictions", prediction.eval(feed_dict={x: allTrainingArray}, session = sess)

Select2 Autocomplete widget not showing complete list

I've tried using django-autocomplete-light in my project's admin page. I've installed the autocomplete url as explained and as far as I can tell the autocomplete works fine.

url('plant_autocomplete/$',
 autocomplete.Select2QuerySetView.as_view(model=Plant),name='plant_autocomplete',)

My problem is that when I hooked the autocomplete to the admin page, the drop-down list contained just the currently saved value, and not all possible values as its supposed to.

when hooked up to autocomplete

when hooked up to autocomplete

all possible values (should be appearing in the autocomplete) values that should be appearing

Admin form code

class TestForm(forms.ModelForm):
    class Meta:
        model = PlantImage
        fields = ('plant_id', 'owner')
        widgets = {
            'plant_id': autocomplete.ModelSelect2(url='plant_autocomplete')
        }

class PlantImageAdmin(admin.ModelAdmin):
    form = TestForm
admin.site.register(PlantImage, PlantImageAdmin)

In angular2 does enter key trigger any click event on the page?

In the code below removeSelectedCountry() should be called when the span element is clicked and handleKeyDown($event) should be called when there is a keydown event on the div.

@Component({
    selector: "wng-country-picker",
    template: `
    <ul class="CountryPicker-selected" *ngIf="selectedCountries.length > 0">
    <li *ngFor="let country of selectedCountries">
        <span class="Pill Pill--primary" (click)="removeSelectedCountry(country)">
        {{ country.name }}
        </span>
    </li>
    </ul> 
    <div (keydown)="handleKeyDown($event)" class="CountryPicker-input"></div>
`,
providers: [CUSTOM_VALUE_ACCESSOR]
})

But removeSelectedCountry() is called every time enter key is pressed.

To make the code work I had to change the click event to mousedown event. It works fine now.

Can anyone explain why enter key would trigger click event?

@Component({
    selector: "wng-country-picker",
    template: `
    <ul class="CountryPicker-selected" *ngIf="selectedCountries.length > 0">
    <li *ngFor="let country of selectedCountries">
        <span class="Pill Pill--primary" (mousedown)="removeSelectedCountry(country)">
        {{ country.name }}
        </span>
    </li>
    </ul> 
    <div (keydown)="handleKeyDown($event)" class="CountryPicker-input"></div>
`,
providers: [CUSTOM_VALUE_ACCESSOR]
})

$.post(url, data) and fetch(url, {method: 'POST', body: data}) not the same

I stuck on one small function. Trying to rewrite jQuery to JS ES6, and this function works correct:

$('#log-in-btn').on('click', function () {
                $('#login-error-message').empty().hide();
                var url = '/login/auth';
                var data = {
                    email: $('#email').val(),
                    password: $('#password').val()
                };

                var dest = $(this).data('dest');

                $.post(url, data, function (response) {
                    if (!response.result) {
                        $('#login-error-message').html(response.errorMessage).show();
                    } else {
                        if (dest !== '' && dest !== undefined) {
                            location.href = dest;
                        } else {
                            location.href = response.url;
                        }
                    }
                }, 'json');
            }); 

same function on JS return me error massage:

let loginBtn = document.getElementById('log-in-btn');

loginBtn.addEventListener('click', e => {
                    e.preventDefault();

                    let errorMessage = document.getElementById('login-error-message'),
                        dest = loginBtn.getAttribute('data-dest'),
                        data = {
                            email: document.getElementById('email').value,
                            password: document.getElementById('password').value
                        };

                    errorMessage.style.display = 'none';

                    fetch('/login/auth', {method: 'POST', body: data})
                        .then(res => res.json())
                        .then(res => {
                            if (!res.result) {
                                errorMessage.innerHTML = res.errorMessage;
                                errorMessage.style.display = 'block';
                            } else if (dest !== '' && dest !== undefined) {
                                location.href = dest;
                            } else {
                                location.href = res.url;
                            }
                        })
                        .catch(rej => document.getElementById('login-error-message').innerHTML = rej.message);
                });

What I'm doing wrong? just simple post request and in first case it works in second not?

jQuery bootstrap theme switcher

I made a little function to switch from a dark version of my hub to a light version. However, my code isn't working, and I've checked the console and have no errors logged.

Could anyone help me spot the problem? I'm a noob and new with jQuery/Javascript. When I click on the link, it does nothing and no errors are generated.

This is the code:

<li>
    <a id="switch-theme" href="#" rel="tooltip" title="Change style" onclick="return false;">
          <i class="fa fa-paint-brush"></i>
    </a>
</li>

<script>
currentTheme = localStorage['theme'];
if(currentTheme == null) //theme isn't set, just set it to dark.
    currentTheme = "dark";

function themeHandler() {
    $("head link#theme-stylesheet").attr("href", "includes/frontend/theme/bootstrap-" + currentTheme + ".min.css");

    //handle theme switching.
    $("#switch-theme").click(function() {
        var theme = "dark";
        if(currentTheme == "dark") {
            theme = "light";
        }
        localStorage['theme'] = theme;
        currentTheme = theme;
        $("head link#theme-stylesheet").attr("href", "includes/frontend/theme/bootstrap-" + theme + ".min.css");
    });

    //we just want the current theme.
    return false;
}

$(document).ready(function() {
    $("[rel=tooltip]").tooltip();
    themeHandler();
});

</script>

What do I need to do to make this work as I expect?

How to pass a default value for argument from one function definition to a higher one

I'm searching for a good way to pass default values for arguments to a calling function. Let me explain this by example:

def greet(name, greeting='Hello', punctuation='!'):
    return greeting+' '+name+punctuation

def greet_with_hi(name, punctuation='!'):
   return greet(name, 'Hi', punctuation)

This is an example without use but here's my question: How can I omit the default value for the puncuation argument of greet_with_hi? A default value for this argument is already defined in greet.

Solutions I can think of:

  • let it as it is, cons: changing the default value must be done on every function definition instead of only changing it in one place
  • use None as value for default argument and handle None inside greet, cons: special handling
  • use a global "constant" like DEFAULT_PUNCTUATION='!' and use this as value for the default argument, cons: seems not to be very pythonic

I haven't seen a common pattern in APIs and other code. How would you handle this pattern?

wxpython sizers - does WX.EXPAND make a difference in spacers?

Following good advice in the BoxSizer from the ground Up tutorial I am refactoring code to factor out the wx.LEFT/RIGHT/TOP/BOTTOM flags into "spacers" - so:

horizontal_sizer.Add(someControl, 0, wx.LEFT, border)

becomes:

horizontal_sizer.Add((border, 0))
horizontal_sizer.Add(someControl)

For the case above I am sure they are completely equivalent. However if wx.EXPAND and a non zero proportion is specified as in:

horizontal_sizer.Add(someControl, proportion, wx.LEFT | wx.EXPAND, border)

is this below:

horizontal_sizer.Add((border, 0))
horizontal_sizer.Add(someControl, proportion, wx.EXPAND)

completely equivalent to the above ? Visually they do seem identical but is there anything I am missing ? In other words does the wx.EXPAND influence the border and if yes how ?

Of course the examples above are trivial but in complex sizers layouts the above transformation (as suggested in the tutorial) greatly simplifies the code and makes common UI patterns stand out, that were plain unreadable in the mess of OR'ed flags and numbers.

Dataframe conditionl logic

I have a dataframe ('dayData') with the columns 'Power1' and 'Power2'

      Power1         Power2   
 1.049246442   -0.231991505  
-0.950753558    0.276990531  
-0.950753558    0.531481549  
 0             -0.231991505  
-0.464648091   -0.231991505  
 1.049246442   -1.204952258   
 0.455388896   -0.486482523   
 0.879383766    0.226092327   
-0.50417844     0.83687077   
 0.152025349   -0.359237014  

I'm trying to use conditional logic to create the 'resultPower' column. For each row, the logic I'm trying to install is: if (Power1 >= 0 AND Power2 =<0) OR if (Power1 <= 0 AND Power2 >= 0) then 0,return the value for Power1.

So when the resultPower column is added the dataframe would look like:

      Power1         Power2   ResultPower
 1.049246442   -0.231991505             0
-0.950753558    0.276990531             0
-0.950753558    0.531481549             0
 0             -0.231991505             0
-0.464648091   -0.231991505  -0.464648091
 1.049246442   -1.204952258             0
 0.455388896   -0.486482523             0
 0.879383766    0.226092327   0.879383766
-0.50417844     0.83687077              0
 0.152025349   -0.359237014             0

I have used basic conditional logic in pandas before, for example I would be able to check one of the logic conditions i.e.

dayData['ResultPower'] = np.where(dayData.Power1 > 0, 0, dayData.Power1)

but I can't find how I can add logic conditions with AND / OR functions. To build something like

dayData['ResultPower'] = np.where(dayData.Power1 >= 0 and dayData.Power2 =< 0 or dayData.Power1 =< 0 and dayData.Power2 >= 0, 0, dayData.Power1)

Could someone let me know if this is possible and the syntax for doing this please?

Thanks

How to pass ajax data to React component?

I am new to react js.I am just getting a data via ajax and manipulate the data in component.But always I am getting undefined.I Know that my ajax call is working but I don;t know How to Handle that data in component.

App.js

    var React = require('react');
var Actions = require('../actions');
var Store = require('../stores/store');
var Nav =require('./Nav');
var Fakeprofile = require('./Fakeprofile');
var Sidemenu = require('./Sidemenu');
var Bulkmail = require('./Bulkmail');
var store = require('../stores/store');
var api = require('../utils');
function getAppState() {

    return {
        //result:store.setProfile()
        result:api.getprofile()
    }
}


var App = React.createClass({
   getInitialState:function () {
       return getAppState();
   },
    componentDidMount: function(){
        Store.addChangeListener(this._onChange);
    },

    componentUnmount: function(){
        Store.removeChangeListener(this._onChange);
    },



    render:function () {
        console.log(this.state);
        return(
            <div>
                <Nav/>
                <Sidemenu/>
                <Fakeprofile />



            </div>

        )
    },
    _onChange: function(){
        this.setState(getAppState());
    }
});

module.exports = App;

utils.js

var actions = require('./actions');

module.exports = {
  getprofile:function () {
      console.log('Gettinf data');
      var url  = 'http://localhost:3000/api/index';
      $.ajax({
          url:url,
          dataType:'json',
          cache:false,
          success:function success(data) {
              console.log(data);



          },
          error:function error(xhr,status,err) {
              console.log(err);
          }
      })
  }
};

Bootstrap switch button event

I'm using bootstrap switch button. I want to change input value when on text or off text is changed. How can I check if on-text="Android" I want to print android to inp1 text or if off-text="IOS" I want to print ios to inp1 text. İs there another way to check text? You can check online demo http://jsfiddle.net/PNU45/156/

HTML

  <input type="input" id="inp1" value="">
  <input type="input" id="inp2" value="">
  <input type="checkbox" checked="true" class="alert-status" id="btn1" data-size="normal" name="my-checkbox" data-on-text="Android" data-off-text="IOS">
  <input type="checkbox" checked="true" class="alert-status" id="btn2" data-size="normal" name="my-checkbox" data-on-text="Java" data-off-text="C#">

JavaScript

$('.alert-status').bootstrapSwitch('state', true);
$('#btn1').on('switchChange.bootstrapSwitch', function (event, state) {
    var x=$(this).data('on-text');
    var y=$(this).data('off-text');
    if(x=="Android"){
        $("#inp1").val("Android");
    }
    if(y=="IOS"){
        $("#inp1").val("IOS");
    }
});
$('#btn2').on('switchChange.bootstrapSwitch', function (event, state) {
    var x=$(this).data('on-text');
    var y=$(this).data('off-text');
    if(x=="Java"){
        $("#inp2").val("Java");
    }
    if(y=="IOS"){
        $("#inp2").val("IOS");
    }
});

JSON loads fails on invaild escape characters [duplicate]

This question already has an answer here:

I am getting a large data file from external service, where each line is a json object. However, it contains multiple hex characters like (xef,xa0,xa9) etc and some unicode characters like (u2022) .I am basically reading the file like

with open(filename,'r') as fh:
    for line in fh:
        attr = json.loads(line)

I tried giving encoding utf-8 and latin-1 to the open method, but still json loads is failing. If the invalid characters are removed then loads is working, but I don't want to lose any data. What's the recommended way to fix this ?

repr(line) sample:

'{"product_type":"SHOES","recommended_browse_nodes":"361208011","item_name":["Citygate  960561 Ankle Boots Womens  Gray Grau (anthrazit 9) Size: 8 (42 EU)"],"product_description":[],"brand_name":"Citygate","manufacturer":"J H P\xf6lking GmbH & Co KG","bullet_point":[],"department_name":"Women\u2019s","size_name":"42 EU","material_composition":["Leather"]}n'

json.loads is failing at xf6 in item_name with Invalid escape: line 1 column 105 (char 104) .

How to select next ul on click event using jQuery

I was looking in other questions, but I couldn`t find answer.

I have code like this:

<div class="chacter_form">
    <form id="new_character" class="new_character" method="post" accept-charset="UTF-8" action="/users/1/characters">   
        <ul class="no_dot form_partial active_partial"></ul>
        <ul class="no_dot hide form_partial test"></ul>
        <ul class="no_dot hide form_partial"></ul>
    </form>
    <button id="prev_form_button"></button>
    <button id="next_form_button"></button>
</div>

Of course every ul has some number of li. I want to write a jQuery function that when #next_form_button is clicked it will hide first ul and show the second. hide class set display to none.

This is my attempt but it is not working:

$(document).on('click', '#next_form_button', function(){
    $active_partial = $('ul.active_partial')
    $next_partial = $('ul.active_partial').next('ul')
    $active_partial.removeClass('active_partial').fadeToggle()
    $next_partial.addClass('active_partial').fadeToggle()
});

Any help would be appreciated

TensorFlow CNN behaving differently when batch is divided

Initially I had the code working with the following code:

for i in range(1000):
    x_batch = []
    y_batch = []
    cost_ = 0.

    x_batch = x
    y_batch = y_data

    sess.run(train_op, feed_dict={X: x_batch, Y: y_batch, p_keep_conv: 0.8, p_keep_hidden: 0.5})
    cost_ += (sess.run(cost, feed_dict={X: x_batch, Y: y_batch, p_keep_conv: 0.8, p_keep_hidden: 0.5}))
    print(cost_)

But then I realized that I could not use larger datasets because it would quickly use all the memory available. Instead I rewrote the code as follows:

for i in range(1000):
    x_batch = []
    y_batch = []
    cost_ = 0.
    for i in range(0, len(y_data), 100):
        x_batch = x[i:i+100]
        y_batch = y_data[i:i+100]

        sess.run(train_op, feed_dict={X: x_batch, Y: y_batch, p_keep_conv: 0.8, p_keep_hidden: 0.5})
        cost_ += (sess.run(cost, feed_dict={X: x_batch, Y: y_batch, p_keep_conv: 0.8, p_keep_hidden: 0.5}))
    print(cost_)

It is supposed to partition the input in batches to reduce the amount of memory used for the video card. The problem is that now it is not getting the same accuracy as before. The accuracy was 89% with the first code and now it is only 33%.

Predict Chart Growth [on hold]

Lets say I have 500 stock charts: They show the value of a share for a specific date:

enter image description here

With Machine Learning I would like to predict the value for a abitrary stock on the next Date.

I thought I could train my model by looking on the growth rates of the stock values. Lets say I have a stock that costs:

Day1: 100 Day2: 95 Day3: 110 Day4: 110 Day5: 105 Day6: 110  NextDate: My prediction

Then I would look on the growth rates:

Day1: 0% Day2: -5% Day3: 15.78% Day4: 0% Day5: -4.54% Day6: 4.76%  NextDate: My prediction

And would train my model by looking always on 3 following dates and using the forth as label. That would be:

X: [0, -5, 15.78]  Y: 0
X: [-5, 15.78, 0]  Y: -4.54
X: [15.78, 0, -4.54] Y: 4.76

Then to predict the value on the next date I would input:

next_date_growth = model.predict([0, -4.54, 4.76])

I am beginner in machine learning, how would you predict stock prices?And what Sklearn algortithm should I use? Thanks

Select the price in a jquery array and add to Total

i a have a combo box where i can choose specific vehicle, each has engine size, name and price wrapped in an array. If vehicle 1 chosen i want to add their price to the total amount. Here is my code:

HTML

<select id="selector" onChange="Expedisi(this);">
            <option>Select product</option>
          <optgroup label="Sedan">
            <option value="Lancer EX">Lancer EX 1.6 / 2.0</option>
            <option value="Lancer EX GT">Lancer EX GT</option>
          <optgroup label="Sport">
            <option value="Lancer Evolution X">Lancer Evolution X</option>
          <optgroup label="SUV">
            <option value="Outlander">Outlander</option>
        </select>

JavaScript

var data = { 
    "Lancer EX" : { img: "cars/mitsubishi/lancerex.png" , label: "Lancer EX " , engine: "1.6 L" , price :"16500" },
    "Lancer EX GT" : { img: "cars/mitsubishi/gt.png", label: "Lancer EX GT", engine: "2.0 L" , price: "22000"},
    "Lancer Evolution X" : { img: "cars/mitsubishi/evox.jpg", label: "Evolution X", engine:"2.0L Turbocharged", price: "85000" },
    "Outlander" : { img: "cars/mitsubishi/outlander.jpg", label: "Outlander", engine: "2.0 L" , price : "33000" },
};

I want to add the price of the chosen vehicle from the combo box to the Total which is 0 at first. Thank you.

Remove title bar without the cross button from jQuery Dialog box

I have seen multiple answers for this question but have not been able to find any that work.

How do i remove the title bar from a jQueryUI Dialog box while keeping the close button.

I have tried this and it does not work. Also it is not a good solution.

$("#example").dialog(dialogOpts);
// remove the title bar
$(".ui-dialog-titlebar").hide();

I was able to follow this and get rid of the title bar. But this also takes away the close button and because there is no title bar, the dialog box is not draggable anymore.

jquery UI dialog: how to initialize without a title bar?

I tried to follow this fiddle here to get rid of the title bar and keep the close button.

http://jsfiddle.net/NK2qm/2/

However, this modifies the CSS for all dialog boxes and adds a triangle below the dialog box. I want this to happen only for one class of dialog box and minus the triangle at the bottom.

Can someone reply to this question with a fiddle showing how to do it?

Thanks.

Implementing an asynchronous iterator

Per PEP-492 I am trying to implement an asynchronous iterator, such that I can do e.g.

async for foo in bar:
    ...

Here is a trivial example, similar to the one in the docs, with a very basic test of instantiation and async iteration:

import pytest

class TestImplementation:
    def __aiter__(self):
        return self
    async def __anext__(self):
        raise StopAsyncIteration


@pytest.mark.asyncio  # note use of pytest-asyncio marker
async def test_async_for():
    async for _ in TestImplementation():
        pass

However, when I execute my test suite, I see:

=================================== FAILURES ===================================
________________________________ test_async_for ________________________________

    @pytest.mark.asyncio
    async def test_async_for():
>       async for _ in TestImplementation():
E       TypeError: 'async for' received an invalid object from __aiter__: TestImplementation

...: TypeError
===================== 1 failed, ... passed in 2.89 seconds ======================

Why does my TestImplementation appear to be invalid? As far as I can tell it meets the protocol:

  1. An object must implement an __aiter__ method ... returning an asynchronous iterator object.
  2. An asynchronous iterator object must implement an __anext__ method ... returning an awaitable.
  3. To stop iteration __anext__ must raise a StopAsyncIteration exception.

How do I integrate travis ci with codeclimate test coverage in Python?

I'm trying to make my Travis CI send test coverage data to Code Climate service, but documentation on Code Climate and Travis CI do not describe in detail how to do this using Python. Still its supported feature according Code Climate and Travis documentations. I've tried to find any working examples on this without luck and can't make it work on my own.

Code Climate documentation: Setting Up Test Coverage, Readme: codeclimate-test-reporter

Travis CI documentation: Using Code Climate with Travis CI

I've set the CODECLIMATE_REPO_TOKEN in Travis CI as described in this answer: http://stackoverflow.com/a/31281481/1754089

My .travis.yml file:

language: python
python:
  - 2.7
install:
  - pip install -r requirements.txt
  - pip install coverage
  - pip install codeclimate-test-reporter
#commands to run tests:
script:
  - python mytests.py
  - coverage run mytests.py
after_success:
  - codeclimate-test-reporter

as the after_success line is excecuted in Travis it gives me this in log-view:

/home/travis/build.sh: line 45: codeclimate-test_reporter: command not found

xlswrite: Showing variable name in sheet name or somewhere

  1. I am using xlswrite.

I am putting lots of variables into different sheets of one xlsx file.

One variable for one sheet.

So I want to put the name of the variable as the name of the sheet.

I couldn't find any command which does this. So perhaps this should be done by coding some python and having one line in matlab which calls that py file.

  1. If this is impossible, I will just try to put the name of the variable in the first row. However, when the variable has more than 1 column, then it says vertcat doesn't work.

    xlswrite('test.xlsx',vertcat('A', [1 3; 1 2]))

What should I do?

======================

A follow-up question

I coded the following based on Suever's answer.

function xlswr(file_name,varargin)
xlswrite(file_name,varargin{i},inputname(i+1))

However, when I call this function by

xlswr('test.xlsx', A, A(:,2))

then A is printed on test.xlsx, but A(:,2) was not.

Whenever the input is not just whole name like A, but some part of the variable, then it doesn't print it out.

How can I fix this?

Adding Class to Element when it's at the Top of the Screen

I am trying to add class to elements that hit the top of the screen that have been appended either by clicking a button inside a parent DIV or by entering text within the input form.

It works, but not for the appended elements. And when it does work for the appended elements, it's like the offset of those elements get off each time they get appended and then it applies the class to every appended element after that. It's annoying and I've been stuck on this for at least a week now.

The code I am using to add class when the element hit the top of the screen is this:

window.poo = function poo() {
     $("#message").each(function() {


var win = $(".chat-log"),
  nav = $(this),

  pos = nav.offset().top,
  sticky = function() {

    win.scrollTop() > pos ?
       nav.addClass('inactive') :
      nav.removeClass('inactive')
  }

win.scroll(sticky);
});

}

poo();

The elements parent is #message and the #message's parent is .chat-log. I have changed #message to .message but it still gave me the same result.

And when the user clicks the buttons within the parents, the offset gets worse each time and the class is applied to all elements before they even hit the top of the screen.

Fixed navigation on scroll becomes fixed only after it has scrolled off screen

On this site , http://evolutionhire.com/ , I've got a navigation bar which should become fixed when it reaches the top of the screen . However it is not performing as expected in that it becomes fixed a couple of hundred pixels after scrolling off screen as opposed to when it hits the top

<ul class="menu">
    <li><a href="#camera">CAMERA</a></li>
    <li><a href="#lighting">LIGHTING</a></li>
    <li><a href="#sound">SOUND</a></li>
    <li><a href="#grip">GRIP</a></li>
    <li><a id="consumables" class="open-consumables">CONSUMABLES</a></li>
    <li><a href="#contact">CONTACT</a></li>
</ul>

This is the class that's added

.fixed {
position: fixed;
top: 0;
}

And the jquery to implement the class

(function ($) {
"use strict";

var menuPosition = function () {
    var nav = $(".menu"),
        height = nav.outerHeight(),
        windowHeight = $(window).height();

    if ($(window).scrollTop() > (windowHeight - height))
        nav.addClass('fixed');
    else 
        nav.removeClass('fixed');        
};

menuPosition();
$(document).scroll(menuPosition);
}(jQuery)); 

jquery: How to sorti divs by data: getting bad results

I want to sort that by usernames:

<div id="listPerformers">
  <div class="performer" data-username="lula">lula</div>
  <div class="performer" data-username="hotesse1">hotesse1 </div>
  <div class="performer" data-username="marina">marina</div>
  <div class="performer" data-username="sabrina">sabrina</div>
  <div class="performer" data-username="aaa">aaa</div>
  <div class="performer" data-username="hotesse2" >hotesse2 </div>
  <div class="performer" data-username="julia">julia</div>
  <div class="performer" data-username="misssexy">misssexy</div>
  <div class="performer" data-username="guitarreblack">guitarreblack</div>
  <div class="performer" data-username="blacklove">blacklove</div>
  <div class="performer" data-username="ddd">ddd</div>
  <div class="performer" data-username="eee">eee</div>
  <div class="performer" data-username="anna">anna</div>
</div>

And I do use that jscript

$('.performer').sort(function(a,b){
   return a.dataset.username > b.dataset.username
}).appendTo('#listPerformers')

http://jsfiddle.net/ore0zqxt/

Problem is: it is badly sorted:

julia

anna

comes in first positions !

Color switching button with jquery

I have this example code to highlight specific cells of a table. Is there a way to switch colors or use multiple colors at the same time?

I am trying to make a button to switch the color of hightlighting. By default when a value is selected, it is highlighted in green color. I would like to have a button so that when I click, my next selection will be a different color. So every time I click this button, the next selection will be a different color. is there a simple way to achieve this?

Here is the fiddle https://jsfiddle.net/g28xasd7/ and my code:

$('.selector').each(function() {
    $(this).on('click', check);
});

$('.all').each(function() {
    $(this).on('click', all);
});

function all(event) {
    if ($(this).is(':checked')) {
        $("input:checkbox:not(:checked)", $(this).parents('form')).not(this).prop("checked", "checked");
    } else {
        $("input:checkbox(:checked)", $(this).parents('form')).not(this).prop("checked", "");
    }

    //$('.selector').prop("checked", this.name === "SelectAll");

    check(event);
}

function check(event) {
    var checked = $(".selector:checked").map(function() {
        return this.name
    }).get()
    $('td').removeClass("highlight").filter(function() {
        return $.inArray($(this).text(), checked) >= 0
    }).addClass("highlight")
    if ($(this).is(".selector"))
        $('.all').not(this).prop("checked", false)
}

Or is there another way to change the color?

mercredi 29 juin 2016

Select option in dynamically generated select (dropdown) list

I am using a combination of two dropdown lists (select). Depending on the choice a user makes in the first list, the second one gets populated by a

$("#second-choice").load("textdata/" + $('#first-choice').val() + ".txt") call. Using the same combo of lists in another part of the webpage, I am saving the selections that the user has made as indexes (the first choice gets saved as 0 etc.). I then repopulate and select the user's choice via nth-child(whatIhaveSaved).

What I am unable to do, however, is make this selection in the second list (i.e. it does load the list data, but does not select anything, no matter the value it reads). What can be done about that?

I am unable to add much more code, so in essence what happens and what I want to do is:

 $("#first-choice").change(function() {
        $("#second-choice").load("textdata/" + $(this).val() + ".txt");
    });

All the other settings I want to save, work great by using:

$('#first-choice option:nth('+ parseInt(savedPresets[0]) +')').attr("selected","selected");

Once this setting, for example, gets applied, the second list gets populated as well. However, the following similar call for the second list, seems to be getting ignored.

Unfortunately, I am not much experienced with jQuery

xterm not working in mininet

I'm using mininet version 2.1.0. My setup is such that I've to run the mininet command from a remote machine, e.g.,

ssh -X user@IP python mininet.py

X11 forwarding seems to be fine. X forwarding does not work from the mininet shell only, but it works from the SSH shell.

However, I'm unable to run xterm command on mininet. I'm not getting any output after running the xterm command.

mininet> pingall
*** Ping: testing ping reachability
h1 -> h2 h3
h2 -> h1 h3
h3 -> h1 h2
*** Results: 0% dropped (6/6 received)
mininet> xterm h1
mininet> h1 xterm
Warning: This program is an suid-root program or is being run by the root user.
The full text of the error or warning message cannot be safely formatted in
this environment. You may get a more descriptive message by running the 
program as a non-root user or by removing the suid bit on the executable.
xterm: Xt error: Can't open display: %s

When I start the mininet from my local machine, xterm works and opens up a new window.

Where should I look for xterm related logs in such case?

I've already spent over a day on this. I also updated mininet version to the latest 2.2.1, but still no success.

Thanks in advance!

Too much recursion on ajax request

Here is the code of my register.js page:

$(document).on('pagecreate', '#register', function() {
    $('#submit').click(function() {
        $('.frmFields').removeClass('error');
        var errors = 0;

        var fields = {
            username: $('#username'),
            name: $('#name'),
            email: $('#email'),
            password: $('#password'),
            vPassword: $('#password_verify'),
            dob: $('#dob')
        };

        $.each(fields, function(key, value) {
            if (value.val() == '') {
                value.addClass('error');
                errors++;

                alert('שדה ' + key + ' הינו שדה חובה');
            }

            if (key == 'name') {
                if (!isText(value.val())) {
                    value.addClass('error');
                    errors++;

                    alert('שדה שם חייב להכיל טקסט בלבד');
                }
            }

            if (key == 'email') {
                if (!isEmailAddress(value.val())) {
                    value.addClass('error');
                    errors++;

                    alert('שדה דואר אלקטרוני חייב להכיל כתובת תקנית');
                }
            }
        });

        if (fields.password.val() != fields.vPassword.val()) {
            vPassword.addClass('error');
            errors++;

            alert('הסיסמאות שהקלדת אינן זהות');
        }

        function checkUsername(uname) {
            var valid = false;

            $.ajax({
                url: './actions/checkUsername.php',
                type: 'GET',
                async: false,
                data: {
                    username: fields.username.val()
                },
                success: function(resp) {
                    if (resp == "success")
                        $('#valid').val('true');
                    else
                        $('#valid').val('false');
                }
            });
        }

        checkUsername(fields.username.val());

        if ($('#valid').val() == 'true') {
            $.ajax({
                url: './actions/register.php',
                type: 'POST',
                data: fields,
                success: function(resp) {
                    if (resp == "success") {
                        alert('yay!');
                    } else
                        alert(resp);
                }
            });
        } else
            alert('שם המשתמש שבחרת תפוס');
    });
});

Everything is working fine, the data is being sent correctly, only that I get an error:

too much reccursion

It happens because of the last $.ajax call. I tried it with $.post and it does the same.

How can I do this correctly so I won't get this error?

Some troubles w/ jQuery dialog closing

Have some partial view with own button, which is returned to the jq dialog. After clicking the button on the partial view, i need that jq dialog get closed. The following script does close the dialog, but it doesnt send data on the server. So it closes the form before sending it. Can you help please?

Script:

 <script>
        $(".close1").on("click", function (e) {
            e.preventDefault();
            $(this).closest(".dialog").dialog("close");
        });
    </script>

Partial View:

@model ManualSite.Models.Student
<div id="myform">
   @using (Ajax.BeginForm("Create", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "results"}))
   {
        @Html.HiddenFor(model => model.Id)
        @Html.LabelFor(model => model.Name)
        <br />
        @Html.TextBoxFor(model => model.Name)
        <br /><br />
        @Html.LabelFor(model => model.Surname)
        <br />
        @Html.TextBoxFor(model => model.Surname)
        <br /><br />
        @Html.LabelFor(model => model.Gpa)
        <br />
        @Html.TextBoxFor(model => model.Gpa)
        <br /><br />

    <input type="submit" name="createSubmit" value="Create" class="close1"/>
   }


</div>

jQuey Dialog:

$(document).ready(function () {
$.ajaxSetup({ cache: false });
$(".viewDialog").on("click", function (e) {
    e.preventDefault();
    $("<div></div>")
        .addClass("dialog")
        .appendTo("body")
        .dialog({
            title: $(this).attr("data-dialog-title"),
            close: function () { $(this).remove() },
            modal: true,
        })
        .load(this.href);

});

});

How to get value from onclick() Button to input jquery

i am trying to create a color picker, whenever i click on a colored button, the respective color name gets sent to the input automatically; if i click on white button i get in input : White and so on ... Here is my code so far:

HTML

function changewhite() {
    document.getElementById("color").innerHTML="White";
}
function changeblack() {
    document.getElementById("color").innerHTML="Black";
}
function changered() {
    document.getElementById("color").innerHTML="Red";
}
function changeblue() {
    document.getElementById("color").innerHTML="Blue";
}
function changeyellow() {
    document.getElementById("color").innerHTML="Yellow";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>Color:</label>

<td width="314"><input name="white" type="button" id="white" onclick="changewhite()" value="" width="20px" />
<input name="black" type="button" id="black" onclick="changeblack()" value="" width="20px" />
<input name="red" type="button" id="red" onclick="changered()" value="" width="20px" />
<input name="blue" type="button" id="blue" onclick="changeblue()" value="" width="20px" />
<input name="yellow" type="button" id="yellow" onclick="changeyellow()" value="" width="20px" />

NB: I would like to add that before using an input to get the color, i was using <p id="color"> </p>, the code was working perfectly, but don't know why with an input it didnt work.

Dataframe conditional logic

I have a dataframe ('dayData') with the columns 'Power1' and 'Power2'

      Power1         Power2   
 1.049246442   -0.231991505  
-0.950753558    0.276990531  
-0.950753558    0.531481549  
 0             -0.231991505  
-0.464648091   -0.231991505  
 1.049246442   -1.204952258   
 0.455388896   -0.486482523   
 0.879383766    0.226092327   
-0.50417844     0.83687077   
 0.152025349   -0.359237014  

I'm trying to use conditional logic to create the 'resultPower' column. For each row, the logic I'm trying to install is:

if (Power1 >= 0 AND Power2 =<0) OR if (Power1 <= 0 AND Power2 >= 0) then 0, return the value for Power1.

So when the resultPower column is added the dataframe would look like:

      Power1         Power2   ResultPower
 1.049246442   -0.231991505             0
-0.950753558    0.276990531             0
-0.950753558    0.531481549             0
 0             -0.231991505             0
-0.464648091   -0.231991505  -0.464648091
 1.049246442   -1.204952258             0
 0.455388896   -0.486482523             0
 0.879383766    0.226092327   0.879383766
-0.50417844     0.83687077              0
 0.152025349   -0.359237014             0

I have used basic conditional logic in pandas before, for example I would be able to check one of the logic conditions i.e.

dayData['ResultPower'] = np.where(dayData.Power1 > 0, 0, dayData.Power1)

but I can't find how I can add logic conditions with AND / OR functions. To build something like:

dayData['ResultPower'] = np.where(dayData.Power1 >= 0 and dayData.Power2 =< 0 or dayData.Power1 =< 0 and dayData.Power2 >= 0, 0, dayData.Power1)

Could someone let me know if this is possible and the syntax for doing this please?

Dataframe reproduction

import pandas as pd
from io import StringIO

datastring = StringIO("""
      Power1         Power2   
 1.049246442   -0.231991505  
-0.950753558    0.276990531  
-0.950753558    0.531481549  
 0             -0.231991505  
-0.464648091   -0.231991505  
 1.049246442   -1.204952258   
 0.455388896   -0.486482523   
 0.879383766    0.226092327   
-0.50417844     0.83687077   
 0.152025349   -0.359237014  
""")

df = pd.read_table(datastring, sep='ss+', engine='python')

How to resolve Python KeyError elegantly (Python csv library)

I have written a basic web scraper in Python using the lxml and JSON libraries. The below code snippet details how I currently write to CSV:

with open(filepath, "ab") as f:

                write = csv.writer(f) 

                try:
                    write.writerow(["allhomes",
                                    statenum,
                                    statesubnum,
                                    suburbnum,
                                    listingnum,
                                    listingsurlstr,
                                    '',  # fill this in! should be 'description'
                                    node["state"],
                                    node["suburb"],
                                    node["postcode"],
                                    node["propertyType"],
                                    node["bathrooms"],
                                    node["bedrooms"],
                                    node["parking"],
                                    pricenode,
                                    node["photoCount"],
                                    node2["pricemin"],
                                    node2["pricemax"],
                                    node2["pricerange"]])
                except KeyError, e:
                    try:
                        write.writerow(["allhomes",
                                        statenum,
                                        statesubnum,
                                        suburbnum,
                                        listingnum,
                                        listingsurlstr,
                                        '',  # fill this in! should be 'description'
                                        node["state"],
                                        node["suburb"],
                                        node["postcode"],
                                        node["propertyType"],
                                        '',
                                        node["bedrooms"],
                                        node["parking"],
                                        pricenode,
                                        node["photoCount"],
                                        node2["pricemin"],
                                        node2["pricemax"],
                                        node2["pricerange"]])
                    except KeyError, e:
                            errorcount += 1
                            with open(filepath, "ab"):  #
                                write = csv.writer(f)
                                write.writerow(["Error: invalid dictionary field key: %s" % e.args,
                                                statenum,
                                                statesubnum,
                                                suburbnum,
                                                listingnum,
                                                listingsurlstr])
                    pass
                pass

The problem is such that if a certain node does not exist (most commonly the Bathrooms node) I have to try again by replacing the Bathrooms node with a blank value, or subsequently give up the entire row of data. My current approach is to try again and write the row by removing the Bathrooms node, but this is messy (and does not fix KeyErrors with other nodes).

How can I pass over writing a single node in this situation if it does not exist or does not contain any data, without sacrificing the whole entry?

Many thanks.

Executing a Python file with Ajax

I am trying to run a python script on page load. The python script will save a log.text file with some log information. After doing some research I came up with:

    <script>
    window.onload = function () {
        $.ajax({
            type: 'POST',
            url: "img/test.py",
            success: function () {
                alert("working")
            },
            error: function () {
                alert("Not Working")
            }
        });
    };
</script>

Which works, everytime the page loads it alerts me that it was successful. And here is test.py:

#!/usr/local/bin/env python

try:
    txt = open(r'log.txt', "wb")
    txt.write("Success")
    txt.close()
except Exception,e:
    txt = open(r'log.txt', "wb")
    txt.write(e)
    txt.close()

But this is where the problem is. The file is not created and I don't know why.

More information: I am using godaddy as a hosting service. My script is written in python2.6. When I ssh in and use:

$ python path_to_file/test.py

It creates the file in the current cd location. So the server can run the file with python but when i use:

$ cd path_to_file
$ ./test.py

I get:

-bash: ./test.py: Permission denied

Is that a problem or is this normal? Everything else works I just seem to be missing one piece of this puzzle. Is my shebang statement correct? Why does my process not generate a log.txt file?

By group, plot highest quantile data vs lowest, and capture stats

I wish to group a dataset by "assay", then compare intensities for small cells versus large cells. The problem I have is that in writing my code I only understand how to group the top and bottom cellArea quantiles of the entire dataFrame, rather than for each individual assay ('wt' and 'cnt').

As a final point, I would like to compare the mean values between the intensities of the two groups for each assay type...

from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df = DataFrame({'assay':['cnt']*10+['wt']*10,
                'image':['001']*10+['002']*5+['001']*5,
                'roi':['1']*5+['2']*5+['3']*5+['1']*5,
                'cellArea':[99,90,50,2,30,65,95,30,56,5,33,18,98,76,56,72,12,5,47,89],
                'intensity':[88,34,1,50,2,67,88,77,73,3,2,67,37,34,12,45,23,82,12,1]},
               columns=['assay','image','roi','cellArea','intensity'])

df.loc[(df['cellArea'] < df['cellArea'].quantile(.20)),'group'] = 'Small_CellArea'
df.loc[(df['cellArea'] > df['cellArea'].quantile(.80)),'group'] = 'Large_CellArea'
df = df.reset_index(drop=True)

sns.violinplot(data=df,y='intensity',x='assay',hue='group',capsize=1,ci=95,palette="Set3",inner='quartile',split=True, cut=0)
plt.ylim(-20,105)
plt.legend(loc='center', bbox_to_anchor=(0.5, 0.08), ncol=3, frameon=True, fancybox=True, shadow=True, fontsize=12)

enter image description here

enter image description here

Assign background image url to a div within a template

I have a function, drawPlaceDetails that assigns values to a html template. getPhotoURL() function returns a url link to the image. I need to assign this url to background-image property. All I get is an empty div with no image. I have validated the url's by printing them to the console and they seem to open up an image.

The template code and function is as follows:

<script type="text/html" id="places-template">
  <li>   
  <div class="placesCard">   
    <div id= "places-name" class="places-name">${name}</div>
    <div id= "places-img" style="height:40px;width:40px; border:1px black solid"></div>
    <div id="places-address" class="places-address">${formatted_address}</div> 
  </div>  
</li> 

function drawPlaceDetails(results){
 $("#places-list").append("<ul></ul>");
 for(var i=0; i<results.length; i++){
 var result = results[i];
 console.log(result);  
 var photo = getPhotoURL(result.photos);    
 $("#places-template").tmpl(result).find("#places-img")[0].style.backgroundImage = "url('" + photo + "')";
 $("#places-template").tmpl(result).appendTo( "ul" );
 }
}

function getPhotoURL(photos){ 
  if(photos){
  return photos[0].getUrl({'maxWidth': 35, 'maxHeight': 35});     
}

enter image description here enter image description here

Python multiprocessing creates sub-process using wrong function

I'm trying to write code that create sub-process using another module(demo_2.py),
and exit program if i get wanted value on sub-processes.

But result looks like this.

Unexpected action on my code. This is a screenshot of the result

It seems that demo_1 makes two sub-process that run demo_1 and load demo_2.
I want to make sub-process only runs demo_2.

What did i missed?

demo_1.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from multiprocessing import Process,Queue
import sys
import demo_2 as A

def multi_process():
    print ("Function multi_process called!")
    process_status_A = Queue()
    process_status_B = Queue()
    A_Process = Process(target = A.process_A, args = (process_status_A,))
    B_Process = Process(target = A.process_A, args = (process_status_B,))
    A_Process.start()
    B_Process.start()
    while True:
        process_status_output_A = process_status_A.get()
        process_status_output_B = process_status_B.get()
        if process_status_output_A == 'exit' and process_status_output_B == 'exit':
            print ("Success!")
            break
    process_status_A.close()
    process_status_B.close()
    A_Process.join()
    B_Process.join()
    sys.exit()


print ("demo_1 started")
if __name__ == "__main__":
    multi_process()

demo_2.py

class process_A(object):
    def __init__(self, process_status):
        print ("demo_2 called!")
        process_status.put('exit')
    def call_exit(self):
        pass

How can I stop a video when it is replaced (Jquery)?

Jquery:

$(function () {

$('.videos').hide();
$(".bat").click(function () {
    $('.videos').hide();
    $('.morcego').slideDown();
    $('.default').replaceWith(".morcego");
});
$('.hit').click(function () {
    $('.videos').hide();
    $('.careca').slideDown();
    $('.default').replaceWith(".careca");
});
$('.metro').click(function () {
    $('.videos').hide();
    $('.metro-last').slideDown();
    $('.default').replaceWith(".metro-last");
    });
});

HTML: ` Watch and listen our reviews

        <iframe width="900" height="400" src="https://www.youtube.com/embed/tl39XPeb7UE?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen class="videos morcego img-responsive"></iframe>

        <iframe width="900" height="400" src="https://www.youtube.com/embed/g7uYfhWNvrA?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen class="videos careca img-responsive"></iframe>

        <iframe width="900" height="400" src="https://www.youtube.com/embed/FDIjP6X9f98?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen class="videos metro-last img-responsive">></iframe>

    </div>

    <div class="videos-list-video">
        <h3 class="align-center">Popular Videos</h3>
        <div class=img-list>

            <img src="img/batman_videos.jpg" class="img-responsive bat">
        </div>
        <div class=img-list>

            <img src="img/hitman_videos.jpg" class="img-responsive hit">
        </div>
        <div class=img-list>

            <img src="img/metro_videos.png" class="img-responsive metro">
        </div>


    </div>

</div>

The program works fine but when the video is replaced, the other one won't stop playing and you hear it. I guess i can't use the replaceWith() method...any suggestions? Thanks

Using jquery to hide and show div element not working

I have a woocommerce product page - here is the link - http://icestartup.com/testsites/ujsnkfvs22/wordpress/product/2-door-wardrobe/

This is a woocommerce product page.

In that page I am trying to hide and show a div tag when I am changing the select menu called "Pick Your Laminate".

Here is the code I used - Note that "pick-your-laminate" is the id of the select tag.

<script type="text/javascript">
$(document).ready(function(){
    $("#pick-your-laminate").change(function(){
        if($(this).children("option").attr(":selected")=="Plain Laminate"){
            $(".box").not(".plain").hide();
            $(".plain").show();
        }
        if($(this).children("option").attr(":selected")=="Digital Laminate"){
            $(".box").not(".digital").hide();
            $(".digital").show();
        }
    });
});
</script>

This did not work. I mean, nothing happened at all when i changed the select menu options. So I made the code more simple and i just thought I will make an alert box display when I change the dropdown menu. Heres the new code -

<script type="text/javascript">
$(document).ready(function(){
    $("#pick-your-laminate").change(function(){
       alert( "Handler for .change() called." );
    });
});
</script>

Still NOTHING HAPPENED.

What is going on? Can you guys find the problem?

You can verify by inspecting the webpage where the code is placed, that will be too nice.

Link here

scikit-learn DBN encoding string labels

I am quite new to both python and scikit-learn. My goal is to get a classification working that should the divide into 6 different string labels with a deep belief net.

I get my data that consists 11 columns like that:

input_file = "Downloads/data.csv"
df = pd.read_csv(input_file, header = 0)
original_headers = list(df.columns.values)
df = df._get_numeric_data()
numeric_headers = list(df.columns.values)
reverse_df = df[numeric_headers]
numpy_array = reverse_df.as_matrix()
X, Y = numpy_array[:,1:], numpy_array[:,0]

Then I do:

# Splitting data
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)

# Data scaling
min_max_scaler = MinMaxScaler()
X_train = min_max_scaler.fit_transform(X_train)

# Training
classifier = SupervisedDBNClassification(hidden_layers_structure=[256, 256],
                                         learning_rate_rbm=0.01,
                                         learning_rate=0.001,
                                         n_epochs_rbm=20,
                                         n_iter_backprop=100,
                                         l2_regularization=0.0,
                                         activation_function='relu')
classifier.fit(X_train, Y_train)

# Test
X_test = min_max_scaler.transform(X_test)
Y_pred = classifier.predict(X_test)
print 'Done.nAccuracy: %f' % accuracy_score(Y_test, Y_pred)

But that it says me: ValueError:

Can't handle mix of unknown and binary

I think I have to do something like the following statements with the data, but I am not sure how to perform it on the data correctly:

le = preprocessing.LabelEncoder()
le.fit(["Class A", "Class B", "Class C", "Class D", "Class E", "Class F"])

Thank you!

Python: Deleting an object from a class from Tkinter

How do I delete a ball after it has been created? I created a class for a ball and have an array generating 20 balls on screen. The balls are created in random positions with random speeds. When the ball is clicked on, it is supposed to disappear. I can't seem to get this to function properly. Please help.

   from Tkinter import *
    import random
    import time
    import math
    import pygame

    canvasWidth=480
    canvasHeight=320


    root= Tk()
    canvas=Canvas(root,width=canvasWidth,height=canvasHeight, bg='white')
    root.title('RaspPi')
    canvas.pack()

    class Ball:
        def __init__(self):
                self.ballSize = 30
                self.xposition = random.randint(0 + self.ballSize, canvasWidth - self.ballSize)
                self.yposition = random.randint(0 + self.ballSize, canvasHeight - self.ballSize)
                self.shape=canvas.create_oval(self.xposition,self.yposition,self.xposition+self.ballSize,self.yposition+self.ballSize, fill='black',activefill="grey",width=0,tag="shape")
                self.xspeed=0
                self.yspeed=0
                self.ballDeleted=False
                canvas.tag_bind("shape","<Button-1>",self.ballDelete)
                while self.xspeed<=0.5 and self.xspeed>=-0.5:
                    self.xspeed = random.randrange(-3,3)
                while self.yspeed <= 0.5 and self.yspeed >= -0.5:
                    self.yspeed = random.randrange(-3,3)



        def move(self):
            canvas.move(self.shape, self.xspeed, self.yspeed)
            pos = canvas.coords(self.shape)
            if pos[2] >= canvasWidth or pos[0] <= 0:
                self.xspeed = -self.xspeed
            if pos[3] >= canvasHeight or pos[1] <= 0:
                self.yspeed = -self.yspeed

        def ballDelete(self,event):
            canvas.delete(self.shape)



    balls=[]
    for i in range(20):
        balls.append(Ball())

    while True:
        for ball in balls:
            if ball.ballDeleted==False:
                ball.move()
            else:
                balls.remove(ball)
        root.update()
        time.sleep(0.01)

    root.

mainloop()

D3.js animation for donut labels

I already have a donut chart in d3.js.

The animation for the labels is some thing like this right now :

starting point of labels : the labels are all in the center of the donut

ending point : they end up going behind the arcs.

Now below is what i am trying to achieve....

what i want to achieve :

I want to change the starting point of labels.

I want the labels to appear from behind the arcs of the donuts instead of the center.

The ending point is fine like it is now.

Is there a way i can achieve this ?

i.e change the emission point of the labels instead from the center they should appear from behind the arcs.

Here is the code that i am trying to modify :

 var text=svg.selectAll('text')
  .data(pie(dataset.data))
  .enter()
  .append("text")
  .transition()
  .duration(1000)
.attr("transform", function (d) {
    console.log(d);
    console.log(arc.centroid(d));
     var c = arc.centroid(d),
            x = c[0],
            y = c[1],
            h = Math.sqrt(x*x + y*y);
   return "translate(" + (x/h * labelr) +  ',' +
           (y/h * labelr) +  ")";
  })
  .attr("dy", ".4em")
  .attr("text-anchor", "middle")
  .text(function(d){
      return d.data +"%";
  })
  .style({
      fill:'#000',
      'font-size':'11px'
  });   

Below is the link to the fiddle :

https://jsfiddle.net/ahc4wdjk/

Convert datatime to milliseconds since midnight UTC or localized in CSV file using Pandas

import pandas as pd
import numpy as np
from datetime import datetime, time


# history file and batch size for processing.

historyFilePath = 'EURUSD.SAMPLE.csv'
batch_size = 5000


# function for date parsing
dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')


# load data into a pandas iterator with all the chunks
ratesFromCSVChunks = pd.read_csv(historyFilePath, index_col=0, engine='python', parse_dates=True,
                                 date_parser=dateparse, header=None,
                                 names=["datetime", "1_Current", "2_BidPx", "3_BidSz", "4_AskPx", "5_AskSz"],
                                 iterator=True,
                                 chunksize=batch_size)



# concatenate chunks to get the final array
ratesFromCSV = pd.concat([chunk for chunk in ratesFromCSVChunks])

# save final csv file
df.to_csv('EURUSD_processed.csv', date_format='%Y-%m-%d %H:%M:%S.%f',
             columns=['1_Current', '2_BidPx', '3_BidSz', '4_AskPx', '5_AskSz'], header=False, float_format='%.5f')

I am reading a CSV file containing forex data in the format

    2014-08-17 17:00:01.000000,1.33910,1.33910,1.00000,1.33930,1.00000
    2014-08-17 17:00:01.000000,1.33910,1.33910,1.00000,1.33950,1.00000
    2014-08-17 17:00:02.000000,1.33910,1.33910,1.00000,1.33930,1.00000
    2014-08-17 17:00:02.000000,1.33900,1.33900,1.00000,1.33940,1.00000
    2014-08-17 17:00:04.000000,1.33910,1.33910,1.00000,1.33950,1.00000
    2014-08-17 17:00:05.000000,1.33930,1.33930,1.00000,1.33950,1.00000
    2014-08-17 17:00:06.000000,1.33920,1.33920,1.00000,1.33960,1.00000
    2014-08-17 17:00:06.000000,1.33910,1.33910,1.00000,1.33950,1.00000
    2014-08-17 17:00:08.000000,1.33900,1.33900,1.00000,1.33942,1.00000
    2014-08-17 17:00:16.000000,1.33900,1.33900,1.00000,1.33940,1.00000

How do you convert from Datatime in the CSV file or pandas dataframe being read to EPOCH time in MILLISECONDS from MIDNIGHT ( UTC or localized ) by the time it is being saved. Each file Starts at Midnight every day . The only thing being changed is the format of datetime to miilliseconds from midnight every day( UTC or localized) . The format i am looking for is:

    43264234, 1.33910,1.33910,1.00000,1.33930,1.00000
    43264739, 1.33910,1.33910,1.00000,1.33950,1.00000
    43265282, 1.33910,1.33910,1.00000,1.33930,1.00000
    43265789, 1.33900,1.33900,1.00000,1.33940,1.00000
    43266318, 1.33910,1.33910,1.00000,1.33950,1.00000
    43266846, 1.33930,1.33930,1.00000,1.33950,1.00000
    43267353, 1.33920,1.33920,1.00000,1.33960,1.00000
    43267872, 1.33910,1.33910,1.00000,1.33950,1.00000
    43268387, 1.33900,1.33900,1.00000,1.33942,1.00000

Any help is well appreciated ( short & precise in Python 3.5 or Python 3.4 and above with Pandas 0.18.1 and numpy 1.11 )

checking if key's already in dictionary with try except

I'm using a dictionary to count how many times different items appear in a dataset. In the init of the class, I create the property as a dictionary like this

self.number_found = {}

The first time I find any particular item, I would get a KeyError if I try to do this because the item isn't in the dictionary yet

self.number_found[item] = 1

so I ended up creating a function that checks if an entry is already in the dictionary and if not, adds it for the first time

 def _count_occurrences(self, item):

    try:
        #this checks to see if the item's already in the dict
        self.number_found[item] = self.number_found[item] + 1
        x = self.number_found[item] 
    except KeyError:
        x = 1
        #this adds an item if not in the dict
        self.number_found[item] = x
        return x

However, this is not working as intended if I find a second occurrence of an item in a dataset.

Let's say there are two 'elephant' in my dataset. When I print self.number_found to the console this is what I get

{'elephant': 1}
{'elephant': None}

and I get this error when adding the second occurrence

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Question: what's the right way to check if the key's already in the dictionary (with an explanation as to why the 1 is changing to a None)

Backend extension not working with other libraries

in my custom extension for typo3 which is ported from 6.2.9 to 7.6.9 I want to use jquery and bootstrap.js

But if I use both one of them is not working well.

in my layoutfile I define this:

<f:be.container>

    <script src="{f:uri.resource(path:'js/jquery-2.1.4.min.js')}" type="text/javascript"></script>
   <script src="{f:uri.resource(path:'js/bootstrap.js')}" type="text/javascript"></script>
    <script src="{f:uri.resource(path:'js/jquery.tablesorter.min.js')}" type="text/javascript"></script>
    <!-- Chart JS -->
    <script src="{f:uri.resource(path:'js/Chart.min.js')}" type="text/javascript"></script>
    <link href="{f:uri.resource(path:'css/resultrepository.css')}" rel="stylesheet" type="text/css"/>
    <!-- Bootstrap -->
    <link href="{f:uri.resource(path:'css/bootstrap.min.css')}" rel="stylesheet">

    <!-- Globales JavaScript für das Result Repository Modul -->
    <script src="{f:uri.resource(path:'js/rereGlobal.js')}" type="text/javascript"></script>

    <!-- JS for Noteverwaltung.html -->
    <script src="{f:uri.resource(path:'js/noteverwaltung.js')}" type="text/javascript"></script>

    <!-- FontAwesome -->
    <link href="{f:uri.resource(path:'css/font-awesome.min.css')}" rel="stylesheet">

In this case what could be the problem? Former when I used it in typo3 6.2.9 it worked fine with the code above. Just in 7.6.9 only jquery or bootstrap.js is working.

Google Maps api - label for markers

I want to include a cusom Map on my site, for the main part everything works, except for one thing.

The red marker needs a label, though I could add a icon and use that as marker, but I'd like to add the label without an extra image.

Also I don't want to use extra plugins.

If this doesn't work: Is it possible to add the mapoptions to the standard embed map? The only downside there is that it zooms upon scrolling.


Look of the current map:

Custom Map


Label the Marker should have:

Google Map

Brandenburger Gate - Google Maps


HTML:

<div id="googleMap"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Javascript (jQuery):

$(function() {

    function showMap() {

        var mapZoom = 14;
        var LatLng = new google.maps.LatLng(52.516275, 13.377704);

        var mapOptions = {
            zoom: mapZoom,
            center: LatLng,
            streetViewControl: false,
            scrollwheel: false,
            navigationControl: false,
            mapTypeControl: false,
            scaleControl: false,
            keyboardShortcuts: false

        };

        var map = new google.maps.Map(document.getElementById('googleMap'),mapOptions);

        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            draggable: false
        });
    }
    google.maps.event.addDomListener(window, 'load', showMap);

});

FormData in asp .net mvc with file upload and other data than files

I am trying to upload an image in asp .net mvc using FormData for a specific item in my database. For that I need to send along with the image the id of the item in the database to link the image to.

I need to use FormData because I need the page not to be refreshed. So I am using jquery for ajax with the image.

I added the id of the image using formdata.append but I get an error in the server which tells me that the id parameter of the method that is called when doing ajax request, is not nullable and so it can't be mapped. It should be mapped to the id of the item in the database I mentioned earlier.

But I added in the form data the id of the item.

This is my javascript code:

var formData = new FormData();
var totalFiles = document.getElementById("inputImage").files.length;
formData.append("categoryId", response.data.toString());
for (var i = 0; i < totalFiles; i++) {
    var file = document.getElementById("inputImage").files[i];
    formData.append("categoryImage", file);
}
$.ajax("@Url.Action("SaveCategoryImage", "Categories")",
{
    type: "POST",
    dataType: "JSON",
    data: formData,
    contentType: false,
    processData: false,
    headers: { __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val() }
});

And this is the method in the controller that should get called:

public async Task<ActionResult> SaveCategoryImage(long cateogoryId, HttpPostedFileBase image)
{
    return new JsonNetResult(new BasicActionResultViewModel {IsSuccessful = true});
}

So why doesn't asp .net mvc map the id I send in the form data to the id in the method of the controller?

How to correctly use kivy graphics context instruction

Hi I recently tried my hands on kivy graphics, context instructions(rotate, ranslate etc). So i tried to implement an animated spinning wheel(used for example to show loading screen). I used garden.iconfonts package for this purpose following closely the example implemented in the package. Heres my code

.kv

<Convert>:
   pos_hint: {'center_x':.5, 'center_y':.5}
   size_hint: .8,.4
   auto_dismiss: False
   on_open:
      self.load()
   loading:loading
   BoxLayout:
      pos: root.pos
      canvas.before:
         Color:
            rgba: 1,1,1,1
         Rectangle:
            pos: self.pos
            size: self.size
            source: 'icons/olivine.png'
      orientation: 'vertical'
      Label:            #STATUS 20 PERCENT
         text: 'Converting file...'
         id: status
         size_hint: 1,.2
         markup: True
      RelativeLayout:    #picture or rolling 60 %
         size_hint: 1,.6
         Label:      #SPINNER
            text: '{}'.format(icon('icon-spin6', 32))
            size_hint: 1,1
            markup: True
            p: 0
            id: loading
            canvas:
               PushMatrix
               Rotate:
                  angle: -self.p
                  origin: self.center
                  axis: 0,0,1
               PopMatrix

.py

from kivy.uix.modalview import ModalView
from kivy.properties import ObjectProperty
from kivy.animation import Animation


class Convert(ModalView):
   loading= ObjectProperty()
   def load(self):
      anim = Animation(p = 360, duration= 1) + Animation(p=0 , duration=0)
      anim.repeat = True
      anim.start(self.loading)

From my code Convert is a popup that shows up when a button is clicked, then as it opens, shows the spinning wheel. But when i run the code it just shows the wheel(i.e the iconfont), but does not spin. The code only works when i change the canvas class under the Label, to canvas.before. I assume that my understanding of how to use these tools is still poor. So im hoping someone can help clearify what im doing wrong, and how to make this work using canvas

How to plot multiple bars in the same graph

I want to plot 6 different bars (AWA, Rem, S1, S2, SWS, stades) for each group. There are 4 groups.

I know the problem is in the: fig, ax=plt.subplots() How can I fix this?

    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline

    N = 4 # groups: EEG_EMG_EOG_twins(28), EEG_EMG_EOG(26), EEG_twins(22), EEG(20)

    AWA = (99, 98, 98, 95)  #EEG_EMG_EOG_twins(28), EEG_EMG_EOG(26), EEG_twins(22), EEG(20)

    ind = np.arange(N)  # the x locations for the groups
    width = 0.35       # the width of the bars

    fig, ax = plt.subplots()
    rects1 = ax.bar(ind, AWA, width, color='r')

    Rem = (100, 99, 97, 94)  #EEG_EMG_EOG_twins(28), EEG_EMG_EOG(26), EEG_twins(22), EEG(20)
    rects2 = ax.bar(ind + width, Rem, width, color='y')

    S1 = (98, 97, 95, 93)  #EEG_EMG_EOG_twins(28), EEG_EMG_EOG(26), EEG_twins(22), EEG(20)
    rects3 = ax.bar(ind + width, S1, width, color='b')

    S2 = (99, 99, 95, 92)  #EEG+EMG+EOG+twins(28), EEG+EMG+EOG(26), EEG+twins(22), EEG(20)
    rects4 = ax.bar(ind + width, S2, width, color='g')

    SWS = (99, 100, 95, 94)  #EEG+EMG+EOG+twins(28), EEG+EMG+EOG(26), EEG+twins(22), EEG(20)
    rects5 = ax.bar(ind + width, SWS, width, color='y')

    stades = (99, 98, 92, 86)  #EEG+EMG+EOG+twins(28), EEG+EMG+EOG(26), EEG+twins(22), EEG(20)
    rects6 = ax.bar(ind + width, stades, width, color='b')

    # add some text for labels, title and axes ticks
    ax.set_ylabel('Accuracy')
    ax.set_title('Accuracy by group - RF')
    ax.set_xticks(ind + width)
    ax.set_xticklabels(('G1', 'G2', 'G3', 'G4'))

    ax.legend((rects1[0], rects2[0], rects3[0], rects4[0], rects5[0], rects6[0]), ('AWA', 'Rem', 'S1', 'S2', 'SWS', 'stades'))

    plt.show()

enter image description here

Why is my Logstash handler throwing a TypeError?

I'm creating a custom logger with the following code:

import logging
import logstash

from socket import gethostname

class CustomLogger(logging.Logger):
    def _log(self, level, msg, args, exc_info=None, extra=None):
        if extra is None:
            extra = { 'hostname' : gethostname() }
        super(CustomLogger, self)._log(level, msg, args, exc_info, extra)

def setup_custom_logger(host, port):
    # add hostname to the formatter.
    logging.setLoggerClass(CustomLogger)

    formatter = logging.Formatter(fmt='%(hostname)s - %(asctime)s - %(levelname)s - %(module)s - %(message)s')

    logstash_handler = logstash.LogstashHandler(host, port, version=2)
    logstash_handler.setLevel(logging.DEBUG)
    logstash_handler.setFormatter(formatter)

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logstash_handler)

    return logger

but when I use the logger returned from setup_custom_logger, I always get a TypeError.

I tried calling it with logger.info('hello') and with logger.info(b'hello'), but in both instances got:

--- Logging error ---
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/handlers.py", line 620, in emit
    self.send(s)
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/handlers.py", line 678, in send
    self.sock.sendto(s, self.address)
TypeError: a bytes-like object is required, not 'str'

It makes some sense that logging 'hello' would not work because 'hello' is, indeed, a str type.

However, b'hello' is a bytes-like object:

>>> type(b'hello')
<class 'bytes'>

Why am I receiving this error? I'm using python-logstash 0.4.6 and Python 3.5.1.

Why select() in a parent process makes accept() unusable in a child process?

I have a parent process which creates 2 server sockets and calls select() on them to wait for new connection. When the connection arrives, a message is sent to a child process (created with fork(), after servers sockets creation, so they are shared).

In this child, calling accept() on the server socket doesn't work. I got a EAGAIN error (non-blocking socket). Whereas calling accept() in the main process works perfectly.

Of course, I don't call accept() in the main process at all, I just tested to check if it worked, and it does.

Why can't I call accept() in a child process after a select() in the parent?

EDIT: The goal here is to create a fixed number of workers (let's say 8) to handle clients connections, as in the prefork model. These connections will be long-connections, not like HTTP. The goal is to load-balance connections between workers.

To do this, I use a shared memory variable which contains for a worker the number of currently connected clients. I want to "ask" the worker with the lowest number of clients to handle a new connection.

That's why I do the select() in the parent, and then send a message to a child process, because I want to "choose" which process will handle the new connection.

The server listen on more than one sockets (one for ssl, one without), that's why I use select() and not directly accept() in children processes, because I can't accept() on multiple sockets in my children workers.

mardi 28 juin 2016

Typeahead only making one request

With the code below, an ajax request to the server will only be made once after the first letter of the first query after a page load.

So if i type product name into the input, the request will be /default.aspx?q=p&serveas=ajax and then no more requests will fire until I reload the page, no matter what I type into the input.

If I copy-paste a word that I know hits I will get a response, but again, only one and only once.

If I console.log on the onResult() callback I can see it is registering the query in the input correctly, it's just not making a request for a result.

I have to parse the Ajax result from HTML to an object because my host can't return JSON search results.

The debug output says everything is normal.

var parseResult = function (data) {

  var arr = [];

  $(data).find('.products').find('.item').each(function(i) {
    var item = $(this);
    arr.push({
      sku: item.prop('id').replace('catalogue-',''),
      name: item.find('.item_name').text(),
      image: item.find('.listing_thumb').find('img').prop('src'),
      url: item.find('a').eq(0).prop('href')
    });
  });

  return arr;

};

searchField.typeahead({

  delay: 300,
  display: ['sku','name'],
  order: "asc",
  minLength: 3,
  maxItem: 15,
  highlight: true,
  filter: false,

  template: "<a href='{{url}}'><img style='max-width:60px;' src='{{image}}'> {{name}} <small style='color:#999;'>{{sku}}</small></a>",
  emptyTemplate: 'No result for "{{query}}"',
  source: {
    items: {
      ajax: {
        type: 'GET',
        url: '/default.aspx',
        data: {
          q: '{{query}}',
          serveas: 'ajax'
        },
        dataType: 'text',

        callback: {
          done: parseResult
        }
      }
    }
  },

  debug: true
});

mod_wsgi: Reload Code via Inotify - not every N seconds

Up to now I followed this advice to reload the code:

https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki

This has the drawback, that the code changes get detected only every N second. I could use N=0.1, but this results in useless disk IO.

AFAIK the inotify callback of the linux kernel is available via python.

Is there a faster way to detect code changes and restart the wsgi handler?

We use daemon mode on linux.

Why code reload for mod_wsgi at all

There is interest in why I want this at all. Here is my setup:

Most people use "manage.py runserver" for development and some other wsgi deployment for for production.

In my context we have automated the creation of new systems and prod and development systems are mostly identical.

One operating system (linux) can host N systems (virtual environments).

Developers can use runserver or mod_wsgi. Using runserver has the benefit that it's easy for debugging, mod_wsgi has the benefit that you don't need to start the server first.

mod_wsgi has the benefit, that you know the URL: https://dev-server/system-name/myurl/

With runserver you don't know the port. Use case: You want to link from an internal wiki to a dev-system ....

A dirty hack to get code reload for mod_wsgi, which we used in the past: maximum-requests=1 but this is slow.

Loading HTML from localStorage breaks function of a button

I save a part of my HTML (div class="savage") in localStorage and retrieve it when the page is refreshed. The HTML in question is a text-box for input with and "add new item" button and an unordered list of items with "delete" buttons and checkboxes. After I add a few items to my list and refresh the page, the list gets loaded correctly but I can't use the add button anymore. I can click on it but nothing happens and it won't append new items to the list. If anyone can tell me what I did wrong or point me in the right direction it would be greatly appreciated.

HTML

<div class="savage">
   <h1>List of exercises to do today </h1>
   <h2> My workout <span id="counter"></span></h2>
       <form><input type="text" id="new-text"/></form><button id="add">Add</button>
           <ul id="mylist">
              <li> <input type="checkbox" class="done"/>figs<button    class="delete">delete</button></li>
              <li><input type="checkbox" class="done"/>pine nuts<button  class="delete">delete</button></li>
           </ul>
</div>

And JQUERY

window.onload = function() {
    if(localStorage.getItem('peterslist')) {
    $('.savage').html(localStorage.getItem('peterslist'));
}
};

function updateStorage() {
    var peterslist = $('.savage').html();
    localStorage.setItem('peterslist', peterslist);
}

BUTTON EVENT HANDLER

$(function(){

  $("#add").on('click', addListItem);
  $(document).on('click', '.delete', deleteitem);
  $(document).on('click', '.done', finishItem);

});

Saving Django formset with Many to Many Field

I'm building a little app with a formset that lets me enter a number of game scores each linking to a player via a many to many field. I'm having problems getting this to save properly with various errors. Basic code.

Model.py

class Player(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
            return self.name

class Score(models.Model):
    score = models.DecimalField(max_digits=4, decimal_places=0)
    turn = models.ForeignKey(Turn)
    players = models.ManyToManyField(Player)  

    def __unicode__(self):
            return self.score

Each score is then joined to a turn but I haven't shown that bit.

Form.py

class NewScore(ModelForm):

    class Meta:
        model = Score
        fields = ('score', 'players',)

View.py

def newscore(request):

NewScoreFormSet = formset_factory(NewScore, extra=2)  

if request.method == 'POST':

    formset = NewScoreFormSet(request.POST)

    if formset.is_valid():

        t = Turn.objects.latest('id')

        for form in formset:

            p = form.cleaned_data.get('players')

            scoreSave = form.save(commit=False)
            scoreSave.turn = t
            scoreSave.save()
            scoreSave.players.add(p)


    else:
        print 'Formset not OK'

    return render(request, 'scorer/game.html',
                {})

else:

    formset = NewScoreFormSet()

    return render(request, 'scorer/game.html',
                {'formset': formset,})

The issue seems to be around getting the player saved through the many to many field and in this current setup I get the error message

TypeError: int() argument must be a string or a number, not 'QuerySet'

I have also tried removing the line

scoreSave.players.add(p)

but that just doesn't save the player at all. Just the score and turn.

Any help in why this won't save would be very helpful.

Many thanks

T

python: DOMTree.writexml fails for non truncated mode?

I am trying to modify some eclipse ".project" files to be able to rename those projects. However several strange Erros occured to me. I recevied a project file, which was hidden, so that I would get the Errno 13 for the open mode 'w' (see IOError: [Errno 13] Permission denied when trying to open hidden file in “w” mode). So I changed the mode to "r+", where the difference is just the missing truncation in the beginning and an additional read-possiblity which I don't use. But then the call DOMTree.writexml(f) only works for the first iteration. If I try to modify the files again, I get an error: "xml.parsers.expat.ExpatError: junk after document element: line 16, column 21". I checked the files and line 16 is just the end of the file and I can't see any difference between the two modes "r+" and "w". So why is there an xml parser error when using the mode "r+" and how is truncating before writing important, if I can't see any difference (even in a HEX-Editor)?

The algorithm looks as follows, where PFile is some path to the project file, ProjDir is the path to some directory which contains the project file.

def modify(PFile, ProjDir, path):
    DOMTree = DOM.parse(PFile)
    ProjDescription= DOMTree.documentElement        
    name = ProjDescription.getElementsByTagName('name')[0]
    # rename Project
    temp1 = ProjDir.split("--")
    if len(temp1) >1:
        temp2 ="--".join(temp1[-2:])
        temp2 = temp1[1][:-10]+"--"+temp2
        name.childNodes[0].data = temp2
        print("Project name: %s"% name.childNodes[0].data)
    else:
        print(ProjDir+" not modified")
        return 0

f = open(PFile,'r+') #errno13 in mode w if file is hidden, in mode r+ truncate is missing?!
#f.truncate();
DOMTree.writexml(f)
f.close()
return 0```

woocommerce variable product swatches - images are disabled/grayed out

I made this awesome image zoom feature in Woocommerce variation page. Here is the link - LINK

But in the webpage the color picker images are grayed out, and if you inspect the element it is appearing as "disabled".

Do you have any idea how to remove "disabled" from the color picker images?

I am stuck.

Changes that I made as yet - 1) I used some jquery in the head section of the HTML. Here is the code.

<script type="text/javascript">
var imgPlainArray = [
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/black-3.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/white-1.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/pink-1.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/red-1.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/black-current-2.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/frosty-white.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/parrot-green.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/royal-blue.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/silver.jpg',
    'http://icestartup.com/testsites/ujsnkfvs22/wordpress/wp-content/uploads/2016/06/yellow.jpg'
];
$(document).ready(function(){
    setTimeout(function(){
        $("#pick-your-laminate").on('change', function(){
            if ( this.value == "Plain Laminate" ) {
                $(".box").not(".plain").hide();
                $(".plain").show();
            } else if ( this.value == "Digital Laminate" ) {
                $(".box").not(".digital").hide();
                $(".digital").show();
            }
        });
    }, 1000);

    $("<img>").attr("src", imgPlainArray[0]).appendTo("#xxx");

    $(".swatch-control > div").click(function(){
        var laminateIndex = $(this).index() - 2;
        $( "#xxx img" ).replaceWith( 
            $("<img>").attr("src", imgPlainArray[laminateIndex])
        );      
    });     
});
</script>

2) I made some changes in the variable.php template of Woocommerce. Just simple stuff though, adds some rows to the table. That cannot make any conflict, i guess.

Scraping Instagram followers page using selenium and python

I have a question related to scraping the instagram followers page. I have a code but it displays only 9 followers. Kindly help me.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def login(driver):
    username = "qureshi11690@yahoo.com"  # <username here>
    password = "qureshi1"  # <password here>

    # Load page
    driver.get("https://www.instagram.com/accounts/login/")

    # Login
    driver.find_element_by_xpath("//div/input[@name='username']").send_keys(username)
    driver.find_element_by_xpath("//div/input[@name='password']").send_keys(password)
    driver.find_element_by_xpath("//span/button").click()

    # Wait for the login page to load
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.LINK_TEXT, "See All")))


def scrape_followers(driver, account):
    # Load account page
    driver.get("https://www.instagram.com/{0}/".format(account))

    # Click the 'Follower(s)' link
    driver.find_element_by_partial_link_text("follower").click()

    # Wait for the followers modal to load
    xpath = "//div[@style='position: relative; z-index: 1;']/div/div[2]/div/div[1]"
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, xpath)))

    # You'll need to figure out some scrolling magic here. Something that can
    # scroll to the bottom of the followers modal, and know when its reached
    # the bottom. This is pretty impractical for people with a lot of followers

    # Finally, scrape the followers
    xpath = "//div[@style='position: relative; z-index: 1;']//ul/li/div/div/div/div/a"
    followers_elems = driver.find_elements_by_xpath(xpath)

    return [e.text for e in followers_elems]


if __name__ == "__main__":
    driver = webdriver.Firefox()
    try:
        login(driver)
        followers = scrape_followers(driver, "instagram")
        print(followers)
    finally:
        driver.quit()

This code was taken from another page. I dont understand how to scroll down the followers page.