python,mysql,csv,datetime , Python Datetime into MySQL


Python Datetime into MySQL

Question:

Tag: python,mysql,csv,datetime

I'm parsing several years worth of daily solar generation CSV files that look like this (with YY-MM-DD.CSV filename format)

sep=;
Version CSV|Tool SunnyBeam11|Linebreaks CR/LF|Delimiter semicolon|Decimalpoint point|Precision 3|Language en-UK|TZO=0|DST|11/03/2012

    ;SN: xyz
    ;SB blah
    ;xyz
    Time;Power
    HH:mm;kW
    00:10;0.000
    00:20;0.000
    00:30;0.000
    00:40;0.000
    00:50;0.000
    01:00;0.000
    01:10;0.000
    01:20;0.000
    01:30;0.000
    01:40;0.000
    01:50;0.000
    02:00;0.000
    02:10;0.000
    02:20;0.000
    02:30;0.000
    02:40;0.000
    02:50;0.000
    03:00;0.000
    03:10;0.000
    03:20;0.000
    03:30;0.000
    03:40;0.000
    03:50;0.000
    04:00;0.000
    04:10;0.000
    04:20;0.000
    04:30;0.000
    04:40;0.000
    04:50;0.000
    05:00;0.000
    05:10;0.000
    05:20;0.000
    05:30;0.000
    05:40;0.000
    05:50;0.000
    06:00;0.000
    06:10;0.000
    06:20;0.000
    06:30;0.000
    06:40;0.000
    06:50;0.000
    07:00;0.000
    07:10;0.012
    07:20;0.048
    07:30;0.072
    07:40;0.078
    07:50;0.114
    08:00;0.150
    08:10;0.156
    08:20;0.168
    08:30;0.204
    08:40;0.180
    08:50;0.198
    09:00;0.210
    09:10;0.222
    09:20;0.294
    09:30;0.330
    09:40;0.342
    09:50;0.402
    10:00;0.492
    10:10;0.396
    10:20;0.474
    10:30;1.224
    10:40;1.374
    10:50;1.416
    11:00;1.470
    11:10;1.500
    11:20;1.530
    11:30;1.530
    11:40;1.542
    11:50;1.536
    12:00;1.554
    12:10;1.584
    12:20;1.584
    12:30;1.572
    12:40;1.560
    12:50;1.548
    13:00;1.518
    13:10;1.494
    13:20;1.470
    13:30;1.440
    13:40;1.404
    13:50;1.356
    14:00;1.332
    14:10;1.284
    14:20;1.236
    14:30;1.194
    14:40;1.110
    14:50;1.050
    15:00;0.972
    15:10;0.888
    15:20;0.816
    15:30;0.744
    15:40;0.648
    15:50;0.594
    16:00;0.528
    16:10;0.438
    16:20;0.342
    16:30;0.264
    16:40;0.228
    16:50;0.180
    17:00;0.120
    17:10;0.084
    17:20;0.048
    17:30;0.024
    17:40;0.006
    17:50;0.000
    18:00;0.000
    18:10;0.000
    18:20;0.000
    18:30;0.000
    18:40;0.000
    18:50;0.000
    19:00;0.000
    19:10;0.000
    19:20;0.000
    19:30;0.000
    19:40;0.000
    19:50;0.000
    20:00;0.000
    20:10;0.000
    20:20;0.000
    20:30;0.000
    20:40;0.000
    20:50;0.000
    21:00;0.000
    21:10;0.000
    21:20;0.000
    21:30;0.000
    21:40;0.000
    21:50;0.000
    22:00;0.000
    22:10;0.000
    22:20;0.000
    22:30;0.000
    22:40;0.000
    22:50;0.000
    23:00;0.000
    23:10;0.000
    23:20;0.000
    23:30;0.000
    23:40;0.000
    23:50;0.000
    00:00;0.000


    E-Today kWh;8.313
    E-Total kWh;67.471

My Python is able to parse out the date in the last field of line 2 and then iteratively combine it with the time on each row. Using the combo of date and time as a timestamp (type incompatibility is probably the problem?) I try to insert it into a mySQL database into a column of type timestamp (and power into a column of type DECIMAL(4,3))

I've played around with various type combinations but clearly not in the right way. I'd be really grateful for a Python expert to clarify how to successfully get the synthesised date into a form compatible with MySQL timestamp.

The Python is:

#!/usr/bin/python

from os import listdir
from datetime import datetime
import MySQLdb
#from sys import argv


def is_dated_csv(filename):
    """
    Return True if filename matches format YY-MM-DD.csv, otherwise False.
    """
    date_format = '%y-%m-%d.csv'

    try:
        date = datetime.strptime(filename, date_format)
        return True
    except ValueError:
        # filename did not match pattern
        print filename + ' did NOT match'
        pass
#'return' terminates a function
    return False


def parse_for_date(filename):
  """
  Read file for the date - from line 2 field 10
  """
  currentFile = open(filename,'r')
  l1 = currentFile.readline() #ignore first line read
  date_line = currentFile.readline() #read second line
  dateLineArray = date_line.split("|")
  day_in_question = dateLineArray[-1]#save the last element (date)
  currentFile.close()
  return day_in_question


def normalise_date_to_UTF(day_in_question):
  """
  Rather wierdly, some days use YYYY.MM.DD format & others use DD/MM/YYYY
  This function normalises either to UTC with a blank time (midnight)
  """
  if '.' in day_in_question: #it's YYYY.MM.DD
    dateArray = day_in_question.split(".")
    dt = (dateArray[0] +dateArray[1] + dateArray[2].rstrip() + '000000')
  elif '/' in day_in_question: #it's DD/MM/YYYY
    dateArray = day_in_question.split("/")
    dt = (dateArray[2].rstrip() + dateArray[1] + dateArray[0] + '000000')
  theDate = datetime.strptime(dt,'%Y%m%d%H%M%S')
  return theDate #A datetime object


def parse_power_values(filename, theDate):
  currentFile = open(filename,'r')
  for i, line in enumerate(currentFile):
    if i <= 7:
      doingSomething = True
      #print 'header' + str(i) + '/ ' + line.rstrip()
    elif ((i > 7) and (i <= 151)):
      lineParts = line.split(';')
      theTime = lineParts[0].split(':')
      theHour = theTime[0]
      theMin = theTime[1]
      timestamp = theDate.replace(hour=int(theHour),minute=int(theMin))
      power = lineParts[1].rstrip()
      if (float(power) > 0):
        #print str(i) + '/ ' + str(timestamp) + '   power = ' + power + 'kWh'
        append_to_database(timestamp,power)
      #else:
      #  print str(i) + '/ '
    elif i > 151:
      print str(timestamp) + ' DONE!'
      print '----------------------'
      break
  currentFile.close()

def append_to_database(timestampval,powerval):
  a = datetime.strptime(timestampval,"%b %d %Y %H:%M")
  host="localhost", # your host, usually localhost
  user="root", # your username
  passwd="******"
  database_name = 'SunnyData'
  table_name = 'DTP'
  timestamp_column  = 'DT'
  power_column = 'PWR'
  sql = ("""INSERT INTO %s(%s,%s) VALUES(%s,'%s')""", ('table_name', 'timestamp_column', 'power_column', a.strftime('%Y-%m-%d %H:%M:%S'), powerval) )
  print sql
  #db = MySQLdb.connect(host,user,passwd,database_name)
  cur = SD.cursor()
  try:
    cur.execute(sql)
    print 'SQL: ' + sql
    SD.commit()
  except:
    print 'DB append failed!'
    SD.rollback()

# Main start of program
path = '.'
for filename in listdir(path):
    if is_dated_csv(filename):
        SD = MySQLdb.connect(host="localhost", user="root",passwd="**********", db = 'SunnyData')
        print filename + ' matched'
      # Do something with the desired .csv file
        day_in_question = parse_for_date(filename)
        print 'the date is ' + day_in_question
        theDate = normalise_date_to_UTF(day_in_question)
        parse_power_values(filename, theDate)
        SD.close()

    pass

and the DB create SQL looks like this

CREATE TABLE `DTP` (
  `idDTP` int(11) NOT NULL,
  `DT` timestamp NULL DEFAULT NULL,
  `PWR` decimal(4,3) DEFAULT NULL,
  PRIMARY KEY (`idDTP`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Many thanks,

Greg (Python novice)


Answer:

I took your code, and it seems like the main issues are in the append_to_database function.

It looks like the return value of normalise_date_to_UTF returns a datetime object, which is being passed to append_to_database (as the timestampval argument), and that is being run through strptime, which is unnecessary since it's not a string and already a datetime.

The SQL statement also needed some adjusting for how you replace variables in strings. In python, the % operator when following a string, allows you to insert values into that string via format codes. Also, table_name, timestamp_column, and power_column had single quotes around them, which meant that the literal string would be inserted, rather than the variable's value.

Basically your append_to_database function should look like this:

def append_to_database(timestampval,powerval):
  host="localhost", # your host, usually localhost
  user="root", # your username
  passwd="******"
  database_name = 'SunnyData'
  table_name = 'DTP'
  timestamp_column  = 'DT'
  power_column = 'PWR'
  sql = ("INSERT INTO %s (%s,%s) VALUES('%s','%s')" % (table_name, timestamp_column, power_column, timestampval.strftime('%Y-%m-%d %H:%M:%S'), powerval) )
  print sql
  #db = MySQLdb.connect(host,user,passwd,database_name)
  cur = SD.cursor()
  try:
    cur.execute(sql)
    print 'SQL: ' + sql
    SD.commit()
  except:
    print 'DB append failed!'
    SD.rollback()

As for the MySQL DB, the SQL inserts are not specifying a value for the idDTP column, and the column isn't auto incrementing, so after python inserts the first value, all subsequent inserts will fail, because the value defaults to 0 for each insert. This can be resolved in one of two ways, altering the python code to specify a value for idDTP or setting idDTP to be auto incrementing.

If you want to alter your table to have auto incrementing ids, the SQL syntax (run on the MySQL server) is:

ALTER TABLE DTP MODIFY COLUMN idDTP INT auto_increment

or you can recreate the table like this:

CREATE TABLE `DTP` (
  `idDTP` int(11) NOT NULL AUTO_INCREMENT,
  `DT` timestamp NULL DEFAULT NULL,
  `PWR` decimal(4,3) DEFAULT NULL,
  PRIMARY KEY (`idDTP`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I ran your code, making the changes above, and with the first part of the data provided, when querying MySQL for the DTP table, it looks like this:

select * from DTP;
+-------+---------------------+-------+
| idDTP | DT                  | PWR   |
+-------+---------------------+-------+
|     1 | 2012-03-11 07:10:00 | 0.012 |
|     2 | 2012-03-11 07:20:00 | 0.048 |
|     3 | 2012-03-11 07:30:00 | 0.072 |
|     4 | 2012-03-11 07:40:00 | 0.078 |
|     5 | 2012-03-11 07:50:00 | 0.114 |
|     6 | 2012-03-11 08:00:00 | 0.150 |
|     7 | 2012-03-11 08:10:00 | 0.156 |
|     8 | 2012-03-11 08:20:00 | 0.168 |
|     9 | 2012-03-11 08:30:00 | 0.204 |
|    10 | 2012-03-11 08:40:00 | 0.180 |
+-------+---------------------+-------+

Hope that helps you with this project!


Related:


represent an index inside a list as x,y in python


python,list,numpy,multidimensional-array
I have a list which contains 1000 integers. The 1000 integers represent 20X50 elements of dimensional array which I read from a file into the list. I need to walk through the list with an indicator in order to find close elements to each other. I want that my indicator...

MySQL: Select several rows based on several keys on a given column


mysql,sql,database
I have this mysql table structure: ------------------------------------ | item_id | meta_key | meta_value | ------------------------------------ 159 category Bungalow 159 location Lagos 159 price 45000 160 category Bungalow 160 location Abuja 160 price 53500 ... 350 category Bungalow 350 location Lagos 350 price 32000 What I'd like to do is select...

How to program a recurring billing/invoice system using PHP and MySQL


php,mysql
I have already programmed a basic invoicing system using PHP/MySQL which has a table structure as follows; Invoice table; invoice_id, invoice_date, customer_id, etc Invoice line table; invoice_line_id, invoice_id, quantity, price, description, etc I need the system to automatically generate future invoices at set intervals (for example every 1 week or...

How to check for multiple attributes in a list


python,python-2.7
I am making a TBRPG game using Python 2.7, and i'm currently making a quest system. I wanted to make a function that checks all of the quests in a list, in this case (quests), and tells you if any of of the quests in the list have the same...

If I export my database with phpmyadmin will it lock my tables or take my database down?


mysql,database,phpmyadmin
I want to create a backup of my database using the phpmyadmin export function. the database can't have any down time so I need to know if running a database export will take the database down? I've looked on-line but all I get is instructions on how to export. No...

compare today's date with unix timestamp value in database


php,mysql
In database I am storing date value unix timestamp value for e.g.'1434952110' using time() now I am trying to compare todays value with this value as below $jobpostdate = date("Y-m-d");//today's date passing in database to compare query $sql = "SELECT jsp_title, jsp_subtitle, jsp_desc, jsp_location, jsp_date "; $sql .= "FROM js_projects...

C# MySQL Parameters.AddWithValue


c#,mysql
Hello I found this code snippet for Adding Values to MySQL Commands in C# MySqlCommand command = connection.CreateCommand(); command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES (?name)"; command.Parameters.AddWithValue("?name", mitarbeiter); connection.Open(); command.ExecuteNonQuery(); Now I want to add data to more than one coloumn, but if i try it like this: command.Parameters.AddWithValue("?id", Projektid,...

How to search images by name inside a folder?


php,mysql,image
I have a MySQL table with a column "rounds" and each "rounds" has his own photos. Exemple round1 has photos from start=380 end=385. This means it has 6 photos and the name of the photos contains 380,381,382,383,384 or 385 inside. I use this PHP code to display the photos from...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)


php,mysql,mysqli,sql-injection,sql-insert
I am new to PHP and hope someone can help me with this. I would like to store two values (an email and a password) in a MySQL db using PHP. The input is passed to the PHP page via Ajax in jQuery (through an onclick event on a website)....

C# - Can't connect to remote MySQL server


c#,mysql
My problem is that I can't connect to my website remote MySQL server. I have read all answers in stackoverflow.com, but I can't find right answer. Here's my C# code: using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { SqlConnection...

Pandas - Dropping multiple empty columns


python,pandas
I have some tables where the first 11 columns are populated with data, but all columns after this are blank. I tried: df=df.dropna(axis=1,how='all') which didn't work. I then used: df = df.drop(df.columns[range(11,36)], axis=1) Which worked on the first few tables, but then some of the tables were longer or shorter...

Can Rails deal with DB uniqueness without index?


mysql,ruby-on-rails,rdbms
I see add_index ~ unique: true statement in schema.rband think uniqueness is constraint for table, not for index.Using index is one of way realizing uniqueness, Programmer should not designate to the RDBMS "how" and index quicken searching but take costs inserting. In fact, is there another way to keep uniqueness...

Sort when values are None or empty strings python


python,list,sorting,null
I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

MySQL - How can I know my query is tuned?


mysql,performance,explain
I'm creating a DB from scratch and I'm trying to create queries with performance in mind. For test purpose I filled my tables with test data. My query needs to join 3 tables: 2 with millions of rows and the third with hundred thousands rows. How can I know my...

I Want to fetch SQL Records in MySQL of current Year


mysql
I am using the query SELECT count(enq.`enquiryId`), Month(enq.`date`), Year(enq.`date`) FROM enquiry enq GROUP BY MONTH(enq.`date`) But I get all year records. I just want to get Current or any input year(At Runtime) records. Please help....

Find the tf-idf score of specific words in documents using sklearn


python,scikit-learn,tf-idf
I have code that runs basic TF-IDF vectorizer on a collection of documents, returning a sparse matrix of D X F where D is the number of documents and F is the number of terms. No problem. But how do I find the TF-IDF score of a specific term in...

Displaying a 32-bit image with NaN values (ImageJ)


python,image-processing,imagej
I wrote a multilanguage 3-D image denoising ImageJ plugin that does some operations on an image and returns the denoised image as a 1-D array. The 1-D array contains NaN values (around the edges). The 1-D array is converted back into an image stack and displayed. It is simply black....

In sklearn, does a fitted pipeline reapply every transform?


python,scikit-learn,pipeline,feature-selection
Apologies if this is obvious but I couldn't find a clear answer to this: Say I've used a pretty typical pipeline: feat_sel = RandomizedLogisticRegression() clf = RandomForestClassifier() pl = Pipeline([ ('preprocessing', preprocessing.StandardScaler()), ('feature_selection', feat_sel), ('classification', clf)]) pl.fit(X,y) Now when I apply pl on a new set, pl.predict(X_classify); is RandomizedLogisticRegression going...

Python - Opening and changing large text files


python,replace,out-of-memory,large-files
I have a ~600MB Roblox type .mesh file, which reads like a text file in any text editor. I have the following code below: mesh = open("file.mesh", "r").read() mesh = mesh.replace("[", "{").replace("]", "}").replace("}{", "},{") mesh = "{"+mesh+"}" f = open("p2t.txt", "w") f.write(mesh) It returns: Traceback (most recent call last): File...

MySQL Query returning strange values


php,mysql
The query is supposed to do the following: Obtain the question and associated answers based on the identification number of the question. (In this case the identification number is called account_id. Order them so that each question (and it's appropriate answers) are lined up in order. The query: SELECT *...

How do I display my mysql table column headers in my php/html output?


php,html,mysql,table,data
2 Questions... Scenario: I would like to query my database table via a form and then display the results that occur(if there are results) and my current situation is that it does work but it clears the form completely and leaves my to an empty page with just the results...

Python: histogram/ binning data from 2 arrays.


python,histogram,large-files
I have two arrays of data: one is a radius values and the other is a corresponding intensity reading at that intensity: e.g. a small section of the data. First column is radius and the second is the intensities. 29.77036614 0.04464427 29.70281027 0.07771409 29.63523525 0.09424901 29.3639355 1.322793 29.29596385 2.321502 29.22783249...

Using counter on array for one value while keeping index of other values


python,collections
After reading the answers on this question How to count the frequency of the elements in a list? I was wondering how to count the frequency of something, and at the same time retreive some extra information, through something like an index. For example a = ['fruit','Item#001'] b = ['fruit','Item#002']...

How to change the IP address of Amazon EC2 instance using boto library


python,amazon-web-services,boto
How can I assign a new IP address (or Elastic IP) to an already existing AWS EC2 instance using boto library.

How does the class_weight parameter in scikit-learn work?


python,scikit-learn
I am having a lot of trouble understanding how the class_weight parameter in scikit-learn's Logistic Regression operates. The Situation I want to use logistic regression to do binary classification on a very unbalanced data set. The classes are labelled 0 (negative) and 1 (positive) and the observed data is in...

PHP: While loop not working after adjusting SELECT for SQL injection prevention


php,mysql,select,sql-injection,associative-array
I am trying to set up PHP queries for MySQL in a way to prevent SQL injection (standard website). I had a couple of INSERT queries where changing this worked well but on the following SELECT I keep getting an error since the update and it looks like the while...

Retrieve Values As Column


mysql,sql
I've the following table in my PHPMYADMIN The desired output is headline                              impressions              clicks Buy A new Iphone                 ...

Identify that a string could be a datetime object


python,regex,algorithm,python-2.7,datetime
If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

Php Mysql Query not working properly


php,mysql
I have a table name tblnetworkstatus and I have 11 columns Id issue_name affected_server affected_service issue_type priority duration status start_date end_date description I am getting id in affected_server and affected_service which I am storing in my DB, now I have three situations Either both affected_server and affected_service has been selected...

Ignore Group if LIMIT is not reached in MySQL


mysql
I am working on a rather tricky SQL for my level of knowledge. I have searched and searched for an answer but haven't came across anything. Hopefully someone can shed some light on this. How can you stop SQL from outputting group of rows if the limit set is not...

How to call MySQL view in Struts2 or Hibernate


java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

Strange Behavior: Floating Point Error after Appending to List


python,python-2.7,behavior
I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

Pandas Dataframe Complex Calculation


python,python-2.7,pandas,dataframes
I have the following dataframe,df: Year totalPubs ActualCitations 0 1994 71 191.002034 1 1995 77 2763.911781 2 1996 69 2022.374474 3 1997 78 3393.094951 I want to write code that would do the following: Citations of currentyear / Sum of totalPubs of the two previous years I want something to...

The event loop is already running


python,python-3.x,pyqt,pyqt4
I have the following 5 files: gui.py # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig)...

group indices of list in list of lists


python,list
I am looking for an elegant solution for the following problem. I have a list of ints and I want to create a list of lists where the indices with the same value are grouped together in the order of the occurrences of said list. [2, 0, 1, 1, 3,...

SQLAlchemy. 2 different relationships for 1 column


python,sqlalchemy
I have a simple many-to-many relationship with associated table: with following data: matches: users: users_mathces: ONE user can play MANY matches and ONE match can involve up to TWO users I want to realize proper relationships in both "Match" and "User" classes users_matches_table = Table('users_matches', Base.metadata, Column('match_id', Integer, ForeignKey('matches.id', onupdate="CASCADE",...

How do variables inside python modules work?


python,module,python-module
I am coming from a Java background with Static variables, and I am trying to create a list of commonly used strings in my python application. I understand there are no static variables in python so I have written a module as follows: import os APP_NAME = 'Window Logger' APP_DATA_FOLDER_PATH...

How do I read this list and parse it?


python,list
I'm using requests and the output I get from the sites API is a list, I've been stuck trying to parse it to get the data from it. I use r = requests.get(urlas, params=params) r.json() to get the data I want. Here is a snippet of the list [{'relation_type': None,...

concatenate field names in a mysql update with inner join


php,mysql
Concatenating two field names from different tables using INNER JOIN during UPDATE statement. I am trying to concatenate two field names in a mysql update statement. This is what I have so far, needless to say it isn't working, any suggestions would be much appreciated. UPDATE products INNER JOIN sub_categories...

MySQL substring match using regular expression; substring contain 'man' not 'woman'


mysql,regex
I have an issue while I fetch data from database using regular expression. While I search for 'man' in tags it returns tags contains 'woman' too; because its substring. SELECT '#hellowomanclothing' REGEXP '^(.)*[^wo]man(.)*$'; # returns 0 correct, it contains 'woman' SELECT '#helloowmanclothing' REGEXP '^(.)*[^wo]man(.)*$'; # returns 0 incorrect, it can...

trying to understand LSH through the sample python code


python,similarity,locality-sensitive-hash
the concise python code i study for is here Question A @ line 8 i do not really understand the syntax meaning for "res = res << 1" for the purpose of "get_signature" Question B @ line 49 (SOLVED BY myself through another Q&A) "xor = r1^r2" does not really...

How to remove structure with python from this case?
python,python-2.7
How to remove "table" from HTML using python? I had case like this: paragraph = ''' <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quidem molestiae consequuntur officiis corporis sint.<br /><br /> <table> <tr> <td> text title </td> <td> text title 2 </td> </tr> </table> <p> lorem ipsum</p> ''' how...

Notice: Array to string conversion in “path of php file” on line 64


php,mysql,arrays,oracle
PHP CODE -: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <?php $rows =0; $fp = fopen("leave1.csv","r"); if($fp){ while(!feof($fp)){ $content = fgets($fp); if($content) $rows++; } } fclose($fp); //echo $rows; $_SESSION['rows'] = $rows; ?>...

Calling function and passing arguments multiple times


python,function,loops
I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

Python recursive function not recursing


python,recursion
I'm trying to solve a puzzle, which is to reverse engineer this code, to get a list of possible passwords, and from those there should be one that 'stands out', and should work function checkPass(password) { var total = 0; var charlist = "abcdefghijklmnopqrstuvwxyz"; for (var i = 0; i...

Trying to rewrite mysql_* to pdo


php,mysql,pdo
First of all I should say that I started to learn PDO and trying to rewrite some old mine codes. Here is one that I found on tutorial for a jquery/ajax/pdo/mysql comment system which is working. This is the mysql_* part which I'm trying to rewrite -> file submit.php which...

Replace nodejs for python?


python,node.js,webserver
i'm working in a HTML5 multiplayer game, and i need a server to sync player's movement, chat, battles, etc. So I'm looking for ways to use python instead nodejs, because i have I have more familiarity with python. The server is simple: var express = require('express'); var app = express();...

Twilio Client Python not Working in IOS Browser


javascript,python,ios,flask,twilio
I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

Count function counting only last line of my list


python,python-2.7
Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string[0] == 'k': cnt.append('k') elif string[0] == 'R': cnt.append('R') print cnt.count('R') if I am giving...

Sum of two variables in RobotFramework


python,automated-tests,robotframework
I have two variables: ${calculatedTotalPrice} = 42,42 ${productPrice1} = 43,15 I executed ${calculatedTotalPrice} Evaluate ${calculatedTotalPrice}+${productPrice1} I got 42,85,15 How can I resolve it?...