jeudi 30 juin 2016

Is there a faster way to find matching features in two arrays (Python)?


I'm trying to go through each feature in one file (1 per line) and find all matching features based on one column of that line in a second file. I have this solution, which does what I want on small files, but it's very slow on big files (my files have >20,000,000 lines). Here's a sample of the two input files.

My (slow) code:

FEATUREFILE = 'S2_STARRseq_rep1_vsControl_peaks.bed'
CONSERVATIONFILEDIR = './conservation/'
with open(str(FEATUREFILE),'r') as peakFile, open('featureConservation.td',"w+") as outfile:
for line in peakFile.readlines():
    chrom = line.split('t')[0]
    startPos = int(line.split('t')[1])
    endPos = int(line.split('t')[2])
    peakName = line.split('t')[3]
    enrichVal = float(line.split('t')[4])

    #Reject negative peak starts, if they exist (sometimes this can happen w/ MACS)
    if startPos > 0:
        with open(str(CONSERVATIONFILEDIR) + str(chrom)+'.bed','r') as conservationFile:
            cumulConserv = 0.
            n = 0
            for conservLine in conservationFile.readlines():
                position = int(conservLine.split('t')[1])
                conservScore = float(conservLine.split('t')[3])
                if position >= startPos and position <= endPos:
                    cumulConserv += conservScore
                    n+=1
        featureConservation = cumulConserv/(n)
        outfile.write(str(chrom) + 't' + str(startPos) + 't' + str(endPos) + 't' + str(peakName) + 't' + str(enrichVal) + 't' + str(featureConservation) + 'n')

Select multiple html elements by clicking on one element in Jquery


I have two images on my html page and I have one button named MOVE to move them left separately. To move them I have a Jquery function with selected class. I have two input fields each of them belongs to the particular image. My button has a click counter function so I need to get a count by clicking on the same button to both images separately into those two input fields.

I think when I select image 1, It's also should be selected input 1, and then the counter will count image 1's counts of moves and when I select image 2, It's also should be selected input 2, and then the counter will count image 2's counts of moves.

I don't know how to select multiple elements by clicking on one element. please help

My Jquery function

$(document).ready(function() {

$(".plan1").click(function() {                              //medium move
    // unselect others
    $(".plan1").removeClass("selected");
    // reselect this one
    $(this).addClass("selected");
});

$("#b1").click(function() {
    // animate selected
    $(".plan1.selected").animate({left:'+=20px'});
    $('#f1.selected').val(function(i, val) { return +val+1 });
});
});

HTML

<img src="imagesource" class="plan1" />
<img src="imagesource" class="plan1" />

<input type="text" id="f1" />
<input type="text" id="f2" />

<button id="b1">MOVE</button>

Rails: How to insert and display new data only when click link without form


Is it possible to insert new row and display it when just click link without inputting form? I'd like to insert and display new data in the following table when click the link. I'm not care whether reload the page or not. schema create_table "rooms", force: :cascade do |t| t.integer "schedule_id" t.integer "day", default: 1 ... For example, the following data exists in the rooms table. id | schedule_id | day | 12 | 34 | 1 | insert the data after clicking link (same schedule_id, but increment day) id | schedule_id | day | 12 | 34 | 1 | 13 | 34 | 2 | model schedule.rb class Schedule < ActiveRecord::Base belongs_to :user has_many :rooms, inverse_of: :schedule, dependent: :destroy has_many :amounts, inverse_of: :schedule, dependent: :destroy accepts_nested_attributes_for :rooms, allow_destroy: true ... room.rb class Room < ActiveRecord::Base belongs_to :schedule, inverse_of: :rooms has_many :events, inverse_of: :room, dependent: :destroy has_many :amounts, inverse_of: :room, dependent: :destroy accepts_nested_attributes_for :events, allow_destroy: true default_scope -> { order(day: :asc) } ... view I'd like to add the link in schedules/_schedule.html.erb It has the followings; ... <% schedule.rooms.each do |r| %> <div class="day">Day <%= r.day %></div> ... Is it possible to insert and display new data when only click the link without inputting form? It would be appreciated if you could give me any suggestion.

Raw Custom Logs in Google App Engine Flexible Environment


I've used the following code in a Flexible (VM) Environment on Google App Engine to separate custom logs with a specific formatting requirement from other application logs: import logging as std_logging std_logging.basicConfig() custom_formatter = std_logging.Formatter('%(created)ft%(message)s') custom_handler = std_logging.FileHandler('/var/log/app_engine/custom_logs/custom.log') custom_handler.setFormatter(custom_formatter) custom_logging = std_logging.getLogger('custom') custom_logging.addHandler(custom_handler) In a normal Python environment, these would write to the log file as plain-text lines in the format specified. However, after dumping the logs produced from App Engine to Cloud Storage, I noticed that App Engine has wrapped each log with other information. E.g. (formatted for clarity) { "insertId":"vsdacv1235jj1", "log":"appengine.googleapis.com/custom.var.log.app_engine.app.custom_logs.custom.log", "metadata":{ "labels":{ "appengine.googleapis.com/module_id":"default", "appengine.googleapis.com/version_id":"1", "compute.googleapis.com/resource_id":"1234256789901203", "compute.googleapis.com/resource_name":"bbq23asd123", "compute.googleapis.com/resource_type":"instance" }, "projectId":"my-project", "serviceName":"appengine.googleapis.com", "timestamp":"2016-06-24T20:16:15Z", "zone":"us-central1-f" }, "textPayload":"1466799374933tthis is my custom message" } The value of the textPayload field is the actual log I produced, but is wrapped by App Engine. Is there a way to prevent this behaviour? It is undesirable to re-process these logs in order to format them correctly.

Python: how to delete object from class?


I'm new to python and having a little trouble with object classes. I have created code were ball objects bounce off the side of the wall. I would like to delete a ball after it has been clicked on. I have tried several different methods of doing this but they have all resulted in errors. Below is my code for the balls bouncing off the walls. How can I edit this code to have the balls deleted once they are clicked? Thanks!

from Tkinter import *
import random
import time

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)
            self.xspeed = random.randrange(-3,3)
            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


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

while True:
    for ball in balls:
        ball.move()

    root.update()
    time.sleep(0.01)

root.mainloop()

Look up value from column in table and interpolate in rows (python pandas scipy)


I am having trouble with a program that will first look up a date in another data frame, and then interpolate a certain value along the rows. Problem: Let the original data frames look like this: A = pd.DataFrame({"date":["06/24/2014","06/25/2014","06/26/2014"], "value":[2, 4, 6]}) B = pd.DataFrame({"date":["06/25/2014","06/26/2014","06/24/2014"], "1":[0.1, 0.5, 0.9],"3":[0.2, 0.6, 1.0],"5":[0.3, 0.7, 1.1],"7":[0.4, 0.8, 1.2]}) The idea is that the program should first find the row in B that matches with A by "date" and them interpolate using the names of the columns as the x_value and the values in the row as y_value. The output should look like this: A = pd.DataFrame({"date":["06/24/2014","06/25/2014","06/26/2014"], "value":[2, 4, 6], "interp":[0.95,0.25, 0.75]}) My approach so far: import pandas as pd from scipy.interpolate import interp1d A = pd.DataFrame({"date":["06/24/2014","06/25/2014","06/26/2014"], "value":[2, 4, 6]}) B = pd.DataFrame({"date":["06/25/2014","06/26/2014","06/24/2014"], "1":[0.1, 0.5, 0.9],"3":[0.2, 0.6, 1.0],"5":[0.3, 0.7, 1.1],"7":[0.4, 0.8, 1.2]}) # Define x as the names of the columns x_value = (1,3,5,7) #Define the interpolation function as follows def interp(row): idx = B[B['date'] == row['date']].index.tolist()[0] #get indx from B z_value = [] #get values from row in B for i in range(1,5): z_value.append(float(B.iloc[idx][i])) tuple(z_value) f_linear = interp1d(x_value,z_value) #define interpolation function y_il = f_linear(row['value']) return y_il Finally, I would apply the function to each row this way: A['interp']=A.apply(interp, axis=1) I get the following output. Is there a better way to do this?? >>> A date interp value 0 06/24/2014 0.95 2 1 06/25/2014 0.25 4 2 06/26/2014 0.75 6

how to remove the delay in obtaining data from the Arduino via COM?


I have an Arduino connected to the joystick. Arduino sends the data via COM port to my PC. On PC, the data processed by the program in Python, in which the circle moving with joystick. The fact is that after a few minutes there is a delay between the joystick and circle. Code for Arduino #define axis_X 0 #define axis_Y 1 int value_X, value_Y = 0; void setup() { Serial.begin(9600); } void loop() { value_X = analogRead(axis_X); Serial.print(value_X, DEC); Serial.print("|"); value_Y = analogRead(axis_Y); Serial.print(value_Y, DEC); Serial.print("n"); delay(20); } Code for PC import Tkinter as tk import serial import os import sys import time #connect to COM ser = serial.Serial('COM11', 9600, dsrdtr = 1,timeout = 0) def data(): time.sleep(0.02) serialline = ser.readline().split("n") coord = [] if serialline[0]: string = serialline[0] coord = string.split("|") return coord #create window root = tk.Tk() canvas = tk.Canvas(root, width=1000, height=700, borderwidth=0, highlightthickness=0, bg="black") canvas.grid() def _create_circle(self, x, y, r, **kwargs): return self.create_oval(x-r, y-r, x+r, y+r, **kwargs) tk.Canvas.create_circle = _create_circle r = 50 x = 100 y = 100 sm = 200 cir = canvas.create_circle(x, y, r, fill="blue", outline="#DDD", width=1) root.wm_title("Circles and Arcs") while 1: coord = data() x = int(coord[0])/5 y = int(coord[1])/5 canvas.coords(cir,x+ sm,y+sm,x+sm + 2*r,y+sm + 2*r) root.update() How to solve this problem?

Changing images using delays


I’m trying to figure out how to make an animation using the order of three images.

The default image is “image1.png” that always shows when the page loads.

  1. After every 5 seconds, the variable “back.src” must abruptly change to image2.png, so without fading. The default is image1.png

  2. And then after 0.5 seconds, the variable again changes but then to image3.png.

  3. 0.5 seconds later it changes back to image2.png

  4. and 0.5 later again back to image1.png.

This is to be repeated in a loop because I want to repeat the process again after 5 seconds.

My problem is, I don't know if structuring this code is the best way to go about it. How would my code need to look based on the requirement explained above?

Here's my code of what I've got so far:

var back = new Image();
back.src = "image1.png";
        function wait(miliseconds) {
            var currentTime = new Date().getTime();
            while (currentTime + miliseconds >= new Date().getTime()) {
            }
        }

        function image1() {
            wait(5000);
            back.src = "image2.png";
        }

        function image2() {
            wait(500);
            back.src = "image3.png";
        }

        function image3() {
            wait(500);
            back.src = "image2.png";
        }


function animate(){
    ctx.save();
    ctx.clearRect(0, 0, cW, cH);
    ctx.drawImage(back,0,0);        
    ctx.restore();
}
var animateInterval = setInterval(animate, 30);

how to get value from selected radio button


sir, i have a form input like input text and radio button. how to get the value of selected radio button, and put that value to the input type text.

heres jsfiddle, https://jsfiddle.net/czw71dfk/2/

    <div id="gender" class="form-inline">
  <div class="form-group">
    <label for="">I Sign up as</label>
    <input #id="place" type="text" class="form-control" readonly/>
    <div class="radio-inline">
      <label class="label_item" for="radioMale">
        <input type="radio" class="radio_item" value="male"  name="gender" id="radioMale">
      </label>
      <p class="text-center colorGrey">Male</p>
     </div>
    <div class="radio-inline">
      <label class="label_item" for="radioFemale">
        <input type="radio" class="radio_item" value="female"  name="gender" id="radioFemale">
      </label>
      <p class="text-center colorGrey">Female</p>
    </div>
    <div class="radio-inline">
      <label class="label_item" for="radioKids">
        <input type="radio" class="radio_item" value="Kids" name="gender" id="radioKids">
      </label>
      <p class="text-center colorGrey">Kids</p>
    </div>
  </div>
</div>

$('#gender input').on('change', function() {
    var gender = $( this ).val();
   $("#place").val( gender );
});

Google Maps JavaScript API does not display


I need help to display Google Maps Javascript API.
When I try it, I have this message :
"Oops ... an error occurred. Google Maps does not load correctly on this page. For more technical information about this error, see the JavaScript console."

And when I look on Javascript console, I see :
"Fullscreen API prefix is obsolete. Please use the non-prefixed version of the API for full screen. For more information, see https://developer.mozilla.org/docs/Web/API/Fullscreen_API".

You can test this :

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 100%;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB9gHvomtav2onQxJeyfZkMNiUUTUPWud4&callback=initMap"
        async defer></script>
  </body>
</html>

Thanks a lot ! :)


Running Cassandra unit tests in parallel using nose, ccm, python


I've recently started using Cassandra as a primary data store, and am trying to write unit tests for this using CCM

I'm able to spin up a Cassandra Cluster instance and test one test class. I want to be able to test another test class in parallel with this, as serial unit testing can take really long, with more test cases added. My test code looks something like -

class BaseTestCase(TestCase):
  def setUp(self):
    super(BaseTestCase, self).setUp()

    # Create and start a CCM (Cassandra Cluster Management) cluster
    self.cluster = ccmlib.cluster.Cluster() # with reqd params
    self.cluster.populate(1).start()  # Start cluster with 1 node

Now when I have more than 1 test class inheriting from this Base class, and I run the tests serially, it works fine. But when I run nosetests in parallel, I get errors along the lines of "A Cassandra instance may already be running". I've tried looking into Dtests but this doesn't seem to solve my problem. It seems that it can run tests across clusters, but not in parallel.

I was wondering if there is anything that someone can point me to, for this purpose, or if anyone thinks I'm doing something incorrect with the usage of CCM or Dtests. Thanks!


radio input with external button


Hello I am making a slideshow out of a radio input and have designed "prev" and "next" buttons to move the slide along. However, I would also like the buttons to also check the next input. Currently the slide moves, but the next input isn't checked. I have looked at this solution here: Select next/prev radio button with external button and tried to implement it but I cannot get it to work. Here is my code: <form action="" method="post"> <ul class="form-ul" style="position: relative; width: 176px; height: 107px;"> <li style="position: absolute; top: 0px; left: 0px; display: block; z-index: 5; opacity: 1; width: 82px; height: 43px;"> <label> <input type="radio" name="term_id" value="59" checked="checked"> </label> </li> <li style="position: absolute; top: 0px; left: 0px; display: none; z-index: 4; opacity: 0; width: 82px; height: 62px;"> <label> <input type="radio" name="term_id" value="61"> </label> </li> </ul> <div id="prev" style="float:left;">PREV</div> <div id="next" style="float:right;">NEXT</div> </form> $(document).ready(function(){ $('#prev').click(function(){ $('.form-ul').find('li:has(input:checked)').prev().children('input').prop("checked", true); }); $('#next').click(function(){ $('.form-ul').find('li:has(input:checked)').next().children('input').prop("checked", true); }); });

Delegate JQuery Popover Trigger Event (Loading Dynamic Divs in Rails)


I am using this rails popover gem and dynamically loading $(".trigger") divs as the user scrolls down. The trigger divs need to show a popover when clicked.

I have an onLoadFunction:

function OnloadFunction (){
   # stuff can get called here
}

and my DOM Ready function:

$(function(){    
    OnloadFunction();
    # Other stuff called here
});

Here's the popover code:

      $('.trigger').popover({
          my: 'center top', // of popover
          at: 'center top', // of trigger
        }).on('click', function() {
            console.log('World!');
        });

The DOM ready function only gets called once. But the OnLoadFunction gets called any time new objects are loaded. So if I add the popover code to the OnLoadFunction, it gets called multiple times and leads to unexpected behavior (popup shows, and then hides since it's being called twice).

If I add the popover code to the OnReady function, then my freshly rendered .trigger divs don't show the popover.

Ideally I would like to bind the popover event to the .body within my DOM ready function, but I'm not sure how to write that.. Any ideas? Something like:

$('body').on("click", ".trigger", function(){
          popover({
            my: 'center top', // of popover
            at: 'center top', // of trigger
          })
        });

But I just get "popover is not a function".


Replacing space with hyphen, using jQuery?


I'm trying to get a filtering system working but I need the title of the filter to be .test-filter rather than .testfilter

html:

<div id="filters" class="button-group supplier-search">
  <div class="button" data-filter="*">Show All</div>
    <ul>
       <li><a href="#" class="sport">Sport</a></li>
       <li><a href="#" class="music">Music</a></li>
       <li><a href="#" class="testfilter">Test Filter</a></li>
    </ul>
    <select id="filter-select">
       <option selected="selected" value="*">-- Show All --</option
       <option value=".sport">Sport</option>
       <option value=".music">Music</option>
       <option value=".testfilter">Test Filter</option>
    </select>
</div>

the javascript i have for creating the class attr is:

$(".supplier-search a").each(function() {
    var el = $(this);
     $("<option />", {
         "value"   :"."+el.attr("class"),
         "text"    : el.text()
     }).appendTo(".supplier-search select");
});

Is there a way I can do this? I've tried using suggested methods such as .split(' ').join('-') and .replace(/ /g,"-") but I'm getting an error:

Uncaught TypeError: $(...).replace is not a function

Owl Carousel 2: is there any way to display current item excerpt or item details?


My goal is to make a carousel with item title and description that looks like this

enter image description here

I want to display current item description under pagination. is it possible via Owl Carousel 2?

Here my code:

$(function(){
        var itemClass = $('#owl-item-carousel');
        itemClass.on('initialized.owl.carousel', function(e){
        var idx = e.item.index;
        $('.owl-item').removeClass('middle');
        $('.owl-item').removeClass('left');
        $('.owl-item').removeClass('right');
        $('.owl-item').removeClass('left-last');
        $('.owl-item').removeClass('right-last');
        $('.owl-item').eq(idx).addClass('middle');
        $('.owl-item').eq(idx-1).addClass('left');
        $('.owl-item').eq(idx+1).addClass('right');
        $('.owl-item').eq(idx-2).addClass('left-last');
        $('.owl-item').eq(idx+2).addClass('right-last');
    });
    $('#owl-item-carousel').owlCarousel({
        center: true,
        items:5,
        loop:true,
        // margin:10,
        pagination: true
    });

    itemClass.on('translate.owl.carousel', function(e){
        idx = e.item.index;
        $('.owl-item').removeClass('middle');
        $('.owl-item').removeClass('left');
        $('.owl-item').removeClass('right');
        $('.owl-item').removeClass('left-last');
        $('.owl-item').removeClass('right-last');
        $('.owl-item').eq(idx).addClass('middle');
        $('.owl-item').eq(idx-1).addClass('left');
        $('.owl-item').eq(idx+1).addClass('right');
        $('.owl-item').eq(idx-2).addClass('left-last');
        $('.owl-item').eq(idx+2).addClass('right-last');
    });
}); 

above code for only adding and remove class in item. But how can i display current item description under the pagination.


hiding browser navigation status bar for google chrome using javascript


I'm trying to to disable google chrome browser navigation status bar on the bottom left for a full screen web app that will be used on touch screen panel. I have a working code for jQuery but I can't use that since my code based on pure JavaScript. Only workaround find is to remove all href tags on mouse hover, keep the data temporarily on a data tag and once it's click navigate to link as how it is suppose to be using the data tag. here is how it looks like without disabling it once its hover. I was able to remove the href with JavaScript but couldn't add the links afterwards. var linksAhref = document.getElementsByTagName('a'); var linksData = document.getElementsByTagName('[href]'); var replaceFunc = function() { for (var i = 0; i < linksAhref.length; i++) { var href = linksAhref || linksData; // console.log(href); linksAhref[i].removeAttribute("href"); // window.location.href = href; } }; for (var i = 0; i < linksAhref.length; i++) { linksAhref[i].addEventListener('mouseover', replaceFunc); } <ul> <li><a href="link-1">Link 1</a></li> <li><a href="link-2">Link 3</a></li> <li><a href="link-3">Link 4</a></li> <li><a href="link-4">Link 5</a></li> </ul> Here is the code that works in jQuery: jsfiddle:

Left truncate using python 3 str.format?


Q: Is is possible to create a format string using Python 3's string formatting syntax to left truncate?

Basically what I want to do is take a git SHA:

"c1e33f6717b9d0125b53688d315aff9cf8dd9977"

And using only a format string, get the display only the right 8 chars:

"f8dd9977"

Things Ive tried:

Invalid Syntax

>>> "{foo[-8]}".format(foo="c1e33f6717b9d0125b53688d315aff9cf8dd9977")  
>>> "{:8.-8}".format("c1e33f6717b9d0125b53688d315aff9cf8dd9977")

Wrong Result

### Results in first 8 not last 8. 
>>> "{:8.8}".format("c1e33f6717b9d0125b53688d315aff9cf8dd9977")

Works but inflexible and cumbersome

### solution requires that bar is always length of 40.
>>> bar="c1e33f6717b9d0125b53688d315aff9cf8dd9977"
>>> "{foo[32]}{foo[33]}{foo[34]}{foo[35]}{foo[36]}{foo[37]}{foo[38]}{foo[39]}".format(foo=bar)

A similar question was asked, but never answered. However mine differs in that I am limited to using only format string, I don't have the ability to change the range of the input param.


ajax success not working in php jquery


I am stuck with strange issue in form submit in modal box. Here is the ajax code which i am using.

frontend.php

$("#submit").click(function(e){
                e.preventDefault;

                   $.ajax({
                    type: 'post',
                     url:$('form#modal').attr('action'),
                    cache: false,
                    dataType: 'json',
                     data:$('form#modal').serialize(),

                     success: function (data) {
                        if(data.success == false)
                            {
                                             alert('test');
                                var arr = data.errors;
                                $.each(arr, function(index, value)
                                {
                                    if (value.length != 0)
                                    {
                                                       alert('test20');

                                    }
                                });

                            } else {


                        alert('test1');
                    }},
                    error: function(err) {
                        console.log(err);
                    }

Here is the php code of file where data is post. backend.php

header( 'Content-Type: application/json' );
$res=array();
$res['errors']=array();


    if(isset($_POST['uid'])) {

        $uid = $_POST['uid'];       
        $messages = $_POST['comment'];
        $job_id = $_POST['id'];
        $profile_pic = $_POST['pic']; ;
        $emp_id = $_POST['emp_id'];
---Some Code for database query --
         $res['success'] = true;
        echo json_encode($res);
        exit;

}

When i submit form i check the firebug console and found data is getting post but response is showing in backend file (backend.php) like this.

{"errors":[],"success":true}

I am expecting the response on frontend.php as backend.php only process the data in backend. But for some reason i am getting output in backend.php in browser.

Edit: I found line 2 > eval jquery.min.js error in firebug.


urllib/beautifulsoup error in directory


obligatory warning that I am just learning python.

My question is why do I receive the error below after being prompted for a file name?[Errno 22] invalid mode ('r') or filename: 'text.txt'

My code: (it works but the html won't load)

import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')

html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

tags = soup('a')
for tag in tags:
     print tag.get('href', None)

IOError: [Errno 22] invalid mode ('r') or filename: ''

Thank you for your help,

Edit: Traceback

Traceback (most recent call last):
  File "C:UsersabrowDesktopPythonbrowser.py", line 6, in <module>
    html = urllib.urlopen(url).read()
  File "C:Python27liburllib.py", line 87, in urlopen
    return opener.open(url)
  File "C:Python27liburllib.py", line 208, in open
    return getattr(self, name)(url)
  File "C:Python27liburllib.py", line 292, in open_http
    import httplib
  File "C:Python27libhttplib.py", line 79, in <module>
    import mimetools
  File "C:Python27libmimetools.py", line 6, in <module>
    import tempfile
  File "C:Python27libtempfile.py", line 35, in <module>
    from random import Random as _Random
  File "C:UsersabrowDesktopPythonrandom.py", line 2, in <module>
    handle = open(name, 'r')
IOError: [Errno 2] No such file or directory: 'text.txt'

draw X charts given an array of X files + add graph title using elements in array + d3


this is my fiddle, which I am building on from this example.

And now I have this fiddle where it uses an array to draw 1 chart per each element in the array

arr = ["https://dl.dropboxusercontent.com/u/49714666/data.tsv", "https://dl.dropboxusercontent.com/u/49714666/data2.tsv"]

for (this_file in arr) {

  d3.tsv(arr[this_file], type, function(error, data) {
    if (error) throw error;

    //draw chart code 

    //add a graph title
    svg.append("text")
      .attr("x", (width / 2))
      .attr("y", 0 - (margin.top / 2))
      .attr("text-anchor", "middle")
      .style("font-size", "12px")
      //.style("text-decoration", "underline")  
      .text(arr[this_file] + " - 1");


  });

}

But the way this works is that each chart title gets the name from the 2nd name in the array. What I want is the 1st elment name to be the title of chart 1 and the 2nd element to be the title of chart 2... How can this be done? Or do I have a slight misunderstanding here?

My current workaround is to use a var=ii to get this to work. here is the fiddle but I am just wondering is there a better way, or maybe I need to rewrite it?


Parsing a symbolic equation in Python


I'm new to Python and find myself in the following situation. I work with equations stored as strings, such as:

>>> my_eqn = "A + 3.1B - 4.7D"

I'm looking to parse the string and store the numeric and alphabetic parts separately in two lists, or some other container. A (very) rough sketch of what I'm trying to put together would look like:

>>> foo = parse_and_separate(my_eqn);
>>> foo.numbers
    [1.0, 3.1, -4.7]
>>> foo.letters
    ['A', 'B', 'D']

Any resources/references/pointers would be much appreciated.

Thanks!

Update

Here's one solution I came up with that's probably overly-complicated but seems to work. Thanks again to all those responded!

import re                                                                                                                                               my_eqn = "A + 3.1B - 4.7D"                                                  

# add a "1.0" in front of single letters                                          
my_eqn = re.sub(r"(b[A-Z]b)","1"+ r"1", my_eqn, re.I)                    

# store the coefficients and variable names separately via regex                      
variables = re.findall("[a-z]", my_eqn, re.I)                               
coeffs = re.findall("[-+]?s?d*.d+|d+", my_eqn)                         

# strip out '+' characters and white space                                  
coeffs = [s.strip('+') for s in coeffs]                                     
coeffs = [s.replace(' ', '') for s in coeffs]                               

# coefficients should be floats                                
coeffs = list(map(float, coeffs))                                           

# confirm answers                                                           
print(variables)                                                            
print(coeffs) 

How to interpret Singular Value Decomposition results (Python 3)?


I'm trying to learn how to reduce dimensionality in datasets. I came across some tutorials on Principle Component Analysis and Singular Value Decomposition. I understand that it takes the dimension of greatest variance and sequentially collapses dimensions of the next highest variance (overly simplified).

I'm confused on how to interpret the output matrices. I looked at the documentation but it wasn't much help. I followed some tutorials and was not too sure what the resulting matrices were exactly. I provided some code to get a feel for the distribution of each variable in the dataset (sklearn.datasets) .

My initial input array is a (n x m) matrix of n samples and m attributes. I could do a common PCA plot of PC1 vs. PC2 but how do I know which dimensions each PC represents?

Sorry if this is a basic question. A lot of the resources are very math heavy which I'm fine with but a more intuitive answer would be useful. No where I've seen talks about how to interpret the output in terms of the original labeled data.

I'm open to using sklearn's decomposition.PCA

#Singular Value Decomposition
U, s, V = np.linalg.svd(X, full_matrices=True)
print(U.shape, s.shape, V.shape, sep="n")
(442, 442)
(10,)
(10, 10)

Web Scraping with Python - Looping for city name, clicking and get interested value


This is my first time with Python and web scraping. Have been looking around and still unable to get what I need to do.

Below are print screen of the elements that I've used via Chrome.

As you can see, it is from the dropdown 'Apartments'.

My 1st step in trying to do is get the list of cities from the drop down

My 2nd step is then, from the given city list, go to each of them (...url.../Brantford/ for example)

My 3rd step is then, given the available apartments, click each of the available apartments to get the price range for each bedroom type

Currently, I am JUST trying to 'loop' through the cities in the first step and it's not working.

Could you please help me out as well, if there's a good forum, article, tutorial etc that's good for beginner like me to read and learn. I'd really like to be good in this so that I may give me to society one day.

Thank you!

import requests
from bs4 import BeautifulSoup

url = 'http://www.homestead.ca/apartments-for-rent/'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html,'lxml')

dropdown_list = soup.find(".child-pages dropdown-menu a href")

print (dropdown_list.prettify())

Screenshot


Spyder crashes at start: UnicodeDecodeError


During a Spyder session my Linux froze. After startup, I could not start Spyder; I got the following error instead: (trusty)dreamer@localhost:~$ spyder Traceback (most recent call last): File "/home/dreamer/anaconda2/bin/spyder", line 2, in <module> from spyderlib import start_app File "/home/dreamer/anaconda2/lib/python2.7/site-packages/spyderlib/start_app.py", line 13, in <module> from spyderlib.config import CONF File "/home/dreamer/anaconda2/lib/python2.7/site-packages/spyderlib/config.py", line 736, in <module> subfolder=SUBFOLDER, backup=True, raw_mode=True) File "/home/dreamer/anaconda2/lib/python2.7/site-packages/spyderlib/userconfig.py", line 215, in __init__ self.load_from_ini() File "/home/dreamer/anaconda2/lib/python2.7/site-packages/spyderlib/userconfig.py", line 260, in load_from_ini self.readfp(configfile) File "/home/dreamer/anaconda2/lib/python2.7/ConfigParser.py", line 324, in readfp self._read(fp, filename) File "/home/dreamer/anaconda2/lib/python2.7/ConfigParser.py", line 479, in _read line = fp.readline() File "/home/dreamer/anaconda2/lib/python2.7/codecs.py", line 690, in readline return self.reader.readline(size) File "/home/dreamer/anaconda2/lib/python2.7/codecs.py", line 545, in readline data = self.read(readsize, firstline=True) File "/home/dreamer/anaconda2/lib/python2.7/codecs.py", line 492, in read newchars, decodedbytes = self.decode(data, self.errors) UnicodeDecodeError: 'utf8' codec can't decode byte 0xfe in position 2: invalid start byte (trusty)dreamer@localhost:~$ I have found this solution, which sounds very much like my problem, but am curious if there are others, and whether anyone knows why this occurred.

Not able to to login using request library in Python


I am trying to open this website, and access the dashboard's information using requests library in python. This is kind of webscraping but the issue is I am not able to login. I tried bunch of different methods to post my login credentials but nothing is working so far.

Website - https://www.handy.com/login

Login HTML - <input autofocus="autofocus" class="string email required" id="user_session_email" name="user_session[email]" required="required" size="50" type="email">

Password HTML - <input class="password required" id="user_session_password" name="user_session[password]" required="required" size="50" type="password">

Code:

First I tried to use the name attribute of both the username and password

import requests
url = "https://www.handy.com/login"
payload = {"user_session[email]": "email or username", "user_session[password]": "password"}
r = requests.post(url, data=payload)
print r.status_code
print r.reason

Also tried with using id attribute of both username and password but the issue is same. Status code is 500 and reason is Internal Server Error. I know how to create persistent sessions but will appreciate if you can help me to login in the website.


Using pandas, calculate Cramér's coefficient matrix


I have a dataframe in pandas which contains metrics calculated on Wikipedia articles. Two categorical variables nation which nation the article is about, and lang which language Wikipedia this was taken from. For a single metric, I would like to see how closely the nation and language variable correlate, I believe this is done using Cramer's statistic.

index   qid     subj    nation  lang    metric          value
5   Q3488399    economy     cdi     fr  informativeness 0.787117
6   Q3488399    economy     cdi     fr  referencerate   0.000945
7   Q3488399    economy     cdi     fr  completeness    43.200000
8   Q3488399    economy     cdi     fr  numheadings     11.000000
9   Q3488399    economy     cdi     fr  articlelength   3176.000000
10  Q7195441    economy     cdi     en  informativeness 0.626570
11  Q7195441    economy     cdi     en  referencerate   0.008610
12  Q7195441    economy     cdi     en  completeness    6.400000
13  Q7195441    economy     cdi     en  numheadings     7.000000
14  Q7195441    economy     cdi     en  articlelength   2323.000000

I would like to generate a matrix that displays Cramer's coefficient between all combinations of nation (france, usa, cote d'ivorie, and uganda) ['fra','usa','uga'] and three languages ['fr','en','sw']. So there would be a resulting 4 by 3 matrix like:

       en         fr          sw
usa    Cramer11   Cramer12    ... 
fra    Cramer21   Cramer22    ... 
cdi    ...
uga    ...

Eventually then I will do this over all the different metrics I am tracking.

for subject in list_of_subjects:
    for metric in list_of_metrics:
        cramer_matrix(metric, df)

Then I can test my hypothesis that metrics will be higher for articles whose language is the language of the Wikipedia. Thanks


mercredi 29 juin 2016

Using py.test with compiled library code


I have a python library with the following repository structure:

repobase
 |- mylibrary
 |  |- __init__.py
 |- tests
    |- test_mylibrary.py

Up to now, running the tests could simply be done by calling py.test in the repobase directory. The import mylibrary in test_mylibrary.py then used the local code in repobase/mylibrary.

Now, I've extended the library to use compiled code. Therefore the source code at repobase/mylibrary is not functional on its own. I have to do a setup.py build. This creates repobase/build/lib.linux-x86_64-2.7/mylibrary.

Is there a reasonable way to make py.test use this directory for importing mylibrary? Given these constraints:

  1. I do not want to include any sys.path / import magic in test_mylibrary.py because this may break tests in other envrionments.

  2. I don't want to give up the possibility to run py.test from repobase. Therefore modifying the PYTHONPATH does not help because . will still be first in sys.path. And thus repobase/mylibrary would be favored over repobase/build/lib.linux-x86_64-2.7/mylibrary.

If not, what's the standard way for testing python libraries, that need building?


Creating a data frame from two dataframes with period indices that overlap but are not identical


I've got two data frames, each one representing an irregular time series. Here is a sample from df1: index 2014-10-30 16:00 118 2014-10-30 19:00 160 2014-10-30 22:00 88 2014-10-31 00:00 128 2014-10-31 03:00 89 2014-10-31 11:00 66 2014-10-31 17:00 84 2014-10-31 20:00 104 2014-10-31 21:00 82 2014-10-31 23:00 95 2014-11-01 02:00 44 2014-11-01 03:00 54 2014-11-01 14:00 83 2014-11-02 03:00 78 2014-11-02 04:00 87 2014-11-02 13:00 90 And here is a sample from df2: index 2016-02-04 02:00 0.00 2016-02-06 00:00 50.00 2016-02-07 05:00 30.00 2016-02-07 21:00 26.00 2016-02-10 18:00 100.00 2016-02-11 00:00 20.00 2016-02-12 03:00 15.00 2016-02-12 18:00 90.00 2016-02-13 17:00 25.00 2016-02-13 19:00 40.00 2016-02-15 00:00 35.00 2016-02-18 04:00 14.00 2016-02-28 00:00 33.98 The indices are pandas Period objects with hourly frequency, and the range of time represented by the indices of the two data frames definitely has some overlap. How can I merge them into a single data frame that indexes by the union of their indices and leaves blanks (which I could later apply an ffill to) where one column lacks a value for a particular index? Here's what I tried: df1.merge(df2, how = 'outer') This gave me what seemed like a nonsensical result that loses the indices: 0 0 118.00 1 160.00 2 88.00 3 128.00 4 89.00 5 66.00 6 84.00 7 104.00 8 82.00 9 95.00 I also tried: df1.merge(df2, how = 'outer', left_on = 'index', right_on = 'index') This gave me a KeyError: pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3979)() pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3843)() pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12265)() pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12216)() KeyError: 'index' How can I do this merge?

convert to multiindex dataframe w/horizontal display and rename columns


let's say i have the following code: df1 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D']) df1['dataframe'] = 'df1' df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D']) df2['dataframe'] = 'df2' df = pd.concat([df1, df2]) df.reset_index().set_index(['dataframe','index']) this will return me a dataframe with 2 levels of indices, 'dataframe' and 'index'. i'm not sure what the correct term is but visually, the first index spans across rows as opposed to columns. there are 2 operations i would like to perform on this dataframe that i am struggling with. 1) i would like to rename the columns in each "sub-dataframe" to something different, taken from a different list and apply them accordingly based on the first index previously assigned. i have tried the following but it does not work if i display "df" again: new_cols = ['df1', 'df2'] for i,x in enumerate(new_cols): old_cols = df.loc[x].columns.tolist() df.loc[x].rename(columns={col_label: '{}_{}'.format(x,col_label) for col_label in old_cols}, inplace=True) so, to be clear, instead of A,B,C,D i'd like df1_A...df1_D and df2_A...df2_D 2) i would like to re-orient this dataframe such that they span across the columns and so i would be scrolling across in order to view each "sub-dataframe" rather than up and down. i've consulted the pandas API but still not able to get this right.

Python ElementTree: ElementTree vs root Element


I'm a bit confused by some of the design decisions in the Python ElementTree API - they seem kind of arbitrary, so I'd like some clarification to see if these decisions have some logic behind them, or if they're just more or less ad hoc. So, generally there are two ways you might want to generate an ElementTree - one is via some kind of source stream, like a file, or other I/O stream. This is achieved via the parse() function, or the ElementTree.parse() class method. Another way is to load the XML directly from a string object. This can be done via the fromstring() function. Okay, great. Now, I would think these functions would basically be identical in terms of what they return - the difference between the two of them is basically the source of input (one takes a file or stream object, the other takes a plain string.) Except for some reason the parse() function returns an ElementTree object, but the fromstring() function returns an Element object. The difference is basically that the Element object is the root element of an XML tree, whereas the ElementTree object is sort of a "wrapper" around the root element, which provides some extra features. You can always get the root element from an ElementTree object by calling getroot(). Still, I'm confused why we have this distinction. Why does fromstring() return a root element directly, but parse() returns an ElementTree object? Is there some logic behind this distinction?

python coercing to unicode when trying to compile with py2exe in os package


I'm trying to export to an exe file a script but when it's compiling it gives me "coercing to unicode" error.

Here's a screen capture: cmd

the setup.py file:

from distutils.core import setup
import py2exe

setup(console=['headers.py'],
options = {
              "py2exe":{
                  "packages": ["linecache", "csv", "Tkinter", "Tkinter", "tkFileDialog", "itertools", "os"]
                  }})

and the code:

import Tkinter, tkFileDialog, os, csv, itertools
root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
for subdir, dirs, files in os.walk(dirname):
    for file in files:
        with open (os.path.join(subdir, file), 'rb') as csvfile:
            #Check if the file has headers#
            if 'Result  :  Query Result' in csvfile.readline():
                if not os.path.exists(subdir + '/output/'):
                    os.makedirs(subdir + '/output/')
                with open(os.path.join(subdir + '/output/', file), 'wb') as out:
                    reader = csv.reader(itertools.islice(csvfile, 6, None), delimiter=',')
                    writer = csv.writer(out)
                    for row in reader:
                        #replace NIL occurrences with empty strings
                        try:
                            row[:] = [ele if ele != "NIL" else "" for ele in row]
                        except IndexError:
                            pass
                        writer.writerow(row) 

It seems to be the os import that I'm doing but I don't know why. I've looked it up and there's nothing that seems to help me.


MouseEnter/MouseLeave event is being queued for each activation


I am having an issue with on mouse enter and mouse leave it triggers fine the first time but during the animation if I move the mouse into the animation it causes a bug. After the animation finishes if I go back to do another mouse enter it automatically does a mouse leave as well. This behavior continues until I refresh the page. Its like it storing additional mouse enter and leaves per an event, how can I prevent this? I can provide more information if needed but I really can't seem to solve this at all... Edit: Basically what is occurring is that for each mouse enter it is adding the event to a queue regardless of whether it is currently being executed or not. This queue builds up and continues to execute the events until the queue is empty. I have tried this and it still keeps queueing: $('div#nav-sidebar').off('mouseleave').on('mouseleave', mouseLeaveEvent); $('div#nav-sidebar').off('mouseenter').on('mouseenter', mouseEnterEvent); HTML Current Code below.... var mouseLeaveEvent = function() { console.log('sidebar mouse leave!') $('li#GlasswareCandles').children('ul.menu-items').slideUp(750); $('li#CandleTins').children('ul.menu-items').slideUp(750); $('li#ScentedOils').children('ul.menu-items').slideUp(750); $('li#Air-Fresheners').children('ul.menu-items').slideUp(750); $('li#OtherProducts').children('ul.menu-items').slideUp(750); $(this).children('ul.blog_list.toggle_list').slideUp(1500); return false; }; var mouseEnterEvent = function() { console.log('sidebar mouse enter!') $(this).children('ul.blog_list.toggle_list').slideDown(500); return false; }; $('div#nav-sidebar').off('mouseleave').on('mouseleave', mouseLeaveEvent); $('div#nav-sidebar').off('mouseenter').on('mouseenter', mouseEnterEvent);

TemplateDoesnotExist at polls


When I am trying to apply template for views by loader module, I'm getting the following error.I want to know whether this error is due to my proxy network or error related to directories of template.

views.py is :

from django.shortcuts import render
from django.http import HttpResponse
from .models import Question
from django.template import loader

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

def detail(request, question_id):
    return HttpResponse("You're looking at question%s"%question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s"%question_id)

Traceback:

>File "C:python27libsite-packagesdjangocorehandlersbase.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

>File "C:python27libsite-packagesdjangocorehandlersbase.py" in >get_response
>  147.                     response = wrapped_callback(request, *callback_args, >**callback_kwargs)

>File "c:Python27Scriptsmysitepollsviews.py" in index
>  8.     template = loader.get_template('polls/index.html')

>File "C:python27libsite-packagesdjangotemplateloader.py" in get_template
>  43.     raise TemplateDoesNotExist(template_name, chain=chain)

>Exception Type: TemplateDoesNotExist at /polls/
>Exception Value: polls/index.html

Find value of string in Array


I've been working on this simple script for a few hours now and have hit a wall. I have an Array comprised of JSON values. When a user searches for a string and clicks the button, the script checks the string against the values stored in the Array. The section I'm stuck on is the conditional, which always returns no match - even if I enter a string which I know is in the JSON file. Code below. Any guidance/pointers would be greatly appreciated. Thanks for your help! Mark. $('#validate-info').on('click', function(){ // Get data, initiate callback $.getJSON('memberships.json', validateMembership); // Execute callback function function validateMembership(data) { // Capture entered value var userVal = document.getElementById('form-data').value; console.log(userVal); var infoTxt = ''; // Push all items into an Array var infoArray = []; $.each(data, function(member, memberInfo) { infoTxt += '<p><strong>Name:</strong> ' + memberInfo.name + '<br />'; infoTxt += '<strong>Membership No.:</strong> ' + memberInfo.number + '<br />'; infoTxt += '<strong>Expiry Date:</strong> ' + memberInfo.expiry + '</p>'; infoArray.push({ name: memberInfo.name, number: memberInfo.number, expiry: memberInfo.expiry }); }); if ($.inArray(userVal, infoArray) > -1 ) { // the value is in the array $('#response').html('<p style="color: green;">In the array</p>'); } else { $('#response').html('<p style="color: red;">Sorry, no matches.</p>'); } } });

Kendo MVC Grid / Details Grid - child grid's controller not getting called


Does Id have to be an integer or it can be string? It seems like in my case #=INVOICE# is getting value but it Read method to controller not sure why not getting called.

I tried looking at this example: http://demos.telerik.com/kendo-ui/grid/detailtemplate

code:
@(Html.Kendo().Grid<OpenInvoicesInfo>()
              .Name("grid")
  .Columns(columns =>
  {
      columns.Bound(p => p.INVOICE).ClientTemplate("<input type='checkbox' value='#= INVOICE #' class='testclass' />").Width(4);
      columns.Bound(i => i.INVOICE).Width(15);
      ...     
  })
      .ClientDetailTemplateId("OrdersTemplate")
  .DataSource(dataSource => dataSource
      .Ajax()
      .PageSize(8)
      .Read(read => read.Action("GetOpenInvoices", "Maint", new { cust = Request.QueryString["cust"] }))
  )

)

<script id="OrdersTemplate" type="text/kendo-tmpl">
@(Html.Kendo().Grid<CustomerComments>()
                            .Name("grid_#=INVOICE#")
            .Columns(columns =>
            {
                columns.Bound(o => o.INVOICE).Width(15);
                columns.Bound(o => o.Comment).Width(40);
            })
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(10)
                .Read(read => read.Action("GetCustomerComments", "Maint", new { invoices = "#=INVOICE#" }))
            )
            .Pageable()
            .Sortable()
            .ToClientTemplate()
)

    Controller:
    public ActionResult GetCustomerComments([DataSourceRequest] DataSourceRequest request, string invoices)
    {

        List<JNI.Enterprise.Contracts.CustomerComments> customer = InvoiceService.GetCustomerComments(invoices);

        return Json(customer.ToDataSourceResult(request));
    }

I will really appreciate if someone can reply. Does it only work if it is in entity framework. I am calling GetCustomerComments from a stored procedure. It is loading the first grid fine but not calling details grid's controller method.


What is the pythonic way of instantiating a class, calling one of its methods, and returning it from a lambda function?


I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working example:

class Foo():
    def parse(self, what):
        self.bar = what

foo = lambda x = Foo(): (x.parse("All set"), x)[-1]

print(foo().bar)
'All set'

The lambda function needs to instantiate a class, call one of its members to parse a string and change its internal state, and return the instantiated class. The only way to do this that I can think of at the moment is as shown in the above example: pass the instance as the default argument, create a list where the first element is the call to the method and the second is the instance itself, then select the last element.

Is there a more pythonic and elegant way of obtaining the same result?

EDIT: A few caveats: In the actual code the class Foo is defined in other modules, and I'm passing the lambda as an argument to another function, hence why I don't really need to name the callback. Indeed, what I actually have is something that looks like

widget.bind( 'some_signal', lambda x = Foo(): (x.parse("All set"), x)[-1] )

"while True:" loop returns nothing after one cycle


Here's the problem: my while loop doesn't repeat AT ALL, it just returns a blank line in the Python Launcher and doesn't carry on the code, i added a print function at the end to check if it did just skip. I used several ways of getting the code to repeat, such as "While True:" and "While 0 == 0" so i have started to think there is a problem somewhere else in the code, the code in question is:

while True:
 while i <= dice_amount:
   dice_output = random.randint(0,dice_range)
   print("dice number ", i, " is ", dice_output)
   i +=1
 while input_answer == "unknown":
   input_answer = input("would you like to throw the dice again? Y/N")
   if input_answer == "N":
    time.sleep(2)
    os.exit
   elif input_answer != "Y":
    input_answer = "unknown"

print("code is broken") #to see if code just skips loop

This is what happens when i try to repeat I would much appreciate the help and I'd just like to say i'm new to coding so I know it may not be optimised, however a comment saying how i could optimise it would be helpful.

At the start the variables are defined as such:

dice_amount = int(input("how many times would you like to roll the dice?"))
dice_range = int(input("how many numbers would you like on the dice?"))
input_answer = "unknown"
i = 1

Python generate grid on tkinter canvas


I am basically trying to generate a grid of pixels on a tkinter canvas. I have the following information passed into the function, the starting cordinates which are 0, 0 (posX, posY), I also have the an array of tiles (2500 for this example), than I have the level size in the x direction which is how many tiles will go from left to right before a new line of them is created. What I want to accomplish is to loop through the array of tiles I have, placing them down every 16 pixels, until it hits the end of the levels x direction, where it will reset the x position to one and add 16 to the y position. I managed to somewhat accomplish this, however this is the out I am receiving from it: My code is the following: for i in range(0, len(level.levelTiles)): if (i == level.levelSizeX - 1): scene.create_rectangle(posX, posY, posX+16, posY+16, fill="red") posY+=16 elif (i % level.levelSizeX == 1 and i > level.levelSizeX): scene.create_rectangle(posX, posY, posX+16, posY+16, fill="red") posX = 0 posY += 16 else: if (48 < i < 52): print (i) print (i > 3) print (i%50) print ("___________________") scene.create_rectangle(posX, posY, posX+16, posY+16, fill="red") posX += 16 I'm stumped on a way to go about this without adding a bunch of more if statements for various problems to get those two rectangles in the right position, since what I have written so far doesn't appear to work until after the tile i > max tiles in x direction + 1.

How to choose option on a web drop down box?


I'm using Python 3.5.1, and I need to automate the download of a bunch of reports every morning (through Python). These are imported from a web platform, which is of restricted access. I started with the following piece of code, which works fine:

import webbrowser, time
webbrowser.open('mylink')
time.sleep(10)

However, I'm struggling now with a drop down box, from which I have to choose and submit the location. Here's the HTML necessary to solve the problem:

<SELECT id=PRMT_SV_N000000000C88F800x000000000E8040B8_NS_ class="clsSelectControl pv" aria-invalid=false style="WIDTH: auto" hasLabel="true">
  <OPTION selected>MDM Location Code</OPTION>
  <OPTION>--------------------------------------------</OPTION>
  <OPTION value=3002 dv="3002  Ontario 002">3002&nbsp;&nbsp;Ontario&nbsp;&nbsp;002</OPTION>
  <OPTION value=3004 dv="3004  Fresno, CA  004">3004&nbsp;&nbsp;Fresno,&nbsp;CA&nbsp;&nbsp;004</OPTION>
  <OPTION value=3005 dv="3005  San Diego

The Finish/submit button HTML:

<BUTTON onclick="oCV_NS_.promptAction('finish')" onmouseover="this.className = 'bp bph'" onmouseout="this.className = 'bp'" id=finishN000000000C88F800x000000000E804A58_NS_ class=bp name=finishN000000000C88F800x000000000E804A58_NS_>Finish</BUTTON>

I have omitted most of the options of course. For this exercise, imagine that I want to choose the first one, 3004 Fresno, CA 004.


getting the status of disabled buttons with JS


I have 7 button on a webpage. When i click on btn7, I want to check how many buttons are disabled.

<button type="submit" class="btn btn-home" name= "btn-save1" id= "btn-save1"  required="required">Save</button>
<button type="submit" class="btn btn-home" name= "btn-save2" id= "btn-save2"  required="required">Save</button>
<button type="submit" class="btn btn-home" name= "btn-save3" id= "btn-save3"  required="required">Save</button>
<button type="submit" class="btn btn-home" name= "btn-save4" id= "btn-save4"  required="required">Save</button>
<button type="submit" class="btn btn-home" name= "btn-save5" id= "btn-save5"  required="required">Save</button>
<button type="submit" class="btn btn-home" name= "btn-save6" id= "btn-save6" required="required">Save</button>

JS

<script type="text/javascript">
$('document').ready(function()
{
                $(document).on('click', '#btn-save7', function(e){
                 alert('test');
})
});
</script>

How can I check if all buttons are disabled?

Edit:

I have checked these links but these are advanced and I am not that good with jQuery. JQuery select all elements without disabled AND no readonly?

http://api.jquery.com/disabled-selector/

jQuery: Checking for disabled attribute and adding/removing it?


Reset Interval breaks my continuos flow of the graph


I am trying to create flowing stacked area chart using d3.js. I have the graph working with a specific range. I am hitting the service every 10ms and getting all data and then triggering an event to start the graph. However my graph works only works for 30mins after that I am trying to reset the interval. When I am trying to do that it there is a jerk in the graph and somehow it breaks. I am not sure if I am doing it the right way. Here is code to look at.

var numbers = [];  
var values = []; 
var flag = false;
var fd;
var td;

//Calling the dates service
d3.json('/api/dates', function(error,data) {
  var dates = data;
  if(data != null){
  fd = new Date(data.start);
  td = new Date(data.end);
  var cnt = 0;
  var startGraph = function(){   
    if (fd > td) {
      console.log(" start Date is greater than end Date");
      clearInterval(interval);
      flag = true;
      $('.background').trigger('newPoint');
      return 
      setTimeout(startGraph,10);
    }
    var fdt = fd.toISOString(); 
    var tdt = new Date(fd.setMinutes(fd.getMinutes() + 30)).toISOString();

    //Calling service to get the values for stacked area chart
    d3.json("/api/service?start=" +fdt+ "&end=" +tdt, function(error,result) {
      if(result != null){
          numbers = numbers.concat(flightInfo.numbers);
          values[values.length] = flightInfo.values;
      }
    });
      cnt++;
  }
  function pushPoint(){
      var cnt=0;
      var interval = setInterval(function(){
        if(cnt!=values.length)
        {
        tick(values[cnt]);
        cnt++;}
        else
        clearInterval(interval);
      },400);        
  }

  //Calling the Processing Dates API to pull the data for area chart
  var interval = setInterval(startGraph,10); 
  }
}); 

How to find the id of the active Select2 element


I have a form with multiple select menus generated with Select2 (version 4) where the id value of each select element is set dynamically. I'd like to find the id of the select element the user clicks on.

I can get this to work

$('.js-example-tokenizer-ajax-data').on('select2:open', function (evt) {
        myValue = $(this).attr('id');
 });

But I need to use myValue as a parameter for data inside an ajax call so an option getting the id of the active select2 element is needed. I've seen posts that suggest var selectedEle = $(document.activeElement) but I don't know how to get the id from there.

UPDATE

It seems I can include this as the value for the data parameter

data: getSelectedElement(function() {
            return JSON.stringify({variable: myValue})
        }),

with the function as

function getSelectedElement(callback) {
        $('.js-example-tokenizer-ajax-data').on('select2:opening', function (evt) {
            myValue = $(this).attr('id');
            callback();
        });
    }

But there are still some timing issues since the ajax seems to fire before a select element is clicked since when I load the page I get an error 'NoneType' object has no attribute '__getitem__' I gather since there was no value for myValue when the page loaded.

Are there other options to get the id of the selected select2 element? Alternatively, are there ways to sort out the timing issue?


How to place dynamic carousel html with out .item class div in the static html page


I am trying to generate dynamic html (Bootstrap .item class divs) with Jquery. In my index.html:

<div id="collapseManagement" class="panel-collapse collapse ">
    <div class="panel-body">
        <div class="carousel slide management-item-carousel" id="osmManagementCarousel">
            <div class="carousel-inner" id="mngCourselInner">
            </div>
        </div>
    </div>
</div>

Jquery code:

//this will call from ajax callback
function dOMCHTMlreation(objEmployee) {

    for(var empIndex=0; empIndex<objEmployee.length;empIndex++){
        var  $itemhtmlEle=$("<div />")
        .addClass("item").html($("<div />")
        .addClass("col-md-12").html($("<a />")
        .attr("href","#")
        .append($("<img />")
        .attr("src",objEmployee[empIndex].Image)))
        .append($("<div />").addClass("caption").html($("<p></p>").html(objEmployee[empIndex].Reason))));
        $("#mngCourselInner").append($itemhtmlEle);
        // $dvItemClass.html("");
        }

      // courselCycle("#osmManagementCarousel");
      // courselSLider(".management-item-carousel .item");
    }   

 // ------------------------call back for Management section.
    function getJson(data) {
        if (data.success === -1) {
            return;
        }
        var objJson = $.xml2json(data);
        dOMCHTMlreation(objJson['#document'].Employees.Employee);

}

The code above throws the following error:

bootstrap.min.js:6 Uncaught TypeError: Cannot read property 'offsetWidth' of undefined

If I place the following html in the index page it is working fine

<div class="carousel-inner" id="mngCourselInner">
    <div class="item active">
    </div>
</div>

But I don't want to place .item div in my html page. Can anyone please help me to do this?


Coloring by Group using Scatter plot and Pandas Groupby [duplicate]


This question already has an answer here:

I would like to use pandas to group by a category, then color by that category on a scatter plot. I'd like to use a pandas object for the plotting because I'm using pandas columns for marker size, shape etc.

When I plot this using the pandas.plot function, I'm struggling to see how to color by group (in this example, by "cat"). The method I'm using below does not work when there are three items in a category, as then it interprets the color as an array of black-white values. Therefore the below plot is not what I want, I want it to be one color for CatA, and one color for catB.

Thanks for any help!

import pandas as pd
import pylab as plt
import seaborn as sns
import numpy as np

d = {'cat' : pd.Series(['catA', 'catA', 'catA', 'catB']),
    'y' : pd.Series([100., 52., 33., 4.]),
    'x': pd.Series([1., 2., 3., 4.]),
    'markersize' : pd.Series([50., 400., 600., 1600.]) }
df = pd.DataFrame(d)


colorlist = sns.husl_palette(len(df.groupby(df.cat)),l=.3, s=.8)

fig=plt.figure()
ax=fig.gca()
for i, (group, dataframe) in enumerate(df.groupby('cat')):
    ax=dataframe.plot(kind='scatter', x='x', y='y', ax=ax, color=colorlist[i], label=group, s=dataframe.markersize)

scatter


PyQt4 Signal and QObject.Emit()


I am learning GUI programing using python and pyqt4 and this is the app i am working on to learn Signal and Slots. This is a simple app which has a spinbox and a dialogue box that connected together using pyqt signals. but i added a class zerospinbox ,it supposed to print massage to console every time that the spinbox or dialogbox value becomes zero and count the number of occurrence of it using a, QObject.Emit() signal. I followed tutorial book to write it and whatever i do it does not show the massage.So if you can please take a look at the code and tell me where i am wrong:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        dial = QDial()
        dial.setNotchesVisible(True)
        spinbox = QSpinBox()

        layout = QHBoxLayout()
        layout.addWidget(dial)
        layout.addWidget(spinbox)
        zerospinbox = ZeroSpinBox()
        self.setLayout(layout)

        self.connect(dial, SIGNAL("valueChanged(int)"),
                     spinbox,SLOT("setValue(int)"))
        self.connect(spinbox, SIGNAL("ValueChanged(int)"),
                     dial,SLOT("setValue(int)"))
        self.setWindowTitle("Signal and Slots")
        zerospinbox = ZeroSpinBox()

        self.connect(zerospinbox, SIGNAL("atzero"),self.announce)        

    def announce(self,zeros):
        print("ZeroSpinBox has been at zero %d times" % zeros)        

class ZeroSpinBox(QSpinBox):

    zeros=0


    def __init__(self, parent=None):
        super(ZeroSpinBox, self).__init__(parent)
        self.connect(self, SIGNAL("valueChanged(int)"), self.checkzero)



    def checkzero(self):
        if self.value()==0:
            self.zeros +=1
            self.emit(SIGNAL("atzero"),self.zeros)

app =QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

thanks


Does canvas.bind work in a while loop


I have a program in Python 3.4.4 using Tkinter, that is supposed to move a square around the screen.

Unfortunately, canvas.bind doesn't seem to be working while inside a while loop, but it needs to be inside of the while loop or else the square won't move. This is because I'm technically drawing a new square with different x, y, x1, and y1 coordinates each time the loop runs, and the bind is what makes the square move in each direction according to the arrow keys.

So here's the code:

from tkinter import *
import time, random
tk = Tk()
canvas = Canvas(tk, width = 1000, height = 1000)
canvas.pack()

def move(event):
    if event.keysym == 'Up':
        y-=10
        y1-=10
    elif event.keysym == 'Down':
        y+=10
        y1+=10
    elif event.keysym == 'Right':
        x+=10
        x1+=10
    elif event.keysym == 'Left':
        x+=10
        x1+=10


background = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'orange') #draws background
ranNum=random.random()*960  #Creates a random number
ranNum1=random.random()*960 #Creates a random number
food = canvas.create_rectangle(ranNum, ranNum1, ranNum + 15, ranNum1 + 15, fill='green') #creates food
r1 = None
o = 0
length = 4
x = 500
y = 500
x1 = 515
y1 = 515
while o < length:          
    if canvas.find_overlapping(ranNum, ranNum, ranNum + 15, ranNum1 + 15) == True:
        x+=5
        y+=5
        x1+=5
        y1+=5
        canvas.delete(food)
    r=canvas.create_rectangle(x, y, x1, y1, fill = 'blue')
    canvas.bind('<KeyPress-Up>', move )
    canvas.bind('<KeyPress-Down>', move)
    canvas.bind('<KeyPress-Left>', move)
    canvas.bind('<KeyPress-Right>', move)
    time.sleep(.0)
    canvas.delete(r1)
    tk.update()
    r1 = r

Strange behavior on jQuery append() when sorting table


I was looking for a method to sort my very complex table, and found this approach which is working perfectly: ( completed code is here: http://jsfiddle.net/sg552sg552/Lsw6mnh4/15/ ) my html code is: <table> <thead> <tr> <th>string</th> </tr> </thead> <tbody> <tr> <td>C</td> </tr> <tr> <td>B</td> </tr> <tr> <td>A</td> </tr> </tbody> </table> and my js code is: $('th').click(function() {   var table =  $(this).parents('table').eq(0); var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index())); for (var i = 0; i < rows.length; i++) { console.info("== before append, rows count: " + $(table).find('tr').size() ) // WHY doesn't this "append" increase the total tr size ? table.append(rows[i]); console.info("== after append, rows count: " + $(table).find('tr').size() ) } }) function comparer(index) {   return function(a, b) {       var valA = getCellValue(a, index), valB = getCellValue(b, index); return $.isNumeric(valA) && $.isNumeric(valB) ?  valA - valB  : valA.localeCompare(valB)  ; } } function getCellValue(row, index) { return $(row).children('td').eq(index).html(); } The function( sorting the table) works perfectly, but I just wonder, why the "append()" function doesn't increase the "tr" count while there's no place to "remove" any "tr" ? Thanks a lot.

IPython console can't locate "backports.shutil_get_terminal_size" and won't load


I'm running Python2.7 on windows 10 doing env and most pkg management with Anaconda. After upgrading a number of packages, my ipython console now fails to start in any IDE or at the console. When I attempt to run it at the console I get this error:

Traceback (most recent call last):
File "C:Anaconda3Scriptsipython-script.py", line 3, in <module>
import IPython
File "C:Anaconda3libsite-packagesIPython__init__.py", line 48, in  <module>
from .core.application import Application
File "C:Anaconda3libsite-packagesIPythoncoreapplication.py", line 24, in <module>
from IPython.core import release, crashhandler
File "C:Anaconda3libsite-packagesIPythoncorecrashhandler.py", line 28, in <module>
from IPython.core import ultratb
File "C:Anaconda3libsite-packagesIPythoncoreultratb.py", line 121, in <module>
from IPython.utils.terminal import get_terminal_size
File "C:Anaconda3libsite-packagesIPythonutilsterminal.py", line 27, in <module>
import backports.shutil_get_terminal_size
ImportError: No module named backports.shutil_get_terminal_size

The first thing I tried to do was:

pip install --upgrade backports.shutil_get_terminal_size

output:

Requirement already up-to-date: backports.shutil_get_terminal_size in c:anaconda3libsite-packages

I've uninstalled and reinstalled ipython with both

conda uninstall ipython
conda install ipython

and

pip uninstall ipython
pip install ipython

Still won't work. Help please!


No color when I make python scatter color plot using third variable to define color


I try to make colorful scatter plot using third variable to define color. It is simple to use the following code:

plt.scatter(mH, mA, s=1, c=mHc)
plt.colorbar()
plt.show()

But I do not have many choices to modify the frame of the plot. I am trying the following code to make colorful scatter plot, at the same time I try to optimize the frame of the plot:

import numpy as np
import math
from matplotlib import rcParams
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator

fig, ax = plt.subplots()

cax = ax.scatter(mH,mA,s=0.5,c=mHc) ### mH, mA, mHC are the dataset
fig.colorbar(cax)
minor_locator1 = AutoMinorLocator(6)
minor_locator2 = AutoMinorLocator(6)
ax.xaxis.set_minor_locator(minor_locator1)
ax.yaxis.set_minor_locator(minor_locator2)
ax.tick_params('both', length=10, width=2, which='major')
ax.tick_params('both', length=5, width=2, which='minor')
ax.set_xlabel(r'$m_H$')
ax.set_ylabel(r'$m_A$')
ax.set_xticks([300,600,900,1200,1500])
ax.set_yticks([300,600,900,1200,1500])

plt.savefig('mH_mA.png',bbox_inches='tight')
plt.show()

But the plot I got is black-white. I believe the problem lies in this sentence fig.colorbar(cax), but I do not have much idea how to correct it. Anyone can offer me some idea to approach this issue. Thanks.enter image description here


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?


HTML code:

<tr class="">
    <td>1</td>
    <td>ABC</td>
    <td>17</td>
</tr>

<tr class="hidden">
    <td>2</td>
    <td>DEF</td>
    <td>22</td>
</tr>

<tr class="">
    <td>3</td>
    <td>GHI</td>
    <td>55</td>
</tr>

<tr class="hidden">
    <td>4</td>
    <td>JKL</td>
    <td>11</td>
</tr>
<input id="hideRows" name="hideRows" type="checkbox">

JS code:

$('#table1').DataTable();

$('#hideRows').change(function() 
{
    var table = $('#table1').DataTable();
    $('tr.hidden').hide();
    $.fn.dataTableExt.afnFiltering.push(function(oSettings, aData, iDataIndex) {
        if ($(oSettings.nTable).hasClass('hidden')) {
            return aData[16] == '' || $('#hideRows').is(':checked');
        } else return true;
    });
    table.draw();
});

Python - curve_fit of Plancks Law from data set


I have a large set of data that in terms of Intensity counts and Wavelength that I want fit with Planks Law to determine the guess parameter for Temperature. The Data set is imported as a text file import numpy as np import scipy as sp from scipy.optimize import curve_fit with open('Good_SolarRun2.txt') as g: data = g.read() data = data.split('n') Wavle2 = [float(row.split()[0]) for row in data] # Wavelength (nm) Int2 = [float(row.split()[1]) for row in data] # Intensity (counts) So I now define the fitting model for Planks Law (In terms of wavelength) https://en.wikipedia.org/wiki/Planck%27s_law from scipy.constants import h,k,c def Plancks_Law(lamb, T): a = np.float32( 2.0*h*c*c ) # J m^{-2} s^{-3} b = np.float32( (h*c)/(k) ) # K m s^{-2} return a/np.power(lamb,5.0) * 1/( np.exp( b/(lamb*T)) - 1 ) So now, I go about setting up the curve_fit configuration with my data set. # Convert Wavelength Arrays from nano-meters to meters x = [data*1e-9 for data in Wavle2] # This has the same shape as Wavle2, but these values are scaled by me. # Also the same shape as Int2 y = np.array(Intscale2p) p0_R = (5000.) optR, pcovR = curve_fit(Plancks_Law, x, y, p0_R) T_R = optR T_Rp = pcovR yM = Plancks_Law(x, T_R) This is not working for me. The parameter returns T_R = 5000, which is the value is et for the best guess. Am I doing something incorrect with the fits?

mardi 28 juin 2016

Mvc Ajax post from check-boxes in partial view


I have a partial view which is used to show a checkbox in a column of table in razor. When I click on any checkbox in the table its posting back to controller with Id of first row and not the Id of row in which the check-box is contained. The javascript function to post ajax request is "SaveChanges" as given below. The hidden field "RecurrenceScheduleId" is the primary key id.

Am I doing something wrong here?

- Following are my view & controller action:

  @model SMRDS.Model.RecurrenceSchedule

  @using (Ajax.BeginForm("_LogOccurancePartial", "Schedule",
            new AjaxOptions
            {
                UpdateTargetId = "tdOccurance",
                HttpMethod = "post",
                LoadingElementId = "btnProgress",
                OnBegin = "dialogBegin",
                OnSuccess = "updateSuccess",
                OnFailure = "dialogFailure"
            },
            new { id = "frm-toggle" }))
           {

            @Html.HiddenFor(model => model.RecurrenceScheduleId)
            @Html.CheckBoxFor(m => m.LogOccurences, new { @onclick ="SaveChanges(this)" })
            }
<script> 

function updateSuccess() {}

function dialogFailure() {}

function dialogComplete() {}

function dialogBegin() {}

function SaveChanges(checkboxInput) {
    $.ajax({
        type: 'POST',
        url: '/Schedule/_LogOccurancePartial',
        data: { newValue: checkboxInput.checked, id: $("#RecurrenceScheduleId").val() },
        dataType: 'json',
        success: function (response) {
           //handle success
        }
    });
}

Controller Action :

 public JsonResult _LogOccurancePartial(bool newValue,int id)
 { 
        var result = BLL.Service.RecurrenceSchedules.UpdateLogOccurence(id, newValue);

        return Json(new { result = result }, JsonRequestBehavior.AllowGet);
 }

Update

Following is the html rendered for hidden fields. At present I have only two rows with Ids "40" & "41".

<input data-val="true" id="RecurrenceScheduleId"
    name="RecurrenceScheduleId" type="hidden" value="40"> 

<input data-val="true" id="RecurrenceScheduleId"
    name="RecurrenceScheduleId" type="hidden" value="41">

dynamic countdown timer not working the clock is not properly showing time


I have a javascript flipclock first of all when ever i refresh the page it start from the beginning as I want it to be resumed from where it was stopped before page refresh and I want my timer to be stoped every day at 4:00 AM or 4:00 PM but when I tried to enter some php the clock is not properly showing i don't know is there any php fiddle available so I can show what is the bud like jquery fiddle

Here is what i tried to do so

    $query      = mysqli_query($connection, "SELECT * FROM timer WHERE id = '1'");
    $timer      = mysqli_fetch_array($query);
    $time_st    = $timer[2];
    $time_end   = $timer[3];
    $date       = $timer[1];
    $time_rem   = $date . " " . $time_st;
    $rem        = strtotime("$time_rem") - time();
    $today      = getdate();
    $time_end   = $today['hours'] . ':' . $today['minutes'] . ':' . $today['seconds'];
?>

My Clock

<div class="clock_area">
            <div class="clock"></div>
            <p>COUNTDOWN TILL 4:20</p>
        </div>

<script type="text/javascript">

    $(document).ready(function() {
        var clock;

        clock = $('.clock').FlipClock({
            clockFace: 'HourlyCounter',
            autoStart: false,
            callbacks: {
                stop: function() {
                    $('.message').html('Offer Closed')
                }
            }
        });
         <?php 
          if($time_end == $time_st || $time_end == '04:20:00') { 
              ?>        
                   clock.setTime(0);
        <?php } else { ?>
        clock.setTime(<?php echo $rem; ?>);
          <?php } ?>
        clock.setCountdown(true);
        clock.start();
    });
</script>

Please help me out with this like my scenario is really simple but little bit logical though


airflow get result after executing an operator


I have configured airflow and created some Dags and subDags that call several operators.

My trouble is that when an operators runs and finishes the job, I'd like to receive the results back in some python structure. For instance:

File1.py

  ...
    ...
    sub_dag_one=SubDagOperator(subdag=subdag_accessHive(
PARENT_DAG_NAME, CHILD_DAG_NAME, default_args, STEP, macros,path,
       ),
        task_id=DELP_DAG_NAME,
        dag=dag,
    )

File2.py

  from airflow import DAG
    from airflow.operators import HiveOperator
def subdag_callHive(parent, child, args, step,
                         user_defined_macros, path
                        ):
        dag_subdag = DAG(
            dag_id='%s.%s' % (parent, child),
            default_args=args,
            schedule_interval="@daily",
            template_searchpath=path,
            user_defined_macros=user_defined_macros,
        )

        # some work...

        HiveOperator(
            task_id='some_id',
            hiveconf_jinja_translate=True,
            hql='select field1 from public.mytable limit 4;',
            trigger_rule='all_done',
            dag=dag_subdag,
        )

        return dag_subdag 

The function subdag_callHive is called from another python script where the main Dag is defined and all the other parameters needed.

I just need would like to be able to get the result from the HiveOperator (*select * from public.mytable limit 4;*) that would be 4 values in this case.

the returned dag_subdag is an object < class 'airflow.models.DAG' > and contains all the attributes/data passed to the call but no information about what the HiveOperator did.

Is this possible? if So, how can it be accomplished.


Sinon FakeServer no requests?


I'm following the SinonJS Fake Server tutorial and I'm running this simple code:

var server;

before(function () { server = sinon.fakeServer.create(); });
after(function () { server.restore(); });

it("calls callback with deserialized data", function () {
    var callback = sinon.spy();
    getTodos(42, callback);

    // This is part of the FakeXMLHttpRequest API
    server.requests[0].respond(
        200,
        { "Content-Type": "application/json" },
        JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
    );

    assert(callback.calledOnce);
});

I'm including the getTodos function in the same file. Here it is as well:

function getTodos(listId, callback) {
    $.ajax({
         url: "/todo/" + listId + "/items",
         success: function (data) {
             // Node-style CPS: callback(err, data)
             callback(null, data);
         }
    });
}

However, I'm getting an error TypeError: Cannot read property 'respond' of undefined. It looks like server.requests is empty -- why is this? How can I make sure the requests show up?

UPDATE: I was able to narrow down the issue. I added an "error" callback to the getTodos function, and did console.log for the error. It turns out there's a Syntax error coming from the jsdom node module trying to do urlObj = new URL(uri, documentBaseURLSerialized(this._ownerDocument)); which is then causing $.ajax({ to fail. Anyone have any ideas on this?

UPDATE 2: Now I'm testing another AJAX request in a different React component (different file) and I'm getting this error again. If I move the function into the same file, I don't have the error. What's going on here?


Jquery function only works with setInterval but not with $(document).ready


$(document).ready(function(){
    var $exp1 = $("#exp1");
    var $hackp =$("#hack-expanded-details div p");
    if($exp1.is(":hover")) {
      $exp1.animate({height:"14em"},200);

    }
    else {
       $exp1.animate({height:"8em"},200);

    }
});
#experience
{
    padding-top:3em;
}
#exp-heading
{

    margin-top:3em;
    background-color:rgba(0, 113, 255, 1);
    width:22em;
    height:3.5em;



}
#exp-heading h3
{
    padding-top:.5em;
    color:#FFF;

}
#exp-heading  i
{
    padding-left:1.5em;
    padding-right:3px;
    color:#FFF;
}
#exp1
{
    background-color:#FFF;
    border:2px solid rgba(0, 113, 255, 1);
    color:#000;
    width:30em;
    margin-top:3em;
    margin-left:9em;
    height:8em;
    border-radius:4px 4px 4px 4px;
}

#hackathon h3 
{
    text-align:center;

}
#hackathon h4
{
    text-align:center;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="experience">
                    <div id="exp-heading">
                    <h3><i class="fa fa-laptop"></i>Experience</h3>
                    </div>

                        <div id="exp1">
                            <div id="hackathon">
                                <h3>GlobalHack IV</h3>
                                <h4>Front-End Developer</h4>
                                <p><span class="italic"> CIC St. Louis, Missouri</span></p>
                            </div>
                            <div id="hack-expanded-details">

                            </div>
                        </div>

it doesn't work. Any ideas?

It did work with setInterval but no clean and setInterval is not what I wanted to use anyways I updated the snippet sorry I am posting for the first time on here so far I never needed too. I am also not unfamiliar with coding that's why this a big mystery for me why it all of the sudden is not working


Python - Replace character not working [duplicate]


This question already has an answer here:

I am running a script through python that inserts data into a database. I can insert several rows; however, if I try to insert a row that has a single quote in it, it gives me an error:

sName = "Jim O'Connor"

returns the error:

ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression ''Jim O'Connor')'. (-3100) (SQLExecDirectW)")

I have tried to use the replace function, but it never turns out quite how I need it to.

sName = sName.replace("'","'")

returns Jim O'Connor

and

sName = sName.replace("'","\'")

returns Jim O\'Connor

What I need is Jim O'Connor

Thanks in advance!

Update: The article posted as an effort to mark this as a duplicate in no way answers the question of why I am getting this error. It is a question on parameterization (which I did not ask about). Although I understand that the answer may be to use parameters, asking why an escaped SQL statement is not working is entirely different then asking how to parameterize. I will review the article to determine if using parameters fixes the issue.


Divide a canvas into spaces of same width and height


I want to have a canvas which covers the full page (apart from a top area and a left area) as shown in the image below (blue area).

I want to divide the canvas in squares/rectangles (yellow lines) each one with the same height and width in a way that I can add some fixed size rectangle (green rectangles) in the grid. Well, something similar to Windows 7 Desktop grid (or Windows 8 Metro) in which icons are aligned to the grid.

The way I guessed to implement it is:

  • draw the blue Canvas: get page height and width and subtract the grey area
  • divide the Canvas in equal dimensions rectangles in a way that when I drag and drop one of the green rectangle into it gets aligned to the grid: no idea here
  • drawing and dragging green rectangles (let's call them nodes): I'm going to use appendTo() to add a Div for each rectangle, and using jQuery UI to drag them. This is already done. Here is an example: http://myownlibrary.altervista.org/es4/

  • One further step I would take is to make the canvas area extendable,that is, when all the rectangles contain some node, I want the canvas to "grow" in width/height (and it is going to be scrolled using horizontal and vertical scroll bars).

it says canvas and has a grid


Hierarchy Element Selection by Class for Window and Attr url


Hello I'm a beginner in related tags, I used as reference: Bind Keyboard to left/right navigation I have this HTML: <div class="pager"> <br /> <div class="myjsp-prev-next" style="text-align:inherit;"> <span class="myjsp-prev"><a href="{url}">Prev</a></span> <span class="myjsp-next"><a href="{url}">Next</a></span> </div> </div> <br /> Javascript: $(function() { $(document).keyup(function(e) { switch (e.keyCode) { case 37: var x = document.querySelectorAll(".myjsp-prev"); window.location = x.attr('href'); break; case 39: window.location = $('span.myjsp-next a').attr('href'); break; } }); }); I was reading the API for JQUERY and wanted to try to use the querySelector to select the elements with that class and then go to the next or prev url. I was reading the hierarchy page for JQUERY and I'm not sure what is wrong. Thanks in advance. EDIT: I tried adding: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { $(document).keyup(function(e) { switch (e.keyCode) { case 37: var x = document.querySelectorAll(".myjsp-prev a")[0]; var href = x.getAttribute('href'); window.location = x.attr('href'); break; case 39: var y = document.querySelectorAll(".myjsp-next a")[0]; var href = y.getAttribute('href'); window.location = y.attr('href'); break; } }); }); </script> I get the error in console log: Uncaught TypeError: y.attr is not a function Uncaught TypeError: x.attr is not a function I also tried eq(x) and eq(y), but still doesn't work. Thank you.

Radix sorting, "Queue" object not iterable


I've come to an end with my assignment, I don't know where I go from where I am right now, the code is currently looking like this:

def radixsorting1(n,m):
    div=1
    mod=10
    bin_list=[]
    alist=[]
    r=[]
    for bins in range(0,10):
        bin_list.append(Queue())
    for k in range(0,m):
        r.append(random.randint(1,10**n))
    if not len(r)==0:
        o=max(r)
        y=len(str(o))
    for p in range(y):
        for num in alist:
            minsta_tal=value%mod
            minsta_tal=int(minsta_tal//div)
            bin_list[minsta_tal].put(num)
        s=[]
        for bins in bin_list:
            while not bins.isempty():
                s.append(bins.dequeue())
    return s  

What I've been trying to do is to create 10 queues in put them in a list, then random m numbers from 1 to 10^n. Lets say I get 66 and 72, then I first sort them by the "small number", that is 6 and 2 in my numbers, then put them in a lost, and then do the process all over again but for the number 6 and 7 (the bigger number). In its current shape I get the error "Queue" object is not iterable.

My Queue class is looking like this, I think this one is okay.

class Queue:
    def __init__(self):
        self.lista=[]

    def put(self,x):
        self.lista.append(x)

    def get(self):
        if not len(self.lista)==0:
            return self.lista.pop(0)

    def isempty(self):
        if len(self.lista)==0:
            return True
        else:
            False

    def length(self):
        return len(self.lista)


    def dequeue(self):
        if not len(self.lista)==0:
            n=self.lista.pop(0)
            return n