code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
/// <summary>
/// Jeremy
/// </summary>
public partial class MarkForm : Form
{
/// <summary>
/// jhdkfsh
/// </summary>
public MarkForm()
{
InitializeComponent();
}
private void m_Button_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
#region Jeremy
/// <summary>
/// Hello
/// </summary>
/// <param name="sender">Jeremy</param>
/// <param name="e">Jeremy</param>
private void m_Button_Load_Click(object sender, EventArgs e)
{
DataTable dt = _GetData();
DataColumn Column = new DataColumn("STT");
dt.Columns.Add(Column);
if (dt.Rows.Count != 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["STT"] = (i + 1);
}
}
m_DataGridView_MarkView.DataSource = dt;
double TongDiem = _GetTongDiem(dt);
int TongChi = _GetTongChi(dt);
m_TextBox_TinChi.Text = TongChi.ToString();
m_TextBox_Total.Text = (TongDiem / TongChi).ToString();
}
#endregion
private double _GetTongDiem(DataTable dt)
{
double TongDiem = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
TongDiem += Convert.ToDouble(dt.Rows[i]["Diem"]) * Convert.ToDouble(dt.Rows[i]["SoChi"]);
}
return TongDiem;
}
/// <summary>
/// Lấy tổng chỉ
/// </summary>
/// <param name="dt"> Bảng dữ liệu</param>
/// <returns>Số chỉ</returns>
private int _GetTongChi(DataTable dt)
{
int TongChi = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
TongChi += Convert.ToInt32(dt.Rows[i]["SoChi"]);
}
return TongChi;
}
private DataTable _GetData()
{
DataTable dt = null;
string QueryString = _GetQueryString();
dt = _GetData(QueryString);
return dt;
}
private string _GetQueryString()
{
string QueryString = "";
QueryString = "SELECT * FROM DanhSach";
return QueryString;
}
/// <summary>
/// Jeremy
/// </summary>
/// <param name="QueryString">Jeremy</param>
/// <returns>Jeremy</returns>
private DataTable _GetData(string QueryString)
{
DataTable dt = new DataTable();
SqlConnection Connection = new SqlConnection();
Connection.ConnectionString = _GetConnectionString();
Connection.Open();
SqlCommand CMD = new SqlCommand();
CMD.Connection = Connection;
CMD.CommandText = QueryString;
SqlDataAdapter ADP = new SqlDataAdapter(CMD);
ADP.Fill(dt);
Connection.Close();
return dt;
}
/// <summary>
/// addsad
/// </summary>
/// <returns>Good</returns>
public string _GetConnectionString()
{
string ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=BangDiem;Integrated Security=True";
return ConnectionString;
}
private void m_DataGridView_MarkView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
//if (UserAddRow == false)
//{
// return;
//}
//DataTable dt = (DataTable)m_DataGridView_MarkView.DataSource;
//DataGridView q = new DataGridView();
//if (dt.Rows.Count == 0)
//{
// dt.Rows[0]["STT"] = 1;
//}
//else
//{
// dt.Rows[e.RowIndex - 1]["STT"] = dt.Rows.Count;
//}
//UserAddRow = false;
}
private void m_DataGridView_MarkView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
}
private void m_DataGridView_MarkView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
DataTable dt = (DataTable)m_DataGridView_MarkView.DataSource;
DataGridViewRow Row = m_DataGridView_MarkView.CurrentRow;
DataRow DataRow = dt.NewRow();
Row.Cells["m_Column_NO"].Value = e.Row.Index;
}
private void m_DataGridView_MarkView_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
{
}
private void m_DataGridView_MarkView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
int Index = e.Row.Index;
DataTable dt = (DataTable)m_DataGridView_MarkView.DataSource;
for (int i = Index; i < dt.Rows.Count; i++)
{
dt.Rows[i]["STT"] = i;
}
}
private void m_Button_Update_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)m_DataGridView_MarkView.DataSource;
if (dt.Rows.Count == 0)
{
return;
}
SqlConnection Connection = new SqlConnection();
Connection.ConnectionString = _GetConnectionString();
Connection.Open();
SqlCommand CMD = new SqlCommand();
CMD.Connection = Connection;
string TEMP = "";
try
{
TEMP = _GetUpdateString(dt);
}
catch (Exception ERROR)
{
return;
}
CMD.CommandText = "Delete DanhSach";
CMD.ExecuteNonQuery();
CMD.CommandText = TEMP;
CMD.ExecuteNonQuery();
Connection.Close();
MessageBox.Show("OKE");
m_Button_Load_Click(sender, e);
}
private string _GetUpdateString(DataTable dt)
{
string UpdateString = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
UpdateString += _GetUpdateString(dt.Rows[i]) + "\n\r";
}
return UpdateString;
}
private string _GetUpdateString(DataRow row)
{
string UpdateString = "INSERT INTO DanhSach VALUES(" + "N'" + row["TenMonHoc"] + "'," + row["SoChi"] + "," + row["Diem"] + ")";
return UpdateString;
}
private void _Update(string UpdateString)
{
}
/// <summary>
/// Lấy tổng số chỉ
/// </summary>
/// <param name="sender">Người gửi</param>
/// <param name="e">Sự kiện</param>
/// <example>Jeremy Luu</example>
public void MarkForm_Load(object sender, EventArgs e)
{
DataTable dt = _GetData();
DataColumn Column = new DataColumn("STT");
dt.Columns.Add(Column);
if (dt.Rows.Count != 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["STT"] = (i + 1);
}
}
m_DataGridView_MarkView.DataSource = dt;
double TongDiem = _GetTongDiem(dt);
int TongChi = _GetTongChi(dt);
m_TextBox_TinChi.Text = TongChi.ToString();
m_TextBox_Total.Text = (TongDiem / TongChi).ToString();
}
private void expandableSplitter1_ExpandedChanged(object sender, DevComponents.DotNetBar.ExpandedChangeEventArgs e)
{
}
}
}
|
1012142-nmcnpm
|
trunk/WindowsFormsApplication1/WindowsFormsApplication1/MarkForm.cs
|
C#
|
asf20
| 8,166
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MarkForm());
}
}
}
|
1012142-nmcnpm
|
trunk/WindowsFormsApplication1/WindowsFormsApplication1/Program.cs
|
C#
|
asf20
| 499
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="author" content="Xuân Bình ">
<link rel="shortcut icon" href="images/icon-logo.png" />
<title>11it3</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/main.css" rel="stylesheet">
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<!-- Navigation -->
<nav class="navbar navbar-custom navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<span class="sr-only">Toggle navigation</span>
<i class="icon-bar"></i>
<i class="icon-bar"></i>
<i class="icon-bar"></i>
</button>
<a class="navbar-brand page-scroll" href="#page-top">
<i class="fa fa-play-circle"></i> <span class="light">11it3</span>.tk
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-right navbar-main-collapse menu-top">
<ul class="nav navbar-nav">
<!-- Hidden li included to remove active class from about link when scrolled up past about section -->
<li class="active">
<a class="page-scroll" href=""> <i class="glyphicon glyphicon-home"></i> Trang chủ</a>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown"><i class="glyphicon glyphicon-book"></i> Danh Mục<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="">Thông báo</a></li>
<li><a href="">Tin từ khoa</a></li>
<li><a href="">Học tập</a></li>
<li class="divider"></li>
<li><a href="">Hài</a></li>
</ul>
</li>
<li>
<a class="page-scroll" href=""><i class="glyphicon glyphicon-bookmark"></i> Giới thiệu</a>
</li>
<li>
<a class="page-scroll" href=""> <i class=" glyphicon glyphicon-envelope"></i> Liên hệ</a>
</li>
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown"><i class="glyphicon glyphicon-book"></i> Danh Mục<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="">Thông báo</a></li>
<li><a href="">Tin từ khoa</a></li>
<li><a href="">Học tập</a></li>
<li class="divider"></li>
<li><a href="">Hài</a></li>
</ul>
</li>
<li>
<a class="page-scroll" href=""><i class="glyphicon glyphicon-bookmark"></i> Giới thiệu</a>
</li>
<li>
<a class="page-scroll" href=""> <i class=" glyphicon glyphicon-envelope"></i> Liên hệ</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Intro Header -->
<div style="background: url('/templates/public/images/home-bg.jpg'); background-size: contain; padding-bottom: 3px;">
<header class="intro">
<div class="intro-body">
<div class="container">
<div class="row">
<div class="col-sm-4 col-sm-offset-2 intro-hl">
<p class="title-intro"> <i class="glyphicon glyphicon-leaf"></i> Mã Nguồn Mỡ 2014 <i class="glyphicon glyphicon-leaf"></i></p>
<p><i class="glyphicon glyphicon-pencil"></i> Nhóm thực hiện: <span>F4++</span></p>
<p><i class="glyphicon glyphicon-list-alt"></i> GVHD: <span>Ths. Đoàn Duy Bình</span></p>
</div>
<div class="col-sm-6 intro-hr">
<img src="images/img-logo.png" alt="Logo" class="img-responsive">
</div>
</div>
</div>
</div>
</header>
<!--Slider-->
<div class="slider" >
<div class="col-sm-8 col-sm-offset-2 clearfix">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active" style="text-align: center">
<img src="images/images.jpeg" alt="hoa đẹp 1" >
<div class="carousel-caption">
<h4>Hoa đẹp 1</h4>
</div>
</div>
<div class="item">
<img src="images/images2.jpeg" alt="hoa đẹp 2">
<div class="carousel-caption">
<h4>Hoa đẹp 2</h4>
</div>
</div>
<div class="item">
<img src="images/images3.jpeg" alt="hoa đẹp 3" >
<div class="carousel-caption">
<h4>Hoa đẹp 3</h4>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<!--Content-->
<session class="content">
<div class="container content-w">
<div class="row">
<div class="col-sm-3 hidden-sm hidden-xs">
<div class="body-left fl">
<div class="left-menu">
<ul class="list-unstyled">
<li class="parent"><a href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-tags"></i> Thông Báo</a></li>
<li class="parent"><a href="index.php?module=cat&action=indexCat&cid=2">
<i class="glyphicon glyphicon-tags"></i> Tin Từ Khoa</a></li>
<li class="parent"><a href="index.php?module=cat&action=indexCat&cid=3">
<i class="glyphicon glyphicon-tags"></i> Học Tập</a></li>
<li class="parent"><a href="index.php?module=cat&action=indexCat&cid=4">
<i class="glyphicon glyphicon-tags"></i> Hài VL</a></li>
</ul>
<div class="clr"></div>
</div>
<div class="support hidden-sm hidden-xs">
<h4 class="text-center">Hỗ trợ trực tuyến</h4>
<div class="skype">
<ul>
<li>
<a title="Chat with Mr.Bình" href="Skype:xuanbinhngyen.it?chat">Mr.Bình</a>
</li>
<li>
<a title="Chat with Mr.Khiết Bông" href="Skype:itsontran?chat">Mr.Khiết Bông</a>
</li>
</ul>
<div class="clr"></div>
</div>
<div class="orther">
<p><i class="glyphicon glyphicon-envelope"></i> Email: <span>xuanbinh.nguyen@outlook.com</span></p>
<p><i class="glyphicon glyphicon-phone"></i> Phone: <span>0165.691.4444</span></p>
</div>
</div>
<div class="advs hidden-sm hidden-xs">
<a title="" href="">
<img alt="" src="images/qc1.jpg">
</a>
<a title="" href="">
<img alt="" src="images/qc2.jpg">
</a>
</div>
</div>
</div>
<div class="col-sm-9">
<div class="body-right fr">
<div class="news-block">
<h2 class="title-cat">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-bookmark"></i> Thông Báo
</a>
</h2>
<div class="content-cat">
<div class="item-left col-sm-5">
<a title="Con trai chiến sĩ hy sinh vụ rơi máy bay Mi171 chào đời" href="index.php?module=news&action=detail&id=19">
<img class="img-responsive" alt="Thị trấn truyền thống Uchiko – Nhật Bản" src="images/images3.jpeg">
</a>
<h4>
<a class="title" title="Thị trấn truyền thống Uchiko – Nhật Bản" href="index.php?module=news&action=detail&id=19">Con trai chiến sĩ hy sinh vụ rơi máy bay Mi171 chào đời
</a>
</h4>
<p>Đặt tên con là Nguyễn Quang Huy với ý nghĩa ngày mai tươi sáng, chị Lan mong những điều tốt đẹp nhất gắn với người chồng đã khuất sẽ ở mãi với hai mẹ con</p>
</div>
<div class="item-right col-sm-7">
<ul class="list-unstyled">
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="news-block">
<h2 class="title-cat">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-bookmark"></i> Thông Báo
</a>
</h2>
<div class="content-cat">
<div class="item-left col-sm-5">
<a title="Con trai chiến sĩ hy sinh vụ rơi máy bay Mi171 chào đời" href="index.php?module=news&action=detail&id=19">
<img class="img-responsive" alt="Thị trấn truyền thống Uchiko – Nhật Bản" src="images/images3.jpeg">
</a>
<h4>
<a class="title" title="Thị trấn truyền thống Uchiko – Nhật Bản" href="index.php?module=news&action=detail&id=19">Con trai chiến sĩ hy sinh vụ rơi máy bay Mi171 chào đời
</a>
</h4>
<p>Đặt tên con là Nguyễn Quang Huy với ý nghĩa ngày mai tươi sáng, chị Lan mong những điều tốt đẹp nhất gắn với người chồng đã khuất sẽ ở mãi với hai mẹ con</p>
</div>
<div class="item-right col-sm-7">
<ul class="list-unstyled">
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="news-block">
<h2 class="title-cat">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-bookmark"></i> Thông Báo
</a>
</h2>
<div class="content-cat">
<div class="item-left col-sm-5">
<a title="Con trai chiến sĩ hy sinh vụ rơi máy bay Mi171 chào đời" href="index.php?module=news&action=detail&id=19">
<img class="img-responsive" alt="Thị trấn truyền thống Uchiko – Nhật Bản" src="images/images3.jpeg">
</a>
<h4>
<a class="title" title="Thị trấn truyền thống Uchiko – Nhật Bản" href="index.php?module=news&action=detail&id=19">Con trai chiến sĩ hy sinh vụ rơi máy bay Mi171 chào đời
</a>
</h4>
<p>Đặt tên con là Nguyễn Quang Huy với ý nghĩa ngày mai tươi sáng, chị Lan mong những điều tốt đẹp nhất gắn với người chồng đã khuất sẽ ở mãi với hai mẹ con</p>
</div>
<div class="item-right col-sm-7">
<ul class="list-unstyled">
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
<li>
<h4>
<a class="title" title="MH370 có thể đã đi xuống phía nam sớm hơn" href="index.php?module=news&action=detail&id=18">
MH370 có thể đã đi xuống phía nam sớm hơn
</a>
</h4>
<p class="cat-date">
<a title="Thông Báo" href="index.php?module=cat&action=indexCat&cid=1">
<i class="glyphicon glyphicon-send"></i> Thông Báo
</a>
<span> <i class="glyphicon glyphicon-time"></i> Cập nhật: 2014-09-13</span>
</p>
<p class="preview">Giới chức Australia hôm qua thông báo kết quả phân tích dữ liệu vệ tinh cho thấy chuyến bay MH370 có thể đã đi xuống phía nam sớm hơn so với suy đoán trước đó, đồng thời cảnh báo cuộc tìm kiếm máy bay mất tích sẽ kéo dài một năm.</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</session>
<!-- Footer -->
<footer>
<div class="container footer">
<p class="pull-left text-center">Copyright © Xuân Bình 2014</p>
<a href="#page-top" alt="" class="pull-right">
<i class="glyphicon glyphicon-arrow-up"></i>
</a>
</div>
</footer>
<!-- jQuery Version 1.11.0 -->
<script src="js/jquery-1.11.0.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
|
11it3
|
index.html
|
HTML
|
mpl11
| 28,727
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package prbd;
/**
*
* @author DANIEL
*/
public class PrBD {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
|
070729bd22012
|
trunk/prBD/src/prbd/PrBD.java
|
Java
|
gpl2
| 324
|
import java.util.Arrays;
import java.util.Collections;
/**
* Created by mauricio on 9/17/14.
*/
public class Triangle {
private int length;
public String symbol = "*";
public Triangle(int length) {
this.length = length;
}
public String getOne() {
return symbol;
}
public String getHorizontalLine() {
return this.getHorizontalLine(this.length);
}
public String getHorizontalLine(int length) {
StringBuilder asterisks = new StringBuilder();
for(int i = 0; i < length; i++) asterisks.append(getOne());
return String.valueOf(asterisks);
}
public String getVerticalLine(int length) {
StringBuilder asterisks = null;
for(int i = 0; i < length; i++) asterisks.append(getOne() + "\n");
return String.valueOf(asterisks).replaceFirst("\\s+$", "");
}
public String getRightTriangle(int length) {
StringBuilder asterisks = new StringBuilder();
for(int i = 1; i <= length; i++) asterisks.append(this.getHorizontalLine(i) + "\n");
return String.valueOf(asterisks).replaceFirst("\\s+$", "");
}
public String getRightTriangle() {
return this.getRightTriangle(this.length);
}
public String getIsosceles() {
StringBuilder asterisks = new StringBuilder();
for(int i = 1; i <= length; i++) {
asterisks.append(this.with(" ").getHorizontalLine(length - i) + this.getHorizontalLine((i*2) -1) + "\n");
}
return String.valueOf(asterisks).replaceFirst("\\s+$", "");
}
public String getDiamond() {
StringBuilder asterisks = new StringBuilder();
asterisks.append(getIsosceles() + "\n" + reverse(getIsosceles(), 1) );
return String.valueOf(asterisks).replaceFirst("\\s+$", "");
}
public String getDiamondWithName( String name) {
String d = getDiamond();
return d.replace(getHorizontalLine((this.length * 2) -1), name);
}
public static String reverse(String triangle, int start) {
String[] reversed = triangle.split("\n");
StringBuilder asterisks = new StringBuilder();
for(int i = reversed.length -(1+start); i > -1 ; i--) {
asterisks.append(reversed[i] + "\n");
}
return String.valueOf(asterisks).replaceFirst("\\s+$", "");
}
public static void draw(String triangle) {
System.out.println(triangle);
}
public Triangle with(String symbol) {
Triangle t = new Triangle(length);
t.symbol = symbol;
return t;
}
public static void main(String[] args) throws CloneNotSupportedException {
Triangle triangle = new Triangle(3);
draw(triangle.getOne());
draw(triangle.getHorizontalLine());
draw(triangle.getRightTriangle());
//draw(reverse(triangle.getIsosceles()));
draw(triangle.getIsosceles());
draw(triangle.getDiamond());
draw(triangle.getDiamondWithName("Bill"));
}
}
|
101-intro-exercises
|
trunk/src/Triangle.java
|
Java
|
mit
| 3,014
|
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Created by mauricio on 9/18/14.
*/
public class PrimeFactors {
private static List list = new ArrayList();
private static void addFactor(int factor) {
if(!list.contains(factor)) {
list.add(factor);
}
}
public static List generate(int num) {
int quotient = 0;
for (int factor = 2; factor <= num ; factor++) {
if (num%factor == 0) {
addFactor(factor);
quotient = num / factor;
if(quotient != 1) {
return generate(quotient);
} else break;
}
}
return list;
}
public static void main(String[] args) {
System.out.println(PrimeFactors.generate(191));
}
}
|
101-intro-exercises
|
trunk/src/PrimeFactors.java
|
Java
|
mit
| 843
|
/**
* Created by mauricio on 9/18/14.
*/
public class FizzBuzz {
public static void fizzBuzz(int limit) {
String result;
for(int num = 1; num <= limit; num++) {
result = "";
if(num % 3 == 0) result += "Fizz";
else if(num % 5 == 0) result += "Buzz";
else if(result.isEmpty()) result = Integer.toString(num);
System.out.println(result);
}
}
public static void main(String[] args) {
fizzBuzz(100);
}
}
|
101-intro-exercises
|
trunk/src/FizzBuzz.java
|
Java
|
mit
| 535
|
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module twitter</title>
</head><body bgcolor="#f0f0f8">
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"> <br><big><big><strong>twitter</strong></big></big> (version 0.8)</font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="twitter.py">twitter.py</a></font></td></tr></table>
<p><tt>A library that provides a Python interface to the Twitter API</tt></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#aa55cc">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
<tr><td bgcolor="#aa55cc"><tt> </tt></td><td> </td>
<td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="StringIO.html">StringIO</a><br>
<a href="base64.html">base64</a><br>
<a href="calendar.html">calendar</a><br>
<a href="datetime.html">datetime</a><br>
<a href="gzip.html">gzip</a><br>
</td><td width="25%" valign=top><a href="httplib.html">httplib</a><br>
<a href="oauth2.html">oauth2</a><br>
<a href="os.html">os</a><br>
<a href="rfc822.html">rfc822</a><br>
<a href="json.html">json</a><br>
</td><td width="25%" valign=top><a href="sys.html">sys</a><br>
<a href="tempfile.html">tempfile</a><br>
<a href="textwrap.html">textwrap</a><br>
<a href="time.html">time</a><br>
<a href="urllib.html">urllib</a><br>
</td><td width="25%" valign=top><a href="urllib2.html">urllib2</a><br>
<a href="urlparse.html">urlparse</a><br>
</td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ee77aa">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
<tr><td bgcolor="#ee77aa"><tt> </tt></td><td> </td>
<td width="100%"><dl>
<dt><font face="helvetica, arial"><a href="__builtin__.html#object">__builtin__.object</a>
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="twitter.html#Api">Api</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#DirectMessage">DirectMessage</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Hashtag">Hashtag</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#List">List</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Status">Status</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Trend">Trend</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#Url">Url</a>
</font></dt><dt><font face="helvetica, arial"><a href="twitter.html#User">User</a>
</font></dt></dl>
</dd>
<dt><font face="helvetica, arial"><a href="exceptions.html#Exception">exceptions.Exception</a>(<a href="exceptions.html#BaseException">exceptions.BaseException</a>)
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="twitter.html#TwitterError">TwitterError</a>
</font></dt></dl>
</dd>
</dl>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="Api">class <strong>Api</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A python interface into the Twitter API<br>
<br>
By default, the <a href="#Api">Api</a> caches results for 1 minute.<br>
<br>
Example usage:<br>
<br>
To create an instance of the twitter.<a href="#Api">Api</a> class, with no authentication:<br>
<br>
>>> import twitter<br>
>>> api = twitter.<a href="#Api">Api</a>()<br>
<br>
To fetch the most recently posted public twitter status messages:<br>
<br>
>>> statuses = api.<a href="#Api-GetPublicTimeline">GetPublicTimeline</a>()<br>
>>> print [s.user.name for s in statuses]<br>
[u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #...<br>
<br>
To fetch a single user's public status messages, where "user" is either<br>
a Twitter "short name" or their user id.<br>
<br>
>>> statuses = api.<a href="#Api-GetUserTimeline">GetUserTimeline</a>(user)<br>
>>> print [s.text for s in statuses]<br>
<br>
To use authentication, instantiate the twitter.<a href="#Api">Api</a> class with a<br>
consumer key and secret; and the oAuth key and secret:<br>
<br>
>>> api = twitter.<a href="#Api">Api</a>(consumer_key='twitter consumer key',<br>
consumer_secret='twitter consumer secret',<br>
access_token_key='the_key_given',<br>
access_token_secret='the_key_secret')<br>
<br>
To fetch your friends (after being authenticated):<br>
<br>
>>> users = api.<a href="#Api-GetFriends">GetFriends</a>()<br>
>>> print [u.name for u in users]<br>
<br>
To post a twitter status message (after being authenticated):<br>
<br>
>>> status = api.<a href="#Api-PostUpdate">PostUpdate</a>('I love python-twitter!')<br>
>>> print status.text<br>
I love python-twitter!<br>
<br>
There are many other methods, including:<br>
<br>
>>> api.<a href="#Api-PostUpdates">PostUpdates</a>(status)<br>
>>> api.<a href="#Api-PostDirectMessage">PostDirectMessage</a>(user, text)<br>
>>> api.<a href="#Api-GetUser">GetUser</a>(user)<br>
>>> api.<a href="#Api-GetReplies">GetReplies</a>()<br>
>>> api.<a href="#Api-GetUserTimeline">GetUserTimeline</a>(user)<br>
>>> api.<a href="#Api-GetStatus">GetStatus</a>(id)<br>
>>> api.<a href="#Api-DestroyStatus">DestroyStatus</a>(id)<br>
>>> api.<a href="#Api-GetFriendsTimeline">GetFriendsTimeline</a>(user)<br>
>>> api.<a href="#Api-GetFriends">GetFriends</a>(user)<br>
>>> api.<a href="#Api-GetFollowers">GetFollowers</a>()<br>
>>> api.<a href="#Api-GetFeatured">GetFeatured</a>()<br>
>>> api.<a href="#Api-GetDirectMessages">GetDirectMessages</a>()<br>
>>> api.<a href="#Api-PostDirectMessage">PostDirectMessage</a>(user, text)<br>
>>> api.<a href="#Api-DestroyDirectMessage">DestroyDirectMessage</a>(id)<br>
>>> api.<a href="#Api-DestroyFriendship">DestroyFriendship</a>(user)<br>
>>> api.<a href="#Api-CreateFriendship">CreateFriendship</a>(user)<br>
>>> api.<a href="#Api-GetUserByEmail">GetUserByEmail</a>(email)<br>
>>> api.<a href="#Api-VerifyCredentials">VerifyCredentials</a>()<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="Api-ClearCredentials"><strong>ClearCredentials</strong></a>(self)</dt><dd><tt>Clear the any credentials for this instance</tt></dd></dl>
<dl><dt><a name="Api-CreateFavorite"><strong>CreateFavorite</strong></a>(self, status)</dt><dd><tt>Favorites the status specified in the status parameter as the authenticating user.<br>
Returns the favorite status when successful.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
The twitter.<a href="#Status">Status</a> instance to mark as a favorite.<br>
Returns:<br>
A twitter.<a href="#Status">Status</a> instance representing the newly-marked favorite.</tt></dd></dl>
<dl><dt><a name="Api-CreateFriendship"><strong>CreateFriendship</strong></a>(self, user)</dt><dd><tt>Befriends the user specified in the user parameter as the authenticating user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
The ID or screen name of the user to befriend.<br>
Returns:<br>
A twitter.<a href="#User">User</a> instance representing the befriended user.</tt></dd></dl>
<dl><dt><a name="Api-CreateList"><strong>CreateList</strong></a>(self, user, name, mode<font color="#909090">=None</font>, description<font color="#909090">=None</font>)</dt><dd><tt>Creates a new list with the give name<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user:<br>
Twitter name to create the list for<br>
name:<br>
New name for the list<br>
mode:<br>
'public' or 'private'.<br>
Defaults to 'public'. [Optional]<br>
description:<br>
Description of the list. [Optional]<br>
<br>
Returns:<br>
A twitter.<a href="#List">List</a> instance representing the new list</tt></dd></dl>
<dl><dt><a name="Api-CreateSubscription"><strong>CreateSubscription</strong></a>(self, owner, list)</dt><dd><tt>Creates a subscription to a list by the authenticated user<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
owner:<br>
<a href="#User">User</a> name or id of the owner of the list being subscribed to.<br>
list:<br>
The slug or list id to subscribe the user to<br>
<br>
Returns:<br>
A twitter.<a href="#List">List</a> instance representing the list subscribed to</tt></dd></dl>
<dl><dt><a name="Api-DestroyDirectMessage"><strong>DestroyDirectMessage</strong></a>(self, id)</dt><dd><tt>Destroys the direct message specified in the required ID parameter.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated, and the<br>
authenticating user must be the recipient of the specified direct<br>
message.<br>
<br>
Args:<br>
id: The id of the direct message to be destroyed<br>
<br>
Returns:<br>
A twitter.<a href="#DirectMessage">DirectMessage</a> instance representing the message destroyed</tt></dd></dl>
<dl><dt><a name="Api-DestroyFavorite"><strong>DestroyFavorite</strong></a>(self, status)</dt><dd><tt>Un-favorites the status specified in the ID parameter as the authenticating user.<br>
Returns the un-favorited status in the requested format when successful.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
The twitter.<a href="#Status">Status</a> to unmark as a favorite.<br>
Returns:<br>
A twitter.<a href="#Status">Status</a> instance representing the newly-unmarked favorite.</tt></dd></dl>
<dl><dt><a name="Api-DestroyFriendship"><strong>DestroyFriendship</strong></a>(self, user)</dt><dd><tt>Discontinues friendship with the user specified in the user parameter.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
The ID or screen name of the user with whom to discontinue friendship.<br>
Returns:<br>
A twitter.<a href="#User">User</a> instance representing the discontinued friend.</tt></dd></dl>
<dl><dt><a name="Api-DestroyList"><strong>DestroyList</strong></a>(self, user, id)</dt><dd><tt>Destroys the list from the given user<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user:<br>
The user to remove the list from.<br>
id:<br>
The slug or id of the list to remove.<br>
Returns:<br>
A twitter.<a href="#List">List</a> instance representing the removed list.</tt></dd></dl>
<dl><dt><a name="Api-DestroyStatus"><strong>DestroyStatus</strong></a>(self, id)</dt><dd><tt>Destroys the status specified by the required ID parameter.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated and the<br>
authenticating user must be the author of the specified status.<br>
<br>
Args:<br>
id:<br>
The numerical ID of the status you're trying to destroy.<br>
<br>
Returns:<br>
A twitter.<a href="#Status">Status</a> instance representing the destroyed status message</tt></dd></dl>
<dl><dt><a name="Api-DestroySubscription"><strong>DestroySubscription</strong></a>(self, owner, list)</dt><dd><tt>Destroys the subscription to a list for the authenticated user<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
owner:<br>
The user id or screen name of the user that owns the<br>
list that is to be unsubscribed from<br>
list:<br>
The slug or list id of the list to unsubscribe from<br>
<br>
Returns:<br>
A twitter.<a href="#List">List</a> instance representing the removed list.</tt></dd></dl>
<dl><dt><a name="Api-FilterPublicTimeline"><strong>FilterPublicTimeline</strong></a>(self, term, since_id<font color="#909090">=None</font>)</dt><dd><tt>Filter the public twitter timeline by a given search term on<br>
the local machine.<br>
<br>
Args:<br>
term:<br>
term to search by.<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#Status">Status</a> instances, one for each message<br>
containing the term</tt></dd></dl>
<dl><dt><a name="Api-GetDirectMessages"><strong>GetDirectMessages</strong></a>(self, since<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Returns a list of the direct messages sent to the authenticating user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
since:<br>
Narrows the returned results to just those statuses created<br>
after the specified HTTP-formatted date. [Optional]<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#DirectMessage">DirectMessage</a> instances</tt></dd></dl>
<dl><dt><a name="Api-GetFavorites"><strong>GetFavorites</strong></a>(self, user<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Return a list of <a href="#Status">Status</a> objects representing favorited tweets.<br>
By default, returns the (up to) 20 most recent tweets for the<br>
authenticated user.<br>
<br>
Args:<br>
user:<br>
The twitter name or id of the user whose favorites you are fetching.<br>
If not specified, defaults to the authenticated user. [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]</tt></dd></dl>
<dl><dt><a name="Api-GetFeatured"><strong>GetFeatured</strong></a>(self)</dt><dd><tt>Fetch the sequence of twitter.<a href="#User">User</a> instances featured on twitter.com<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#User">User</a> instances</tt></dd></dl>
<dl><dt><a name="Api-GetFollowerIDs"><strong>GetFollowerIDs</strong></a>(self, userid<font color="#909090">=None</font>, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch the sequence of twitter.<a href="#User">User</a> instances, one for each follower<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#User">User</a> instances, one for each follower</tt></dd></dl>
<dl><dt><a name="Api-GetFollowers"><strong>GetFollowers</strong></a>(self, page<font color="#909090">=None</font>)</dt><dd><tt>Fetch the sequence of twitter.<a href="#User">User</a> instances, one for each follower<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#User">User</a> instances, one for each follower</tt></dd></dl>
<dl><dt><a name="Api-GetFriendIDs"><strong>GetFriendIDs</strong></a>(self, user<font color="#909090">=None</font>, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Returns a list of twitter user id's for every person<br>
the specified user is following.<br>
<br>
Args:<br>
user:<br>
The id or screen_name of the user to retrieve the id list for<br>
[Optional]<br>
<br>
Returns:<br>
A list of integers, one for each user id.</tt></dd></dl>
<dl><dt><a name="Api-GetFriends"><strong>GetFriends</strong></a>(self, user<font color="#909090">=None</font>, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch the sequence of twitter.<a href="#User">User</a> instances, one for each friend.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user:<br>
The twitter name or id of the user whose friends you are fetching.<br>
If not specified, defaults to the authenticated user. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#User">User</a> instances, one for each friend</tt></dd></dl>
<dl><dt><a name="Api-GetFriendsTimeline"><strong>GetFriendsTimeline</strong></a>(self, user<font color="#909090">=None</font>, count<font color="#909090">=None</font>, page<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, retweets<font color="#909090">=None</font>, include_entities<font color="#909090">=None</font>)</dt><dd><tt>Fetch the sequence of twitter.<a href="#Status">Status</a> messages for a user's friends<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated if the user is private.<br>
<br>
Args:<br>
user:<br>
Specifies the ID or screen name of the user for whom to return<br>
the friends_timeline. If not specified then the authenticated<br>
user set in the twitter.<a href="#Api">Api</a> instance will be used. [Optional]<br>
count:<br>
Specifies the number of statuses to retrieve. May not be<br>
greater than 100. [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
retweets:<br>
If True, the timeline will contain native retweets. [Optional]<br>
include_entities:<br>
If True, each tweet will include a node called "entities,".<br>
This node offers a variety of metadata about the tweet in a<br>
discreet structure, including: user_mentions, urls, and<br>
hashtags. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#Status">Status</a> instances, one for each message</tt></dd></dl>
<dl><dt><a name="Api-GetLists"><strong>GetLists</strong></a>(self, user, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch the sequence of lists for a user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user:<br>
The twitter name or id of the user whose friends you are fetching.<br>
If the passed in user is the same as the authenticated user<br>
then you will also receive private list data.<br>
cursor:<br>
"page" value that Twitter will use to start building the<br>
list sequence from. -1 to start at the beginning.<br>
Twitter will return in the result the values for next_cursor<br>
and previous_cursor. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#List">List</a> instances, one for each list</tt></dd></dl>
<dl><dt><a name="Api-GetMentions"><strong>GetMentions</strong></a>(self, since_id<font color="#909090">=None</font>, max_id<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Returns the 20 most recent mentions (status containing @twitterID)<br>
for the authenticating user.<br>
<br>
Args:<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
max_id:<br>
Returns only statuses with an ID less than<br>
(that is, older than) the specified ID. [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#Status">Status</a> instances, one for each mention of the user.</tt></dd></dl>
<dl><dt><a name="Api-GetPublicTimeline"><strong>GetPublicTimeline</strong></a>(self, since_id<font color="#909090">=None</font>, include_rts<font color="#909090">=None</font>, include_entities<font color="#909090">=None</font>)</dt><dd><tt>Fetch the sequence of public twitter.<a href="#Status">Status</a> message for all users.<br>
<br>
Args:<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
include_rts:<br>
If True, the timeline will contain native retweets (if they<br>
exist) in addition to the standard stream of tweets. [Optional]<br>
include_entities:<br>
If True, each tweet will include a node called "entities,".<br>
This node offers a variety of metadata about the tweet in a<br>
discreet structure, including: user_mentions, urls, and<br>
hashtags. [Optional]<br>
<br>
Returns:<br>
An sequence of twitter.<a href="#Status">Status</a> instances, one for each message</tt></dd></dl>
<dl><dt><a name="Api-GetRateLimitStatus"><strong>GetRateLimitStatus</strong></a>(self)</dt><dd><tt>Fetch the rate limit status for the currently authorized user.<br>
<br>
Returns:<br>
A dictionary containing the time the limit will reset (reset_time),<br>
the number of remaining hits allowed before the reset (remaining_hits),<br>
the number of hits allowed in a 60-minute period (hourly_limit), and<br>
the time of the reset in seconds since The Epoch (reset_time_in_seconds).</tt></dd></dl>
<dl><dt><a name="Api-GetReplies"><strong>GetReplies</strong></a>(self, since<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, page<font color="#909090">=None</font>)</dt><dd><tt>Get a sequence of status messages representing the 20 most<br>
recent replies (status updates prefixed with @twitterID) to the<br>
authenticating user.<br>
<br>
Args:<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
since:<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#Status">Status</a> instances, one for each reply to the user.</tt></dd></dl>
<dl><dt><a name="Api-GetRetweets"><strong>GetRetweets</strong></a>(self, statusid)</dt><dd><tt>Returns up to 100 of the first retweets of the tweet identified<br>
by statusid<br>
<br>
Args:<br>
statusid:<br>
The ID of the tweet for which retweets should be searched for<br>
<br>
Returns:<br>
A list of twitter.<a href="#Status">Status</a> instances, which are retweets of statusid</tt></dd></dl>
<dl><dt><a name="Api-GetSearch"><strong>GetSearch</strong></a>(self, term, geocode<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, per_page<font color="#909090">=15</font>, page<font color="#909090">=1</font>, lang<font color="#909090">='en'</font>, show_user<font color="#909090">='true'</font>, query_users<font color="#909090">=False</font>)</dt><dd><tt>Return twitter search results for a given term.<br>
<br>
Args:<br>
term:<br>
term to search by.<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
geocode:<br>
geolocation information in the form (latitude, longitude, radius)<br>
[Optional]<br>
per_page:<br>
number of results to return. Default is 15 [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
lang:<br>
language for results. Default is English [Optional]<br>
show_user:<br>
prefixes screen name in status<br>
query_users:<br>
If set to False, then all users only have screen_name and<br>
profile_image_url available.<br>
If set to True, all information of users are available,<br>
but it uses lots of request quota, one per status.<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#Status">Status</a> instances, one for each message containing<br>
the term</tt></dd></dl>
<dl><dt><a name="Api-GetStatus"><strong>GetStatus</strong></a>(self, id)</dt><dd><tt>Returns a single status message.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated if the<br>
status message is private.<br>
<br>
Args:<br>
id:<br>
The numeric ID of the status you are trying to retrieve.<br>
<br>
Returns:<br>
A twitter.<a href="#Status">Status</a> instance representing that status message</tt></dd></dl>
<dl><dt><a name="Api-GetSubscriptions"><strong>GetSubscriptions</strong></a>(self, user, cursor<font color="#909090">=-1</font>)</dt><dd><tt>Fetch the sequence of Lists that the given user is subscribed to<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user:<br>
The twitter name or id of the user<br>
cursor:<br>
"page" value that Twitter will use to start building the<br>
list sequence from. -1 to start at the beginning.<br>
Twitter will return in the result the values for next_cursor<br>
and previous_cursor. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#List">List</a> instances, one for each list</tt></dd></dl>
<dl><dt><a name="Api-GetTrendsCurrent"><strong>GetTrendsCurrent</strong></a>(self, exclude<font color="#909090">=None</font>)</dt><dd><tt>Get the current top trending topics<br>
<br>
Args:<br>
exclude:<br>
Appends the exclude parameter as a request parameter.<br>
Currently only exclude=hashtags is supported. [Optional]<br>
<br>
Returns:<br>
A list with 10 entries. Each entry contains the twitter.</tt></dd></dl>
<dl><dt><a name="Api-GetTrendsDaily"><strong>GetTrendsDaily</strong></a>(self, exclude<font color="#909090">=None</font>, startdate<font color="#909090">=None</font>)</dt><dd><tt>Get the current top trending topics for each hour in a given day<br>
<br>
Args:<br>
startdate:<br>
The start date for the report.<br>
Should be in the format YYYY-MM-DD. [Optional]<br>
exclude:<br>
Appends the exclude parameter as a request parameter.<br>
Currently only exclude=hashtags is supported. [Optional]<br>
<br>
Returns:<br>
A list with 24 entries. Each entry contains the twitter.<br>
<a href="#Trend">Trend</a> elements that were trending at the corresponding hour of the day.</tt></dd></dl>
<dl><dt><a name="Api-GetTrendsWeekly"><strong>GetTrendsWeekly</strong></a>(self, exclude<font color="#909090">=None</font>, startdate<font color="#909090">=None</font>)</dt><dd><tt>Get the top 30 trending topics for each day in a given week.<br>
<br>
Args:<br>
startdate:<br>
The start date for the report.<br>
Should be in the format YYYY-MM-DD. [Optional]<br>
exclude:<br>
Appends the exclude parameter as a request parameter.<br>
Currently only exclude=hashtags is supported. [Optional]<br>
Returns:<br>
A list with each entry contains the twitter.<br>
<a href="#Trend">Trend</a> elements of trending topics for the corrsponding day of the week</tt></dd></dl>
<dl><dt><a name="Api-GetUser"><strong>GetUser</strong></a>(self, user)</dt><dd><tt>Returns a single user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user: The twitter name or id of the user to retrieve.<br>
<br>
Returns:<br>
A twitter.<a href="#User">User</a> instance representing that user</tt></dd></dl>
<dl><dt><a name="Api-GetUserByEmail"><strong>GetUserByEmail</strong></a>(self, email)</dt><dd><tt>Returns a single user by email address.<br>
<br>
Args:<br>
email:<br>
The email of the user to retrieve.<br>
<br>
Returns:<br>
A twitter.<a href="#User">User</a> instance representing that user</tt></dd></dl>
<dl><dt><a name="Api-GetUserRetweets"><strong>GetUserRetweets</strong></a>(self, count<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, max_id<font color="#909090">=None</font>, include_entities<font color="#909090">=False</font>)</dt><dd><tt>Fetch the sequence of retweets made by a single user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
count:<br>
The number of status messages to retrieve. [Optional]<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
max_id:<br>
Returns results with an ID less than (that is, older than) or<br>
equal to the specified ID. [Optional]<br>
include_entities:<br>
If True, each tweet will include a node called "entities,".<br>
This node offers a variety of metadata about the tweet in a<br>
discreet structure, including: user_mentions, urls, and<br>
hashtags. [Optional]<br>
<br>
Returns:<br>
A sequence of twitter.<a href="#Status">Status</a> instances, one for each message up to count</tt></dd></dl>
<dl><dt><a name="Api-GetUserTimeline"><strong>GetUserTimeline</strong></a>(self, id<font color="#909090">=None</font>, user_id<font color="#909090">=None</font>, screen_name<font color="#909090">=None</font>, since_id<font color="#909090">=None</font>, max_id<font color="#909090">=None</font>, count<font color="#909090">=None</font>, page<font color="#909090">=None</font>, include_rts<font color="#909090">=None</font>, include_entities<font color="#909090">=None</font>)</dt><dd><tt>Fetch the sequence of public <a href="#Status">Status</a> messages for a single user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated if the user is private.<br>
<br>
Args:<br>
id:<br>
Specifies the ID or screen name of the user for whom to return<br>
the user_timeline. [Optional]<br>
user_id:<br>
Specfies the ID of the user for whom to return the<br>
user_timeline. Helpful for disambiguating when a valid user ID<br>
is also a valid screen name. [Optional]<br>
screen_name:<br>
Specfies the screen name of the user for whom to return the<br>
user_timeline. Helpful for disambiguating when a valid screen<br>
name is also a user ID. [Optional]<br>
since_id:<br>
Returns results with an ID greater than (that is, more recent<br>
than) the specified ID. There are limits to the number of<br>
Tweets which can be accessed through the API. If the limit of<br>
Tweets has occured since the since_id, the since_id will be<br>
forced to the oldest ID available. [Optional]<br>
max_id:<br>
Returns only statuses with an ID less than (that is, older<br>
than) or equal to the specified ID. [Optional]<br>
count:<br>
Specifies the number of statuses to retrieve. May not be<br>
greater than 200. [Optional]<br>
page:<br>
Specifies the page of results to retrieve.<br>
Note: there are pagination limits. [Optional]<br>
include_rts:<br>
If True, the timeline will contain native retweets (if they<br>
exist) in addition to the standard stream of tweets. [Optional]<br>
include_entities:<br>
If True, each tweet will include a node called "entities,".<br>
This node offers a variety of metadata about the tweet in a<br>
discreet structure, including: user_mentions, urls, and<br>
hashtags. [Optional]<br>
<br>
Returns:<br>
A sequence of <a href="#Status">Status</a> instances, one for each message up to count</tt></dd></dl>
<dl><dt><a name="Api-MaximumHitFrequency"><strong>MaximumHitFrequency</strong></a>(self)</dt><dd><tt>Determines the minimum number of seconds that a program must wait<br>
before hitting the server again without exceeding the rate_limit<br>
imposed for the currently authenticated user.<br>
<br>
Returns:<br>
The minimum second interval that a program must use so as to not<br>
exceed the rate_limit imposed for the user.</tt></dd></dl>
<dl><dt><a name="Api-PostDirectMessage"><strong>PostDirectMessage</strong></a>(self, user, text)</dt><dd><tt>Post a twitter direct message from the authenticated user<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user: The ID or screen name of the recipient user.<br>
text: The message text to be posted. Must be less than 140 characters.<br>
<br>
Returns:<br>
A twitter.<a href="#DirectMessage">DirectMessage</a> instance representing the message posted</tt></dd></dl>
<dl><dt><a name="Api-PostUpdate"><strong>PostUpdate</strong></a>(self, status, in_reply_to_status_id<font color="#909090">=None</font>)</dt><dd><tt>Post a twitter status message from the authenticated user.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
status:<br>
The message text to be posted.<br>
Must be less than or equal to 140 characters.<br>
in_reply_to_status_id:<br>
The ID of an existing status that the status to be posted is<br>
in reply to. This implicitly sets the in_reply_to_user_id<br>
attribute of the resulting status to the user ID of the<br>
message being replied to. Invalid/missing status IDs will be<br>
ignored. [Optional]<br>
Returns:<br>
A twitter.<a href="#Status">Status</a> instance representing the message posted.</tt></dd></dl>
<dl><dt><a name="Api-PostUpdates"><strong>PostUpdates</strong></a>(self, status, continuation<font color="#909090">=None</font>, **kwargs)</dt><dd><tt>Post one or more twitter status messages from the authenticated user.<br>
<br>
Unlike api.PostUpdate, this method will post multiple status updates<br>
if the message is longer than 140 characters.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
status:<br>
The message text to be posted.<br>
May be longer than 140 characters.<br>
continuation:<br>
The character string, if any, to be appended to all but the<br>
last message. Note that Twitter strips trailing '...' strings<br>
from messages. Consider using the unicode \u2026 character<br>
(horizontal ellipsis) instead. [Defaults to None]<br>
**kwargs:<br>
See api.PostUpdate for a list of accepted parameters.<br>
<br>
Returns:<br>
A of list twitter.<a href="#Status">Status</a> instance representing the messages posted.</tt></dd></dl>
<dl><dt><a name="Api-SetCache"><strong>SetCache</strong></a>(self, cache)</dt><dd><tt>Override the default cache. Set to None to prevent caching.<br>
<br>
Args:<br>
cache:<br>
An instance that supports the same API as the twitter._FileCache</tt></dd></dl>
<dl><dt><a name="Api-SetCacheTimeout"><strong>SetCacheTimeout</strong></a>(self, cache_timeout)</dt><dd><tt>Override the default cache timeout.<br>
<br>
Args:<br>
cache_timeout:<br>
Time, in seconds, that responses should be reused.</tt></dd></dl>
<dl><dt><a name="Api-SetCredentials"><strong>SetCredentials</strong></a>(self, consumer_key, consumer_secret, access_token_key<font color="#909090">=None</font>, access_token_secret<font color="#909090">=None</font>)</dt><dd><tt>Set the consumer_key and consumer_secret for this instance<br>
<br>
Args:<br>
consumer_key:<br>
The consumer_key of the twitter account.<br>
consumer_secret:<br>
The consumer_secret for the twitter account.<br>
access_token_key:<br>
The oAuth access token key value you retrieved<br>
from running get_access_token.py.<br>
access_token_secret:<br>
The oAuth access token's secret, also retrieved<br>
from the get_access_token.py run.</tt></dd></dl>
<dl><dt><a name="Api-SetSource"><strong>SetSource</strong></a>(self, source)</dt><dd><tt>Suggest the "from source" value to be displayed on the Twitter web site.<br>
<br>
The value of the 'source' parameter must be first recognized by<br>
the Twitter server. New source values are authorized on a case by<br>
case basis by the Twitter development team.<br>
<br>
Args:<br>
source:<br>
The source name as a string. Will be sent to the server as<br>
the 'source' parameter.</tt></dd></dl>
<dl><dt><a name="Api-SetUrllib"><strong>SetUrllib</strong></a>(self, urllib)</dt><dd><tt>Override the default urllib implementation.<br>
<br>
Args:<br>
urllib:<br>
An instance that supports the same API as the urllib2 module</tt></dd></dl>
<dl><dt><a name="Api-SetUserAgent"><strong>SetUserAgent</strong></a>(self, user_agent)</dt><dd><tt>Override the default user agent<br>
<br>
Args:<br>
user_agent:<br>
A string that should be send to the server as the <a href="#User">User</a>-agent</tt></dd></dl>
<dl><dt><a name="Api-SetXTwitterHeaders"><strong>SetXTwitterHeaders</strong></a>(self, client, url, version)</dt><dd><tt>Set the X-Twitter HTTP headers that will be sent to the server.<br>
<br>
Args:<br>
client:<br>
The client name as a string. Will be sent to the server as<br>
the 'X-Twitter-Client' header.<br>
url:<br>
The URL of the meta.xml as a string. Will be sent to the server<br>
as the 'X-Twitter-Client-URL' header.<br>
version:<br>
The client version as a string. Will be sent to the server<br>
as the 'X-Twitter-Client-Version' header.</tt></dd></dl>
<dl><dt><a name="Api-UsersLookup"><strong>UsersLookup</strong></a>(self, user_id<font color="#909090">=None</font>, screen_name<font color="#909090">=None</font>, users<font color="#909090">=None</font>)</dt><dd><tt>Fetch extended information for the specified users.<br>
<br>
Users may be specified either as lists of either user_ids,<br>
screen_names, or twitter.<a href="#User">User</a> objects. The list of users that<br>
are queried is the union of all specified parameters.<br>
<br>
The twitter.<a href="#Api">Api</a> instance must be authenticated.<br>
<br>
Args:<br>
user_id:<br>
A list of user_ids to retrieve extended information.<br>
[Optional]<br>
screen_name:<br>
A list of screen_names to retrieve extended information.<br>
[Optional]<br>
users:<br>
A list of twitter.<a href="#User">User</a> objects to retrieve extended information.<br>
[Optional]<br>
<br>
Returns:<br>
A list of twitter.<a href="#User">User</a> objects for the requested users</tt></dd></dl>
<dl><dt><a name="Api-VerifyCredentials"><strong>VerifyCredentials</strong></a>(self)</dt><dd><tt>Returns a twitter.<a href="#User">User</a> instance if the authenticating user is valid.<br>
<br>
Returns:<br>
A twitter.<a href="#User">User</a> instance representing that user if the<br>
credentials are valid, None otherwise.</tt></dd></dl>
<dl><dt><a name="Api-__init__"><strong>__init__</strong></a>(self, consumer_key<font color="#909090">=None</font>, consumer_secret<font color="#909090">=None</font>, access_token_key<font color="#909090">=None</font>, access_token_secret<font color="#909090">=None</font>, input_encoding<font color="#909090">=None</font>, request_headers<font color="#909090">=None</font>, cache<font color="#909090">=<object object at 0x1001da0a0></font>, shortner<font color="#909090">=None</font>, base_url<font color="#909090">=None</font>, use_gzip_compression<font color="#909090">=False</font>, debugHTTP<font color="#909090">=False</font>)</dt><dd><tt>Instantiate a new twitter.<a href="#Api">Api</a> <a href="__builtin__.html#object">object</a>.<br>
<br>
Args:<br>
consumer_key:<br>
Your Twitter user's consumer_key.<br>
consumer_secret:<br>
Your Twitter user's consumer_secret.<br>
access_token_key:<br>
The oAuth access token key value you retrieved<br>
from running get_access_token.py.<br>
access_token_secret:<br>
The oAuth access token's secret, also retrieved<br>
from the get_access_token.py run.<br>
input_encoding:<br>
The encoding used to encode input strings. [Optional]<br>
request_header:<br>
A dictionary of additional HTTP request headers. [Optional]<br>
cache:<br>
The cache instance to use. Defaults to DEFAULT_CACHE.<br>
Use None to disable caching. [Optional]<br>
shortner:<br>
The shortner instance to use. Defaults to None.<br>
See shorten_url.py for an example shortner. [Optional]<br>
base_url:<br>
The base URL to use to contact the Twitter API.<br>
Defaults to https://twitter.com. [Optional]<br>
use_gzip_compression:<br>
Set to True to tell enable gzip compression for any call<br>
made to Twitter. Defaults to False. [Optional]<br>
debugHTTP:<br>
Set to True to enable debug output from urllib2 when performing<br>
any HTTP requests. Defaults to False. [Optional]</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<hr>
Data and other attributes defined here:<br>
<dl><dt><strong>DEFAULT_CACHE_TIMEOUT</strong> = 60</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="DirectMessage">class <strong>DirectMessage</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class representing the <a href="#DirectMessage">DirectMessage</a> structure used by the twitter API.<br>
<br>
The <a href="#DirectMessage">DirectMessage</a> structure exposes the following properties:<br>
<br>
direct_message.id<br>
direct_message.created_at<br>
direct_message.created_at_in_seconds # read only<br>
direct_message.sender_id<br>
direct_message.sender_screen_name<br>
direct_message.recipient_id<br>
direct_message.recipient_screen_name<br>
direct_message.text<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="DirectMessage-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A dict representation of this twitter.<a href="#DirectMessage">DirectMessage</a> instance.<br>
<br>
The return value uses the same key names as the JSON representation.<br>
<br>
Return:<br>
A dict representing this twitter.<a href="#DirectMessage">DirectMessage</a> instance</tt></dd></dl>
<dl><dt><a name="DirectMessage-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A JSON string representation of this twitter.<a href="#DirectMessage">DirectMessage</a> instance.<br>
<br>
Returns:<br>
A JSON string representation of this twitter.<a href="#DirectMessage">DirectMessage</a> instance</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetCreatedAt"><strong>GetCreatedAt</strong></a>(self)</dt><dd><tt>Get the time this direct message was posted.<br>
<br>
Returns:<br>
The time this direct message was posted</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetCreatedAtInSeconds"><strong>GetCreatedAtInSeconds</strong></a>(self)</dt><dd><tt>Get the time this direct message was posted, in seconds since the epoch.<br>
<br>
Returns:<br>
The time this direct message was posted, in seconds since the epoch.</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get the unique id of this direct message.<br>
<br>
Returns:<br>
The unique id of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetRecipientId"><strong>GetRecipientId</strong></a>(self)</dt><dd><tt>Get the unique recipient id of this direct message.<br>
<br>
Returns:<br>
The unique recipient id of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetRecipientScreenName"><strong>GetRecipientScreenName</strong></a>(self)</dt><dd><tt>Get the unique recipient screen name of this direct message.<br>
<br>
Returns:<br>
The unique recipient screen name of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetSenderId"><strong>GetSenderId</strong></a>(self)</dt><dd><tt>Get the unique sender id of this direct message.<br>
<br>
Returns:<br>
The unique sender id of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetSenderScreenName"><strong>GetSenderScreenName</strong></a>(self)</dt><dd><tt>Get the unique sender screen name of this direct message.<br>
<br>
Returns:<br>
The unique sender screen name of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-GetText"><strong>GetText</strong></a>(self)</dt><dd><tt>Get the text of this direct message.<br>
<br>
Returns:<br>
The text of this direct message.</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetCreatedAt"><strong>SetCreatedAt</strong></a>(self, created_at)</dt><dd><tt>Set the time this direct message was posted.<br>
<br>
Args:<br>
created_at:<br>
The time this direct message was created</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set the unique id of this direct message.<br>
<br>
Args:<br>
id:<br>
The unique id of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetRecipientId"><strong>SetRecipientId</strong></a>(self, recipient_id)</dt><dd><tt>Set the unique recipient id of this direct message.<br>
<br>
Args:<br>
recipient_id:<br>
The unique recipient id of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetRecipientScreenName"><strong>SetRecipientScreenName</strong></a>(self, recipient_screen_name)</dt><dd><tt>Set the unique recipient screen name of this direct message.<br>
<br>
Args:<br>
recipient_screen_name:<br>
The unique recipient screen name of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetSenderId"><strong>SetSenderId</strong></a>(self, sender_id)</dt><dd><tt>Set the unique sender id of this direct message.<br>
<br>
Args:<br>
sender_id:<br>
The unique sender id of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetSenderScreenName"><strong>SetSenderScreenName</strong></a>(self, sender_screen_name)</dt><dd><tt>Set the unique sender screen name of this direct message.<br>
<br>
Args:<br>
sender_screen_name:<br>
The unique sender screen name of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-SetText"><strong>SetText</strong></a>(self, text)</dt><dd><tt>Set the text of this direct message.<br>
<br>
Args:<br>
text:<br>
The text of this direct message</tt></dd></dl>
<dl><dt><a name="DirectMessage-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="DirectMessage-__init__"><strong>__init__</strong></a>(self, id<font color="#909090">=None</font>, created_at<font color="#909090">=None</font>, sender_id<font color="#909090">=None</font>, sender_screen_name<font color="#909090">=None</font>, recipient_id<font color="#909090">=None</font>, recipient_screen_name<font color="#909090">=None</font>, text<font color="#909090">=None</font>)</dt><dd><tt>An <a href="__builtin__.html#object">object</a> to hold a Twitter direct message.<br>
<br>
This class is normally instantiated by the twitter.<a href="#Api">Api</a> class and<br>
returned in a sequence.<br>
<br>
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"<br>
<br>
Args:<br>
id:<br>
The unique id of this direct message. [Optional]<br>
created_at:<br>
The time this direct message was posted. [Optional]<br>
sender_id:<br>
The id of the twitter user that sent this message. [Optional]<br>
sender_screen_name:<br>
The name of the twitter user that sent this message. [Optional]<br>
recipient_id:<br>
The id of the twitter that received this message. [Optional]<br>
recipient_screen_name:<br>
The name of the twitter that received this message. [Optional]<br>
text:<br>
The text of this direct message. [Optional]</tt></dd></dl>
<dl><dt><a name="DirectMessage-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="DirectMessage-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A string representation of this twitter.<a href="#DirectMessage">DirectMessage</a> instance.<br>
<br>
The return value is the same as the JSON string representation.<br>
<br>
Returns:<br>
A string representation of this twitter.<a href="#DirectMessage">DirectMessage</a> instance.</tt></dd></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="DirectMessage-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create a new instance based on a JSON dict.<br>
<br>
Args:<br>
data:<br>
A JSON dict, as converted from the JSON in the twitter API<br>
<br>
Returns:<br>
A twitter.<a href="#DirectMessage">DirectMessage</a> instance</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<dl><dt><strong>created_at</strong></dt>
<dd><tt>The time this direct message was posted.</tt></dd>
</dl>
<dl><dt><strong>created_at_in_seconds</strong></dt>
<dd><tt>The time this direct message was posted, in seconds since the epoch</tt></dd>
</dl>
<dl><dt><strong>id</strong></dt>
<dd><tt>The unique id of this direct message.</tt></dd>
</dl>
<dl><dt><strong>recipient_id</strong></dt>
<dd><tt>The unique recipient id of this direct message.</tt></dd>
</dl>
<dl><dt><strong>recipient_screen_name</strong></dt>
<dd><tt>The unique recipient screen name of this direct message.</tt></dd>
</dl>
<dl><dt><strong>sender_id</strong></dt>
<dd><tt>The unique sender id of this direct message.</tt></dd>
</dl>
<dl><dt><strong>sender_screen_name</strong></dt>
<dd><tt>The unique sender screen name of this direct message.</tt></dd>
</dl>
<dl><dt><strong>text</strong></dt>
<dd><tt>The text of this direct message</tt></dd>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="Hashtag">class <strong>Hashtag</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class represeinting a twitter hashtag<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="Hashtag-__init__"><strong>__init__</strong></a>(self, text<font color="#909090">=None</font>)</dt></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="Hashtag-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create a new instance based on a JSON dict.<br>
<br>
Args:<br>
data:<br>
A JSON dict, as converted from the JSON in the twitter API<br>
<br>
Returns:<br>
A twitter.<a href="#Hashtag">Hashtag</a> instance</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="List">class <strong>List</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class representing the <a href="#List">List</a> structure used by the twitter API.<br>
<br>
The <a href="#List">List</a> structure exposes the following properties:<br>
<br>
list.id<br>
list.name<br>
list.slug<br>
list.description<br>
list.full_name<br>
list.mode<br>
list.uri<br>
list.member_count<br>
list.subscriber_count<br>
list.following<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="List-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A dict representation of this twitter.<a href="#List">List</a> instance.<br>
<br>
The return value uses the same key names as the JSON representation.<br>
<br>
Return:<br>
A dict representing this twitter.<a href="#List">List</a> instance</tt></dd></dl>
<dl><dt><a name="List-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A JSON string representation of this twitter.<a href="#List">List</a> instance.<br>
<br>
Returns:<br>
A JSON string representation of this twitter.<a href="#List">List</a> instance</tt></dd></dl>
<dl><dt><a name="List-GetDescription"><strong>GetDescription</strong></a>(self)</dt><dd><tt>Get the description of this list.<br>
<br>
Returns:<br>
The description of this list</tt></dd></dl>
<dl><dt><a name="List-GetFollowing"><strong>GetFollowing</strong></a>(self)</dt><dd><tt>Get the following status of this list.<br>
<br>
Returns:<br>
The following status of this list</tt></dd></dl>
<dl><dt><a name="List-GetFull_name"><strong>GetFull_name</strong></a>(self)</dt><dd><tt>Get the full_name of this list.<br>
<br>
Returns:<br>
The full_name of this list</tt></dd></dl>
<dl><dt><a name="List-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get the unique id of this list.<br>
<br>
Returns:<br>
The unique id of this list</tt></dd></dl>
<dl><dt><a name="List-GetMember_count"><strong>GetMember_count</strong></a>(self)</dt><dd><tt>Get the member_count of this list.<br>
<br>
Returns:<br>
The member_count of this list</tt></dd></dl>
<dl><dt><a name="List-GetMode"><strong>GetMode</strong></a>(self)</dt><dd><tt>Get the mode of this list.<br>
<br>
Returns:<br>
The mode of this list</tt></dd></dl>
<dl><dt><a name="List-GetName"><strong>GetName</strong></a>(self)</dt><dd><tt>Get the real name of this list.<br>
<br>
Returns:<br>
The real name of this list</tt></dd></dl>
<dl><dt><a name="List-GetSlug"><strong>GetSlug</strong></a>(self)</dt><dd><tt>Get the slug of this list.<br>
<br>
Returns:<br>
The slug of this list</tt></dd></dl>
<dl><dt><a name="List-GetSubscriber_count"><strong>GetSubscriber_count</strong></a>(self)</dt><dd><tt>Get the subscriber_count of this list.<br>
<br>
Returns:<br>
The subscriber_count of this list</tt></dd></dl>
<dl><dt><a name="List-GetUri"><strong>GetUri</strong></a>(self)</dt><dd><tt>Get the uri of this list.<br>
<br>
Returns:<br>
The uri of this list</tt></dd></dl>
<dl><dt><a name="List-GetUser"><strong>GetUser</strong></a>(self)</dt><dd><tt>Get the user of this list.<br>
<br>
Returns:<br>
The owner of this list</tt></dd></dl>
<dl><dt><a name="List-SetDescription"><strong>SetDescription</strong></a>(self, description)</dt><dd><tt>Set the description of this list.<br>
<br>
Args:<br>
description:<br>
The description of this list.</tt></dd></dl>
<dl><dt><a name="List-SetFollowing"><strong>SetFollowing</strong></a>(self, following)</dt><dd><tt>Set the following status of this list.<br>
<br>
Args:<br>
following:<br>
The following of this list.</tt></dd></dl>
<dl><dt><a name="List-SetFull_name"><strong>SetFull_name</strong></a>(self, full_name)</dt><dd><tt>Set the full_name of this list.<br>
<br>
Args:<br>
full_name:<br>
The full_name of this list.</tt></dd></dl>
<dl><dt><a name="List-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set the unique id of this list.<br>
<br>
Args:<br>
id:<br>
The unique id of this list.</tt></dd></dl>
<dl><dt><a name="List-SetMember_count"><strong>SetMember_count</strong></a>(self, member_count)</dt><dd><tt>Set the member_count of this list.<br>
<br>
Args:<br>
member_count:<br>
The member_count of this list.</tt></dd></dl>
<dl><dt><a name="List-SetMode"><strong>SetMode</strong></a>(self, mode)</dt><dd><tt>Set the mode of this list.<br>
<br>
Args:<br>
mode:<br>
The mode of this list.</tt></dd></dl>
<dl><dt><a name="List-SetName"><strong>SetName</strong></a>(self, name)</dt><dd><tt>Set the real name of this list.<br>
<br>
Args:<br>
name:<br>
The real name of this list</tt></dd></dl>
<dl><dt><a name="List-SetSlug"><strong>SetSlug</strong></a>(self, slug)</dt><dd><tt>Set the slug of this list.<br>
<br>
Args:<br>
slug:<br>
The slug of this list.</tt></dd></dl>
<dl><dt><a name="List-SetSubscriber_count"><strong>SetSubscriber_count</strong></a>(self, subscriber_count)</dt><dd><tt>Set the subscriber_count of this list.<br>
<br>
Args:<br>
subscriber_count:<br>
The subscriber_count of this list.</tt></dd></dl>
<dl><dt><a name="List-SetUri"><strong>SetUri</strong></a>(self, uri)</dt><dd><tt>Set the uri of this list.<br>
<br>
Args:<br>
uri:<br>
The uri of this list.</tt></dd></dl>
<dl><dt><a name="List-SetUser"><strong>SetUser</strong></a>(self, user)</dt><dd><tt>Set the user of this list.<br>
<br>
Args:<br>
user:<br>
The owner of this list.</tt></dd></dl>
<dl><dt><a name="List-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="List-__init__"><strong>__init__</strong></a>(self, id<font color="#909090">=None</font>, name<font color="#909090">=None</font>, slug<font color="#909090">=None</font>, description<font color="#909090">=None</font>, full_name<font color="#909090">=None</font>, mode<font color="#909090">=None</font>, uri<font color="#909090">=None</font>, member_count<font color="#909090">=None</font>, subscriber_count<font color="#909090">=None</font>, following<font color="#909090">=None</font>, user<font color="#909090">=None</font>)</dt></dl>
<dl><dt><a name="List-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="List-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A string representation of this twitter.<a href="#List">List</a> instance.<br>
<br>
The return value is the same as the JSON string representation.<br>
<br>
Returns:<br>
A string representation of this twitter.<a href="#List">List</a> instance.</tt></dd></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="List-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create a new instance based on a JSON dict.<br>
<br>
Args:<br>
data:<br>
A JSON dict, as converted from the JSON in the twitter API<br>
<br>
Returns:<br>
A twitter.<a href="#List">List</a> instance</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<dl><dt><strong>description</strong></dt>
<dd><tt>The description of this list.</tt></dd>
</dl>
<dl><dt><strong>following</strong></dt>
<dd><tt>The following status of this list.</tt></dd>
</dl>
<dl><dt><strong>full_name</strong></dt>
<dd><tt>The full_name of this list.</tt></dd>
</dl>
<dl><dt><strong>id</strong></dt>
<dd><tt>The unique id of this list.</tt></dd>
</dl>
<dl><dt><strong>member_count</strong></dt>
<dd><tt>The member_count of this list.</tt></dd>
</dl>
<dl><dt><strong>mode</strong></dt>
<dd><tt>The mode of this list.</tt></dd>
</dl>
<dl><dt><strong>name</strong></dt>
<dd><tt>The real name of this list.</tt></dd>
</dl>
<dl><dt><strong>slug</strong></dt>
<dd><tt>The slug of this list.</tt></dd>
</dl>
<dl><dt><strong>subscriber_count</strong></dt>
<dd><tt>The subscriber_count of this list.</tt></dd>
</dl>
<dl><dt><strong>uri</strong></dt>
<dd><tt>The uri of this list.</tt></dd>
</dl>
<dl><dt><strong>user</strong></dt>
<dd><tt>The owner of this list.</tt></dd>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="Status">class <strong>Status</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class representing the <a href="#Status">Status</a> structure used by the twitter API.<br>
<br>
The <a href="#Status">Status</a> structure exposes the following properties:<br>
<br>
status.created_at<br>
status.created_at_in_seconds # read only<br>
status.favorited<br>
status.in_reply_to_screen_name<br>
status.in_reply_to_user_id<br>
status.in_reply_to_status_id<br>
status.truncated<br>
status.source<br>
status.id<br>
status.text<br>
status.location<br>
status.relative_created_at # read only<br>
status.user<br>
status.urls<br>
status.user_mentions<br>
status.hashtags<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="Status-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A dict representation of this twitter.<a href="#Status">Status</a> instance.<br>
<br>
The return value uses the same key names as the JSON representation.<br>
<br>
Return:<br>
A dict representing this twitter.<a href="#Status">Status</a> instance</tt></dd></dl>
<dl><dt><a name="Status-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A JSON string representation of this twitter.<a href="#Status">Status</a> instance.<br>
<br>
Returns:<br>
A JSON string representation of this twitter.<a href="#Status">Status</a> instance</tt></dd></dl>
<dl><dt><a name="Status-GetCreatedAt"><strong>GetCreatedAt</strong></a>(self)</dt><dd><tt>Get the time this status message was posted.<br>
<br>
Returns:<br>
The time this status message was posted</tt></dd></dl>
<dl><dt><a name="Status-GetCreatedAtInSeconds"><strong>GetCreatedAtInSeconds</strong></a>(self)</dt><dd><tt>Get the time this status message was posted, in seconds since the epoch.<br>
<br>
Returns:<br>
The time this status message was posted, in seconds since the epoch.</tt></dd></dl>
<dl><dt><a name="Status-GetFavorited"><strong>GetFavorited</strong></a>(self)</dt><dd><tt>Get the favorited setting of this status message.<br>
<br>
Returns:<br>
True if this status message is favorited; False otherwise</tt></dd></dl>
<dl><dt><a name="Status-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get the unique id of this status message.<br>
<br>
Returns:<br>
The unique id of this status message</tt></dd></dl>
<dl><dt><a name="Status-GetInReplyToScreenName"><strong>GetInReplyToScreenName</strong></a>(self)</dt></dl>
<dl><dt><a name="Status-GetInReplyToStatusId"><strong>GetInReplyToStatusId</strong></a>(self)</dt></dl>
<dl><dt><a name="Status-GetInReplyToUserId"><strong>GetInReplyToUserId</strong></a>(self)</dt></dl>
<dl><dt><a name="Status-GetLocation"><strong>GetLocation</strong></a>(self)</dt><dd><tt>Get the geolocation associated with this status message<br>
<br>
Returns:<br>
The geolocation string of this status message.</tt></dd></dl>
<dl><dt><a name="Status-GetNow"><strong>GetNow</strong></a>(self)</dt><dd><tt>Get the wallclock time for this status message.<br>
<br>
Used to calculate relative_created_at. Defaults to the time<br>
the <a href="__builtin__.html#object">object</a> was instantiated.<br>
<br>
Returns:<br>
Whatever the status instance believes the current time to be,<br>
in seconds since the epoch.</tt></dd></dl>
<dl><dt><a name="Status-GetRelativeCreatedAt"><strong>GetRelativeCreatedAt</strong></a>(self)</dt><dd><tt>Get a human redable string representing the posting time<br>
<br>
Returns:<br>
A human readable string representing the posting time</tt></dd></dl>
<dl><dt><a name="Status-GetSource"><strong>GetSource</strong></a>(self)</dt></dl>
<dl><dt><a name="Status-GetText"><strong>GetText</strong></a>(self)</dt><dd><tt>Get the text of this status message.<br>
<br>
Returns:<br>
The text of this status message.</tt></dd></dl>
<dl><dt><a name="Status-GetTruncated"><strong>GetTruncated</strong></a>(self)</dt></dl>
<dl><dt><a name="Status-GetUser"><strong>GetUser</strong></a>(self)</dt><dd><tt>Get a twitter.<a href="#User">User</a> reprenting the entity posting this status message.<br>
<br>
Returns:<br>
A twitter.<a href="#User">User</a> reprenting the entity posting this status message</tt></dd></dl>
<dl><dt><a name="Status-SetCreatedAt"><strong>SetCreatedAt</strong></a>(self, created_at)</dt><dd><tt>Set the time this status message was posted.<br>
<br>
Args:<br>
created_at:<br>
The time this status message was created</tt></dd></dl>
<dl><dt><a name="Status-SetFavorited"><strong>SetFavorited</strong></a>(self, favorited)</dt><dd><tt>Set the favorited state of this status message.<br>
<br>
Args:<br>
favorited:<br>
boolean True/False favorited state of this status message</tt></dd></dl>
<dl><dt><a name="Status-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set the unique id of this status message.<br>
<br>
Args:<br>
id:<br>
The unique id of this status message</tt></dd></dl>
<dl><dt><a name="Status-SetInReplyToScreenName"><strong>SetInReplyToScreenName</strong></a>(self, in_reply_to_screen_name)</dt></dl>
<dl><dt><a name="Status-SetInReplyToStatusId"><strong>SetInReplyToStatusId</strong></a>(self, in_reply_to_status_id)</dt></dl>
<dl><dt><a name="Status-SetInReplyToUserId"><strong>SetInReplyToUserId</strong></a>(self, in_reply_to_user_id)</dt></dl>
<dl><dt><a name="Status-SetLocation"><strong>SetLocation</strong></a>(self, location)</dt><dd><tt>Set the geolocation associated with this status message<br>
<br>
Args:<br>
location:<br>
The geolocation string of this status message</tt></dd></dl>
<dl><dt><a name="Status-SetNow"><strong>SetNow</strong></a>(self, now)</dt><dd><tt>Set the wallclock time for this status message.<br>
<br>
Used to calculate relative_created_at. Defaults to the time<br>
the <a href="__builtin__.html#object">object</a> was instantiated.<br>
<br>
Args:<br>
now:<br>
The wallclock time for this instance.</tt></dd></dl>
<dl><dt><a name="Status-SetSource"><strong>SetSource</strong></a>(self, source)</dt></dl>
<dl><dt><a name="Status-SetText"><strong>SetText</strong></a>(self, text)</dt><dd><tt>Set the text of this status message.<br>
<br>
Args:<br>
text:<br>
The text of this status message</tt></dd></dl>
<dl><dt><a name="Status-SetTruncated"><strong>SetTruncated</strong></a>(self, truncated)</dt></dl>
<dl><dt><a name="Status-SetUser"><strong>SetUser</strong></a>(self, user)</dt><dd><tt>Set a twitter.<a href="#User">User</a> reprenting the entity posting this status message.<br>
<br>
Args:<br>
user:<br>
A twitter.<a href="#User">User</a> reprenting the entity posting this status message</tt></dd></dl>
<dl><dt><a name="Status-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="Status-__init__"><strong>__init__</strong></a>(self, created_at<font color="#909090">=None</font>, favorited<font color="#909090">=None</font>, id<font color="#909090">=None</font>, text<font color="#909090">=None</font>, location<font color="#909090">=None</font>, user<font color="#909090">=None</font>, in_reply_to_screen_name<font color="#909090">=None</font>, in_reply_to_user_id<font color="#909090">=None</font>, in_reply_to_status_id<font color="#909090">=None</font>, truncated<font color="#909090">=None</font>, source<font color="#909090">=None</font>, now<font color="#909090">=None</font>, urls<font color="#909090">=None</font>, user_mentions<font color="#909090">=None</font>, hashtags<font color="#909090">=None</font>)</dt><dd><tt>An <a href="__builtin__.html#object">object</a> to hold a Twitter status message.<br>
<br>
This class is normally instantiated by the twitter.<a href="#Api">Api</a> class and<br>
returned in a sequence.<br>
<br>
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"<br>
<br>
Args:<br>
created_at:<br>
The time this status message was posted. [Optiona]<br>
favorited:<br>
Whether this is a favorite of the authenticated user. [Optiona]<br>
id:<br>
The unique id of this status message. [Optiona]<br>
text:<br>
The text of this status message. [Optiona]<br>
location:<br>
the geolocation string associated with this message. [Optiona]<br>
relative_created_at:<br>
A human readable string representing the posting time. [Optiona]<br>
user:<br>
A twitter.<a href="#User">User</a> instance representing the person posting the<br>
message. [Optiona]<br>
now:<br>
The current time, if the client choses to set it.<br>
Defaults to the wall clock time. [Optiona]</tt></dd></dl>
<dl><dt><a name="Status-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="Status-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A string representation of this twitter.<a href="#Status">Status</a> instance.<br>
<br>
The return value is the same as the JSON string representation.<br>
<br>
Returns:<br>
A string representation of this twitter.<a href="#Status">Status</a> instance.</tt></dd></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="Status-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create a new instance based on a JSON dict.<br>
<br>
Args:<br>
data: A JSON dict, as converted from the JSON in the twitter API<br>
Returns:<br>
A twitter.<a href="#Status">Status</a> instance</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<dl><dt><strong>created_at</strong></dt>
<dd><tt>The time this status message was posted.</tt></dd>
</dl>
<dl><dt><strong>created_at_in_seconds</strong></dt>
<dd><tt>The time this status message was posted, in seconds since the epoch</tt></dd>
</dl>
<dl><dt><strong>favorited</strong></dt>
<dd><tt>The favorited state of this status message.</tt></dd>
</dl>
<dl><dt><strong>id</strong></dt>
<dd><tt>The unique id of this status message.</tt></dd>
</dl>
<dl><dt><strong>in_reply_to_screen_name</strong></dt>
<dd><tt></tt></dd>
</dl>
<dl><dt><strong>in_reply_to_status_id</strong></dt>
<dd><tt></tt></dd>
</dl>
<dl><dt><strong>in_reply_to_user_id</strong></dt>
<dd><tt></tt></dd>
</dl>
<dl><dt><strong>location</strong></dt>
<dd><tt>The geolocation string of this status message</tt></dd>
</dl>
<dl><dt><strong>now</strong></dt>
<dd><tt>The wallclock time for this status instance.</tt></dd>
</dl>
<dl><dt><strong>relative_created_at</strong></dt>
<dd><tt>Get a human readable string representing the posting time</tt></dd>
</dl>
<dl><dt><strong>source</strong></dt>
<dd><tt></tt></dd>
</dl>
<dl><dt><strong>text</strong></dt>
<dd><tt>The text of this status message</tt></dd>
</dl>
<dl><dt><strong>truncated</strong></dt>
<dd><tt></tt></dd>
</dl>
<dl><dt><strong>user</strong></dt>
<dd><tt>A twitter.User reprenting the entity posting this status message</tt></dd>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="Trend">class <strong>Trend</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class representing a trending topic<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="Trend-__init__"><strong>__init__</strong></a>(self, name<font color="#909090">=None</font>, query<font color="#909090">=None</font>, timestamp<font color="#909090">=None</font>)</dt></dl>
<dl><dt><a name="Trend-__str__"><strong>__str__</strong></a>(self)</dt></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="Trend-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data, timestamp<font color="#909090">=None</font>)</dt><dd><tt>Create a new instance based on a JSON dict<br>
<br>
Args:<br>
data:<br>
A JSON dict<br>
timestamp:<br>
Gets set as the timestamp property of the new <a href="__builtin__.html#object">object</a><br>
<br>
Returns:<br>
A twitter.<a href="#Trend">Trend</a> <a href="__builtin__.html#object">object</a></tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="TwitterError">class <strong>TwitterError</strong></a>(<a href="exceptions.html#Exception">exceptions.Exception</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>Base class for Twitter errors<br> </tt></td></tr>
<tr><td> </td>
<td width="100%"><dl><dt>Method resolution order:</dt>
<dd><a href="twitter.html#TwitterError">TwitterError</a></dd>
<dd><a href="exceptions.html#Exception">exceptions.Exception</a></dd>
<dd><a href="exceptions.html#BaseException">exceptions.BaseException</a></dd>
<dd><a href="__builtin__.html#object">__builtin__.object</a></dd>
</dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<dl><dt><strong>message</strong></dt>
<dd><tt>Returns the first argument used to construct this error.</tt></dd>
</dl>
<hr>
Methods inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
<dl><dt><a name="TwitterError-__init__"><strong>__init__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__init__">__init__</a>(...) initializes x; see x.__class__.__doc__ for signature</tt></dd></dl>
<hr>
Data and other attributes inherited from <a href="exceptions.html#Exception">exceptions.Exception</a>:<br>
<dl><dt><strong>__new__</strong> = <built-in method __new__ of type object at 0x100119f80><dd><tt>T.<a href="#TwitterError-__new__">__new__</a>(S, ...) -> a new <a href="__builtin__.html#object">object</a> with type S, a subtype of T</tt></dl>
<hr>
Methods inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
<dl><dt><a name="TwitterError-__delattr__"><strong>__delattr__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__delattr__">__delattr__</a>('name') <==> del x.name</tt></dd></dl>
<dl><dt><a name="TwitterError-__getattribute__"><strong>__getattribute__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__getattribute__">__getattribute__</a>('name') <==> x.name</tt></dd></dl>
<dl><dt><a name="TwitterError-__getitem__"><strong>__getitem__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__getitem__">__getitem__</a>(y) <==> x[y]</tt></dd></dl>
<dl><dt><a name="TwitterError-__getslice__"><strong>__getslice__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__getslice__">__getslice__</a>(i, j) <==> x[i:j]<br>
<br>
Use of negative indices is not supported.</tt></dd></dl>
<dl><dt><a name="TwitterError-__reduce__"><strong>__reduce__</strong></a>(...)</dt></dl>
<dl><dt><a name="TwitterError-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__repr__">__repr__</a>() <==> repr(x)</tt></dd></dl>
<dl><dt><a name="TwitterError-__setattr__"><strong>__setattr__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__setattr__">__setattr__</a>('name', value) <==> x.name = value</tt></dd></dl>
<dl><dt><a name="TwitterError-__setstate__"><strong>__setstate__</strong></a>(...)</dt></dl>
<dl><dt><a name="TwitterError-__str__"><strong>__str__</strong></a>(...)</dt><dd><tt>x.<a href="#TwitterError-__str__">__str__</a>() <==> str(x)</tt></dd></dl>
<dl><dt><a name="TwitterError-__unicode__"><strong>__unicode__</strong></a>(...)</dt></dl>
<hr>
Data descriptors inherited from <a href="exceptions.html#BaseException">exceptions.BaseException</a>:<br>
<dl><dt><strong>__dict__</strong></dt>
</dl>
<dl><dt><strong>args</strong></dt>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="Url">class <strong>Url</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class representing an URL contained in a tweet<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="Url-__init__"><strong>__init__</strong></a>(self, url<font color="#909090">=None</font>, expanded_url<font color="#909090">=None</font>)</dt></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="Url-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create a new instance based on a JSON dict.<br>
<br>
Args:<br>
data:<br>
A JSON dict, as converted from the JSON in the twitter API<br>
<br>
Returns:<br>
A twitter.<a href="#Url">Url</a> instance</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom> <br>
<font color="#000000" face="helvetica, arial"><a name="User">class <strong>User</strong></a>(<a href="__builtin__.html#object">__builtin__.object</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt> </tt></td>
<td colspan=2><tt>A class representing the <a href="#User">User</a> structure used by the twitter API.<br>
<br>
The <a href="#User">User</a> structure exposes the following properties:<br>
<br>
user.id<br>
user.name<br>
user.screen_name<br>
user.location<br>
user.description<br>
user.profile_image_url<br>
user.profile_background_tile<br>
user.profile_background_image_url<br>
user.profile_sidebar_fill_color<br>
user.profile_background_color<br>
user.profile_link_color<br>
user.profile_text_color<br>
user.protected<br>
user.utc_offset<br>
user.time_zone<br>
user.url<br>
user.status<br>
user.statuses_count<br>
user.followers_count<br>
user.friends_count<br>
user.favourites_count<br> </tt></td></tr>
<tr><td> </td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="User-AsDict"><strong>AsDict</strong></a>(self)</dt><dd><tt>A dict representation of this twitter.<a href="#User">User</a> instance.<br>
<br>
The return value uses the same key names as the JSON representation.<br>
<br>
Return:<br>
A dict representing this twitter.<a href="#User">User</a> instance</tt></dd></dl>
<dl><dt><a name="User-AsJsonString"><strong>AsJsonString</strong></a>(self)</dt><dd><tt>A JSON string representation of this twitter.<a href="#User">User</a> instance.<br>
<br>
Returns:<br>
A JSON string representation of this twitter.<a href="#User">User</a> instance</tt></dd></dl>
<dl><dt><a name="User-GetDescription"><strong>GetDescription</strong></a>(self)</dt><dd><tt>Get the short text description of this user.<br>
<br>
Returns:<br>
The short text description of this user</tt></dd></dl>
<dl><dt><a name="User-GetFavouritesCount"><strong>GetFavouritesCount</strong></a>(self)</dt><dd><tt>Get the number of favourites for this user.<br>
<br>
Returns:<br>
The number of favourites for this user.</tt></dd></dl>
<dl><dt><a name="User-GetFollowersCount"><strong>GetFollowersCount</strong></a>(self)</dt><dd><tt>Get the follower count for this user.<br>
<br>
Returns:<br>
The number of users following this user.</tt></dd></dl>
<dl><dt><a name="User-GetFriendsCount"><strong>GetFriendsCount</strong></a>(self)</dt><dd><tt>Get the friend count for this user.<br>
<br>
Returns:<br>
The number of users this user has befriended.</tt></dd></dl>
<dl><dt><a name="User-GetId"><strong>GetId</strong></a>(self)</dt><dd><tt>Get the unique id of this user.<br>
<br>
Returns:<br>
The unique id of this user</tt></dd></dl>
<dl><dt><a name="User-GetLocation"><strong>GetLocation</strong></a>(self)</dt><dd><tt>Get the geographic location of this user.<br>
<br>
Returns:<br>
The geographic location of this user</tt></dd></dl>
<dl><dt><a name="User-GetName"><strong>GetName</strong></a>(self)</dt><dd><tt>Get the real name of this user.<br>
<br>
Returns:<br>
The real name of this user</tt></dd></dl>
<dl><dt><a name="User-GetProfileBackgroundColor"><strong>GetProfileBackgroundColor</strong></a>(self)</dt></dl>
<dl><dt><a name="User-GetProfileBackgroundImageUrl"><strong>GetProfileBackgroundImageUrl</strong></a>(self)</dt></dl>
<dl><dt><a name="User-GetProfileBackgroundTile"><strong>GetProfileBackgroundTile</strong></a>(self)</dt><dd><tt>Boolean for whether to tile the profile background image.<br>
<br>
Returns:<br>
True if the background is to be tiled, False if not, None if unset.</tt></dd></dl>
<dl><dt><a name="User-GetProfileImageUrl"><strong>GetProfileImageUrl</strong></a>(self)</dt><dd><tt>Get the url of the thumbnail of this user.<br>
<br>
Returns:<br>
The url of the thumbnail of this user</tt></dd></dl>
<dl><dt><a name="User-GetProfileLinkColor"><strong>GetProfileLinkColor</strong></a>(self)</dt></dl>
<dl><dt><a name="User-GetProfileSidebarFillColor"><strong>GetProfileSidebarFillColor</strong></a>(self)</dt></dl>
<dl><dt><a name="User-GetProfileTextColor"><strong>GetProfileTextColor</strong></a>(self)</dt></dl>
<dl><dt><a name="User-GetProtected"><strong>GetProtected</strong></a>(self)</dt></dl>
<dl><dt><a name="User-GetScreenName"><strong>GetScreenName</strong></a>(self)</dt><dd><tt>Get the short twitter name of this user.<br>
<br>
Returns:<br>
The short twitter name of this user</tt></dd></dl>
<dl><dt><a name="User-GetStatus"><strong>GetStatus</strong></a>(self)</dt><dd><tt>Get the latest twitter.<a href="#Status">Status</a> of this user.<br>
<br>
Returns:<br>
The latest twitter.<a href="#Status">Status</a> of this user</tt></dd></dl>
<dl><dt><a name="User-GetStatusesCount"><strong>GetStatusesCount</strong></a>(self)</dt><dd><tt>Get the number of status updates for this user.<br>
<br>
Returns:<br>
The number of status updates for this user.</tt></dd></dl>
<dl><dt><a name="User-GetTimeZone"><strong>GetTimeZone</strong></a>(self)</dt><dd><tt>Returns the current time zone string for the user.<br>
<br>
Returns:<br>
The descriptive time zone string for the user.</tt></dd></dl>
<dl><dt><a name="User-GetUrl"><strong>GetUrl</strong></a>(self)</dt><dd><tt>Get the homepage url of this user.<br>
<br>
Returns:<br>
The homepage url of this user</tt></dd></dl>
<dl><dt><a name="User-GetUtcOffset"><strong>GetUtcOffset</strong></a>(self)</dt></dl>
<dl><dt><a name="User-SetDescription"><strong>SetDescription</strong></a>(self, description)</dt><dd><tt>Set the short text description of this user.<br>
<br>
Args:<br>
description: The short text description of this user</tt></dd></dl>
<dl><dt><a name="User-SetFavouritesCount"><strong>SetFavouritesCount</strong></a>(self, count)</dt><dd><tt>Set the favourite count for this user.<br>
<br>
Args:<br>
count:<br>
The number of favourites for this user.</tt></dd></dl>
<dl><dt><a name="User-SetFollowersCount"><strong>SetFollowersCount</strong></a>(self, count)</dt><dd><tt>Set the follower count for this user.<br>
<br>
Args:<br>
count:<br>
The number of users following this user.</tt></dd></dl>
<dl><dt><a name="User-SetFriendsCount"><strong>SetFriendsCount</strong></a>(self, count)</dt><dd><tt>Set the friend count for this user.<br>
<br>
Args:<br>
count:<br>
The number of users this user has befriended.</tt></dd></dl>
<dl><dt><a name="User-SetId"><strong>SetId</strong></a>(self, id)</dt><dd><tt>Set the unique id of this user.<br>
<br>
Args:<br>
id: The unique id of this user.</tt></dd></dl>
<dl><dt><a name="User-SetLocation"><strong>SetLocation</strong></a>(self, location)</dt><dd><tt>Set the geographic location of this user.<br>
<br>
Args:<br>
location: The geographic location of this user</tt></dd></dl>
<dl><dt><a name="User-SetName"><strong>SetName</strong></a>(self, name)</dt><dd><tt>Set the real name of this user.<br>
<br>
Args:<br>
name: The real name of this user</tt></dd></dl>
<dl><dt><a name="User-SetProfileBackgroundColor"><strong>SetProfileBackgroundColor</strong></a>(self, profile_background_color)</dt></dl>
<dl><dt><a name="User-SetProfileBackgroundImageUrl"><strong>SetProfileBackgroundImageUrl</strong></a>(self, profile_background_image_url)</dt></dl>
<dl><dt><a name="User-SetProfileBackgroundTile"><strong>SetProfileBackgroundTile</strong></a>(self, profile_background_tile)</dt><dd><tt>Set the boolean flag for whether to tile the profile background image.<br>
<br>
Args:<br>
profile_background_tile: Boolean flag for whether to tile or not.</tt></dd></dl>
<dl><dt><a name="User-SetProfileImageUrl"><strong>SetProfileImageUrl</strong></a>(self, profile_image_url)</dt><dd><tt>Set the url of the thumbnail of this user.<br>
<br>
Args:<br>
profile_image_url: The url of the thumbnail of this user</tt></dd></dl>
<dl><dt><a name="User-SetProfileLinkColor"><strong>SetProfileLinkColor</strong></a>(self, profile_link_color)</dt></dl>
<dl><dt><a name="User-SetProfileSidebarFillColor"><strong>SetProfileSidebarFillColor</strong></a>(self, profile_sidebar_fill_color)</dt></dl>
<dl><dt><a name="User-SetProfileTextColor"><strong>SetProfileTextColor</strong></a>(self, profile_text_color)</dt></dl>
<dl><dt><a name="User-SetProtected"><strong>SetProtected</strong></a>(self, protected)</dt></dl>
<dl><dt><a name="User-SetScreenName"><strong>SetScreenName</strong></a>(self, screen_name)</dt><dd><tt>Set the short twitter name of this user.<br>
<br>
Args:<br>
screen_name: the short twitter name of this user</tt></dd></dl>
<dl><dt><a name="User-SetStatus"><strong>SetStatus</strong></a>(self, status)</dt><dd><tt>Set the latest twitter.<a href="#Status">Status</a> of this user.<br>
<br>
Args:<br>
status:<br>
The latest twitter.<a href="#Status">Status</a> of this user</tt></dd></dl>
<dl><dt><a name="User-SetStatusesCount"><strong>SetStatusesCount</strong></a>(self, count)</dt><dd><tt>Set the status update count for this user.<br>
<br>
Args:<br>
count:<br>
The number of updates for this user.</tt></dd></dl>
<dl><dt><a name="User-SetTimeZone"><strong>SetTimeZone</strong></a>(self, time_zone)</dt><dd><tt>Sets the user's time zone string.<br>
<br>
Args:<br>
time_zone:<br>
The descriptive time zone to assign for the user.</tt></dd></dl>
<dl><dt><a name="User-SetUrl"><strong>SetUrl</strong></a>(self, url)</dt><dd><tt>Set the homepage url of this user.<br>
<br>
Args:<br>
url: The homepage url of this user</tt></dd></dl>
<dl><dt><a name="User-SetUtcOffset"><strong>SetUtcOffset</strong></a>(self, utc_offset)</dt></dl>
<dl><dt><a name="User-__eq__"><strong>__eq__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="User-__init__"><strong>__init__</strong></a>(self, id<font color="#909090">=None</font>, name<font color="#909090">=None</font>, screen_name<font color="#909090">=None</font>, location<font color="#909090">=None</font>, description<font color="#909090">=None</font>, profile_image_url<font color="#909090">=None</font>, profile_background_tile<font color="#909090">=None</font>, profile_background_image_url<font color="#909090">=None</font>, profile_sidebar_fill_color<font color="#909090">=None</font>, profile_background_color<font color="#909090">=None</font>, profile_link_color<font color="#909090">=None</font>, profile_text_color<font color="#909090">=None</font>, protected<font color="#909090">=None</font>, utc_offset<font color="#909090">=None</font>, time_zone<font color="#909090">=None</font>, followers_count<font color="#909090">=None</font>, friends_count<font color="#909090">=None</font>, statuses_count<font color="#909090">=None</font>, favourites_count<font color="#909090">=None</font>, url<font color="#909090">=None</font>, status<font color="#909090">=None</font>)</dt></dl>
<dl><dt><a name="User-__ne__"><strong>__ne__</strong></a>(self, other)</dt></dl>
<dl><dt><a name="User-__str__"><strong>__str__</strong></a>(self)</dt><dd><tt>A string representation of this twitter.<a href="#User">User</a> instance.<br>
<br>
The return value is the same as the JSON string representation.<br>
<br>
Returns:<br>
A string representation of this twitter.<a href="#User">User</a> instance.</tt></dd></dl>
<hr>
Static methods defined here:<br>
<dl><dt><a name="User-NewFromJsonDict"><strong>NewFromJsonDict</strong></a>(data)</dt><dd><tt>Create a new instance based on a JSON dict.<br>
<br>
Args:<br>
data:<br>
A JSON dict, as converted from the JSON in the twitter API<br>
<br>
Returns:<br>
A twitter.<a href="#User">User</a> instance</tt></dd></dl>
<hr>
Data descriptors defined here:<br>
<dl><dt><strong>__dict__</strong></dt>
<dd><tt>dictionary for instance variables (if defined)</tt></dd>
</dl>
<dl><dt><strong>__weakref__</strong></dt>
<dd><tt>list of weak references to the object (if defined)</tt></dd>
</dl>
<dl><dt><strong>description</strong></dt>
<dd><tt>The short text description of this user.</tt></dd>
</dl>
<dl><dt><strong>favourites_count</strong></dt>
<dd><tt>The number of favourites for this user.</tt></dd>
</dl>
<dl><dt><strong>followers_count</strong></dt>
<dd><tt>The number of users following this user.</tt></dd>
</dl>
<dl><dt><strong>friends_count</strong></dt>
<dd><tt>The number of friends for this user.</tt></dd>
</dl>
<dl><dt><strong>id</strong></dt>
<dd><tt>The unique id of this user.</tt></dd>
</dl>
<dl><dt><strong>location</strong></dt>
<dd><tt>The geographic location of this user.</tt></dd>
</dl>
<dl><dt><strong>name</strong></dt>
<dd><tt>The real name of this user.</tt></dd>
</dl>
<dl><dt><strong>profile_background_color</strong></dt>
</dl>
<dl><dt><strong>profile_background_image_url</strong></dt>
<dd><tt>The url of the profile background of this user.</tt></dd>
</dl>
<dl><dt><strong>profile_background_tile</strong></dt>
<dd><tt>Boolean for whether to tile the background image.</tt></dd>
</dl>
<dl><dt><strong>profile_image_url</strong></dt>
<dd><tt>The url of the thumbnail of this user.</tt></dd>
</dl>
<dl><dt><strong>profile_link_color</strong></dt>
</dl>
<dl><dt><strong>profile_sidebar_fill_color</strong></dt>
</dl>
<dl><dt><strong>profile_text_color</strong></dt>
</dl>
<dl><dt><strong>protected</strong></dt>
</dl>
<dl><dt><strong>screen_name</strong></dt>
<dd><tt>The short twitter name of this user.</tt></dd>
</dl>
<dl><dt><strong>status</strong></dt>
<dd><tt>The latest twitter.Status of this user.</tt></dd>
</dl>
<dl><dt><strong>statuses_count</strong></dt>
<dd><tt>The number of updates for this user.</tt></dd>
</dl>
<dl><dt><strong>time_zone</strong></dt>
<dd><tt>Returns the current time zone string for the user.<br>
<br>
Returns:<br>
The descriptive time zone string for the user.</tt></dd>
</dl>
<dl><dt><strong>url</strong></dt>
<dd><tt>The homepage url of this user.</tt></dd>
</dl>
<dl><dt><strong>utc_offset</strong></dt>
</dl>
</td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#eeaa77">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
<tr><td bgcolor="#eeaa77"><tt> </tt></td><td> </td>
<td width="100%"><dl><dt><a name="-md5"><strong>md5</strong></a> = openssl_md5(...)</dt><dd><tt>Returns a md5 hash <a href="__builtin__.html#object">object</a>; optionally initialized with a string</tt></dd></dl>
</td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#55aa55">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
<tr><td bgcolor="#55aa55"><tt> </tt></td><td> </td>
<td width="100%"><strong>ACCESS_TOKEN_URL</strong> = 'https://api.twitter.com/oauth/access_token'<br>
<strong>AUTHORIZATION_URL</strong> = 'https://api.twitter.com/oauth/authorize'<br>
<strong>CHARACTER_LIMIT</strong> = 140<br>
<strong>DEFAULT_CACHE</strong> = <object object at 0x1001da0a0><br>
<strong>REQUEST_TOKEN_URL</strong> = 'https://api.twitter.com/oauth/request_token'<br>
<strong>SIGNIN_URL</strong> = 'https://api.twitter.com/oauth/authenticate'<br>
<strong>__author__</strong> = 'python-twitter@googlegroups.com'<br>
<strong>__version__</strong> = '0.8'</td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#7799ee">
<td colspan=3 valign=bottom> <br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Author</strong></big></font></td></tr>
<tr><td bgcolor="#7799ee"><tt> </tt></td><td> </td>
<td width="100%">python-twitter@googlegroups.com</td></tr></table>
</body></html>
|
1101391i-python-twitter
|
doc/twitter.html
|
HTML
|
asf20
| 132,276
|
#!/usr/bin/python2.4
#
# Copyright 2007 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
# parse_qsl moved to urlparse module in v2.6
try:
from urlparse import parse_qsl
except:
from cgi import parse_qsl
import oauth2 as oauth
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'
consumer_key = None
consumer_secret = None
if consumer_key is None or consumer_secret is None:
print 'You need to edit this script and provide values for the'
print 'consumer_key and also consumer_secret.'
print ''
print 'The values you need come from Twitter - you need to register'
print 'as a developer your "application". This is needed only until'
print 'Twitter finishes the idea they have of a way to allow open-source'
print 'based libraries to have a token that can be used to generate a'
print 'one-time use key that will allow the library to make the request'
print 'on your behalf.'
print ''
sys.exit(1)
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
oauth_client = oauth.Client(oauth_consumer)
print 'Requesting temp token from Twitter'
resp, content = oauth_client.request(REQUEST_TOKEN_URL, 'GET')
if resp['status'] != '200':
print 'Invalid respond from Twitter requesting temp token: %s' % resp['status']
else:
request_token = dict(parse_qsl(content))
print ''
print 'Please visit this Twitter page and retrieve the pincode to be used'
print 'in the next step to obtaining an Authentication Token:'
print ''
print '%s?oauth_token=%s' % (AUTHORIZATION_URL, request_token['oauth_token'])
print ''
pincode = raw_input('Pincode? ')
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(pincode)
print ''
print 'Generating and signing request for an access token'
print ''
oauth_client = oauth.Client(oauth_consumer, token)
resp, content = oauth_client.request(ACCESS_TOKEN_URL, method='POST', body='oauth_callback=oob&oauth_verifier=%s' % pincode)
access_token = dict(parse_qsl(content))
if resp['status'] != '200':
print 'The request for a Token did not succeed: %s' % resp['status']
print access_token
else:
print 'Your Twitter Access Token key: %s' % access_token['oauth_token']
print ' Access Token secret: %s' % access_token['oauth_token_secret']
print ''
|
1101391i-python-twitter
|
get_access_token.py
|
Python
|
asf20
| 3,192
|
#!/usr/bin/python2.4
#
# Copyright 2007 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''A class that defines the default URL Shortener.
TinyURL is provided as the default and as an example.
'''
import urllib
# Change History
#
# 2010-05-16
# TinyURL example and the idea for this comes from a bug filed by
# acolorado with patch provided by ghills. Class implementation
# was done by bear.
#
# Issue 19 http://code.google.com/p/python-twitter/issues/detail?id=19
#
class ShortenURL(object):
'''Helper class to make URL Shortener calls if/when required'''
def __init__(self,
userid=None,
password=None):
'''Instantiate a new ShortenURL object
Args:
userid: userid for any required authorization call [optional]
password: password for any required authorization call [optional]
'''
self.userid = userid
self.password = password
def Shorten(self,
longURL):
'''Call TinyURL API and returned shortened URL result
Args:
longURL: URL string to shorten
Returns:
The shortened URL as a string
Note:
longURL is required and no checks are made to ensure completeness
'''
result = None
f = urllib.urlopen("http://tinyurl.com/api-create.php?url=%s" % longURL)
try:
result = f.read()
finally:
f.close()
return result
|
1101391i-python-twitter
|
examples/shorten_url.py
|
Python
|
asf20
| 2,072
|
#!/usr/bin/python2.4
'''Load the latest update for a Twitter user and leave it in an XHTML fragment'''
__author__ = 'dewitt@google.com'
import codecs
import getopt
import sys
import twitter
TEMPLATE = """
<div class="twitter">
<span class="twitter-user"><a href="http://twitter.com/%s">Twitter</a>: </span>
<span class="twitter-text">%s</span>
<span class="twitter-relative-created-at"><a href="http://twitter.com/%s/statuses/%s">Posted %s</a></span>
</div>
"""
def Usage():
print 'Usage: %s [options] twitterid' % __file__
print
print ' This script fetches a users latest twitter update and stores'
print ' the result in a file as an XHTML fragment'
print
print ' Options:'
print ' --help -h : print this help'
print ' --output : the output file [default: stdout]'
def FetchTwitter(user, output):
assert user
statuses = twitter.Api().GetUserTimeline(user=user, count=1)
s = statuses[0]
xhtml = TEMPLATE % (s.user.screen_name, s.text, s.user.screen_name, s.id, s.relative_created_at)
if output:
Save(xhtml, output)
else:
print xhtml
def Save(xhtml, output):
out = codecs.open(output, mode='w', encoding='ascii',
errors='xmlcharrefreplace')
out.write(xhtml)
out.close()
def main():
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output='])
except getopt.GetoptError:
Usage()
sys.exit(2)
try:
user = args[0]
except:
Usage()
sys.exit(2)
output = None
for o, a in opts:
if o in ("-h", "--help"):
Usage()
sys.exit(2)
if o in ("-o", "--output"):
output = a
FetchTwitter(user, output)
if __name__ == "__main__":
main()
|
1101391i-python-twitter
|
examples/twitter-to-xhtml.py
|
Python
|
asf20
| 1,685
|
#!/usr/bin/python2.4
'''Post a message to twitter'''
__author__ = 'dewitt@google.com'
import ConfigParser
import getopt
import os
import sys
import twitter
USAGE = '''Usage: tweet [options] message
This script posts a message to Twitter.
Options:
-h --help : print this help
--consumer-key : the twitter consumer key
--consumer-secret : the twitter consumer secret
--access-key : the twitter access token key
--access-secret : the twitter access token secret
--encoding : the character set encoding used in input strings, e.g. "utf-8". [optional]
Documentation:
If either of the command line flags are not present, the environment
variables TWEETUSERNAME and TWEETPASSWORD will then be checked for your
consumer_key or consumer_secret, respectively.
If neither the command line flags nor the enviroment variables are
present, the .tweetrc file, if it exists, can be used to set the
default consumer_key and consumer_secret. The file should contain the
following three lines, replacing *consumer_key* with your consumer key, and
*consumer_secret* with your consumer secret:
A skeletal .tweetrc file:
[Tweet]
consumer_key: *consumer_key*
consumer_secret: *consumer_password*
access_key: *access_key*
access_secret: *access_password*
'''
def PrintUsageAndExit():
print USAGE
sys.exit(2)
def GetConsumerKeyEnv():
return os.environ.get("TWEETUSERNAME", None)
def GetConsumerSecretEnv():
return os.environ.get("TWEETPASSWORD", None)
def GetAccessKeyEnv():
return os.environ.get("TWEETACCESSKEY", None)
def GetAccessSecretEnv():
return os.environ.get("TWEETACCESSSECRET", None)
class TweetRc(object):
def __init__(self):
self._config = None
def GetConsumerKey(self):
return self._GetOption('consumer_key')
def GetConsumerSecret(self):
return self._GetOption('consumer_secret')
def GetAccessKey(self):
return self._GetOption('access_key')
def GetAccessSecret(self):
return self._GetOption('access_secret')
def _GetOption(self, option):
try:
return self._GetConfig().get('Tweet', option)
except:
return None
def _GetConfig(self):
if not self._config:
self._config = ConfigParser.ConfigParser()
self._config.read(os.path.expanduser('~/.tweetrc'))
return self._config
def main():
try:
shortflags = 'h'
longflags = ['help', 'consumer-key=', 'consumer-secret=',
'access-key=', 'access-secret=', 'encoding=']
opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags)
except getopt.GetoptError:
PrintUsageAndExit()
consumer_keyflag = None
consumer_secretflag = None
access_keyflag = None
access_secretflag = None
encoding = None
for o, a in opts:
if o in ("-h", "--help"):
PrintUsageAndExit()
if o in ("--consumer-key"):
consumer_keyflag = a
if o in ("--consumer-secret"):
consumer_secretflag = a
if o in ("--access-key"):
access_keyflag = a
if o in ("--access-secret"):
access_secretflag = a
if o in ("--encoding"):
encoding = a
message = ' '.join(args)
if not message:
PrintUsageAndExit()
rc = TweetRc()
consumer_key = consumer_keyflag or GetConsumerKeyEnv() or rc.GetConsumerKey()
consumer_secret = consumer_secretflag or GetConsumerSecretEnv() or rc.GetConsumerSecret()
access_key = access_keyflag or GetAccessKeyEnv() or rc.GetAccessKey()
access_secret = access_secretflag or GetAccessSecretEnv() or rc.GetAccessSecret()
if not consumer_key or not consumer_secret or not access_key or not access_secret:
PrintUsageAndExit()
api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret,
access_token_key=access_key, access_token_secret=access_secret,
input_encoding=encoding)
try:
status = api.PostUpdate(message)
except UnicodeDecodeError:
print "Your message could not be encoded. Perhaps it contains non-ASCII characters? "
print "Try explicitly specifying the encoding with the --encoding flag"
sys.exit(2)
print "%s just posted: %s" % (status.user.name, status.text)
if __name__ == "__main__":
main()
|
1101391i-python-twitter
|
examples/tweet.py
|
Python
|
asf20
| 4,205
|
"""JSON token scanner
"""
import re
try:
from simplejson._speedups import make_scanner as c_make_scanner
except ImportError:
c_make_scanner = None
__all__ = ['make_scanner']
NUMBER_RE = re.compile(
r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
(re.VERBOSE | re.MULTILINE | re.DOTALL))
def py_make_scanner(context):
parse_object = context.parse_object
parse_array = context.parse_array
parse_string = context.parse_string
match_number = NUMBER_RE.match
encoding = context.encoding
strict = context.strict
parse_float = context.parse_float
parse_int = context.parse_int
parse_constant = context.parse_constant
object_hook = context.object_hook
def _scan_once(string, idx):
try:
nextchar = string[idx]
except IndexError:
raise StopIteration
if nextchar == '"':
return parse_string(string, idx + 1, encoding, strict)
elif nextchar == '{':
return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook)
elif nextchar == '[':
return parse_array((string, idx + 1), _scan_once)
elif nextchar == 'n' and string[idx:idx + 4] == 'null':
return None, idx + 4
elif nextchar == 't' and string[idx:idx + 4] == 'true':
return True, idx + 4
elif nextchar == 'f' and string[idx:idx + 5] == 'false':
return False, idx + 5
m = match_number(string, idx)
if m is not None:
integer, frac, exp = m.groups()
if frac or exp:
res = parse_float(integer + (frac or '') + (exp or ''))
else:
res = parse_int(integer)
return res, m.end()
elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
return parse_constant('NaN'), idx + 3
elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
return parse_constant('Infinity'), idx + 8
elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
return parse_constant('-Infinity'), idx + 9
else:
raise StopIteration
return _scan_once
make_scanner = c_make_scanner or py_make_scanner
|
1101391i-python-twitter
|
simplejson/scanner.py
|
Python
|
asf20
| 2,227
|
#include "Python.h"
#include "structmember.h"
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PyInt_FromSsize_t PyInt_FromLong
#define PyInt_AsSsize_t PyInt_AsLong
#endif
#ifndef Py_IS_FINITE
#define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
#endif
#ifdef __GNUC__
#define UNUSED __attribute__((__unused__))
#else
#define UNUSED
#endif
#define DEFAULT_ENCODING "utf-8"
#define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
#define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
#define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
#define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
static PyTypeObject PyScannerType;
static PyTypeObject PyEncoderType;
typedef struct _PyScannerObject {
PyObject_HEAD
PyObject *encoding;
PyObject *strict;
PyObject *object_hook;
PyObject *parse_float;
PyObject *parse_int;
PyObject *parse_constant;
} PyScannerObject;
static PyMemberDef scanner_members[] = {
{"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
{"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
{"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
{"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
{"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
{"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
{NULL}
};
typedef struct _PyEncoderObject {
PyObject_HEAD
PyObject *markers;
PyObject *defaultfn;
PyObject *encoder;
PyObject *indent;
PyObject *key_separator;
PyObject *item_separator;
PyObject *sort_keys;
PyObject *skipkeys;
int fast_encode;
int allow_nan;
} PyEncoderObject;
static PyMemberDef encoder_members[] = {
{"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
{"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
{"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
{"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
{"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
{"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
{"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
{"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
{NULL}
};
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
static PyObject *
ascii_escape_unicode(PyObject *pystr);
static PyObject *
ascii_escape_str(PyObject *pystr);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
void init_speedups(void);
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
scanner_dealloc(PyObject *self);
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
static void
encoder_dealloc(PyObject *self);
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
static PyObject *
_encoded_const(PyObject *const);
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj);
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj);
#define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
#define MIN_EXPANSION 6
#ifdef Py_UNICODE_WIDE
#define MAX_EXPANSION (2 * MIN_EXPANSION)
#else
#define MAX_EXPANSION MIN_EXPANSION
#endif
static int
_convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
{
/* PyObject to Py_ssize_t converter */
*size_ptr = PyInt_AsSsize_t(o);
if (*size_ptr == -1 && PyErr_Occurred());
return 1;
return 0;
}
static PyObject *
_convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
{
/* Py_ssize_t to PyObject converter */
return PyInt_FromSsize_t(*size_ptr);
}
static Py_ssize_t
ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
{
/* Escape unicode code point c to ASCII escape sequences
in char *output. output must have at least 12 bytes unused to
accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
output[chars++] = '\\';
switch (c) {
case '\\': output[chars++] = (char)c; break;
case '"': output[chars++] = (char)c; break;
case '\b': output[chars++] = 'b'; break;
case '\f': output[chars++] = 'f'; break;
case '\n': output[chars++] = 'n'; break;
case '\r': output[chars++] = 'r'; break;
case '\t': output[chars++] = 't'; break;
default:
#ifdef Py_UNICODE_WIDE
if (c >= 0x10000) {
/* UTF-16 surrogate pair */
Py_UNICODE v = c - 0x10000;
c = 0xd800 | ((v >> 10) & 0x3ff);
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
c = 0xdc00 | (v & 0x3ff);
output[chars++] = '\\';
}
#endif
output[chars++] = 'u';
output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
output[chars++] = "0123456789abcdef"[(c ) & 0xf];
}
return chars;
}
static PyObject *
ascii_escape_unicode(PyObject *pystr)
{
/* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t max_output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
Py_UNICODE *input_unicode;
input_chars = PyUnicode_GET_SIZE(pystr);
input_unicode = PyUnicode_AS_UNICODE(pystr);
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
max_output_size = 2 + (input_chars * MAX_EXPANSION);
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
chars = 0;
output[chars++] = '"';
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = input_unicode[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
if (output_size - chars < (1 + MAX_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
Py_ssize_t new_output_size = output_size * 2;
/* This is an upper bound */
if (new_output_size > max_output_size) {
new_output_size = max_output_size;
}
/* Make sure that the output size changed before resizing */
if (new_output_size != output_size) {
output_size = new_output_size;
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static PyObject *
ascii_escape_str(PyObject *pystr)
{
/* Take a PyString pystr and return a new ASCII-only escaped PyString */
Py_ssize_t i;
Py_ssize_t input_chars;
Py_ssize_t output_size;
Py_ssize_t chars;
PyObject *rval;
char *output;
char *input_str;
input_chars = PyString_GET_SIZE(pystr);
input_str = PyString_AS_STRING(pystr);
/* Fast path for a string that's already ASCII */
for (i = 0; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (!S_CHAR(c)) {
/* If we have to escape something, scan the string for unicode */
Py_ssize_t j;
for (j = i; j < input_chars; j++) {
c = (Py_UNICODE)(unsigned char)input_str[j];
if (c > 0x7f) {
/* We hit a non-ASCII character, bail to unicode mode */
PyObject *uni;
uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
if (uni == NULL) {
return NULL;
}
rval = ascii_escape_unicode(uni);
Py_DECREF(uni);
return rval;
}
}
break;
}
}
if (i == input_chars) {
/* Input is already ASCII */
output_size = 2 + input_chars;
}
else {
/* One char input can be up to 6 chars output, estimate 4 of these */
output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
}
rval = PyString_FromStringAndSize(NULL, output_size);
if (rval == NULL) {
return NULL;
}
output = PyString_AS_STRING(rval);
output[0] = '"';
/* We know that everything up to i is ASCII already */
chars = i + 1;
memcpy(&output[1], input_str, i);
for (; i < input_chars; i++) {
Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
if (S_CHAR(c)) {
output[chars++] = (char)c;
}
else {
chars = ascii_escape_char(c, output, chars);
}
/* An ASCII char can't possibly expand to a surrogate! */
if (output_size - chars < (1 + MIN_EXPANSION)) {
/* There's more than four, so let's resize by a lot */
output_size *= 2;
if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
output_size = 2 + (input_chars * MIN_EXPANSION);
}
if (_PyString_Resize(&rval, output_size) == -1) {
return NULL;
}
output = PyString_AS_STRING(rval);
}
}
output[chars++] = '"';
if (_PyString_Resize(&rval, chars) == -1) {
return NULL;
}
return rval;
}
static void
raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
{
/* Use the Python function simplejson.decoder.errmsg to raise a nice
looking ValueError exception */
static PyObject *errmsg_fn = NULL;
PyObject *pymsg;
if (errmsg_fn == NULL) {
PyObject *decoder = PyImport_ImportModule("simplejson.decoder");
if (decoder == NULL)
return;
errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
Py_DECREF(decoder);
if (errmsg_fn == NULL)
return;
}
pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
if (pymsg) {
PyErr_SetObject(PyExc_ValueError, pymsg);
Py_DECREF(pymsg);
}
}
static PyObject *
join_list_unicode(PyObject *lst)
{
/* return u''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
join_list_string(PyObject *lst)
{
/* return ''.join(lst) */
static PyObject *joinfn = NULL;
if (joinfn == NULL) {
PyObject *ustr = PyString_FromStringAndSize(NULL, 0);
if (ustr == NULL)
return NULL;
joinfn = PyObject_GetAttrString(ustr, "join");
Py_DECREF(ustr);
if (joinfn == NULL)
return NULL;
}
return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
}
static PyObject *
_build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
/* return (rval, idx) tuple, stealing reference to rval */
PyObject *tpl;
PyObject *pyidx;
/*
steal a reference to rval, returns (rval, idx)
*/
if (rval == NULL) {
return NULL;
}
pyidx = PyInt_FromSsize_t(idx);
if (pyidx == NULL) {
Py_DECREF(rval);
return NULL;
}
tpl = PyTuple_New(2);
if (tpl == NULL) {
Py_DECREF(pyidx);
Py_DECREF(rval);
return NULL;
}
PyTuple_SET_ITEM(tpl, 0, rval);
PyTuple_SET_ITEM(tpl, 1, pyidx);
return tpl;
}
static PyObject *
scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyString pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyString (if ASCII-only) or PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyString_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
int has_unicode = 0;
char *buf = PyString_AS_STRING(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = (unsigned char)buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
else if (c > 0x7f) {
has_unicode = 1;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end);
if (strchunk == NULL) {
goto bail;
}
if (has_unicode) {
chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
Py_DECREF(strchunk);
if (chunk == NULL) {
goto bail;
}
}
else {
chunk = strchunk;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
if (c > 0x7f) {
has_unicode = 1;
}
if (has_unicode) {
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
}
else {
char c_char = Py_CHARMASK(c);
chunk = PyString_FromStringAndSize(&c_char, 1);
if (chunk == NULL) {
goto bail;
}
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_string(chunks);
if (rval == NULL) {
goto bail;
}
Py_CLEAR(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
static PyObject *
scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
{
/* Read the JSON string from PyUnicode pystr.
end is the index of the first character after the quote.
encoding is the encoding of pystr (must be an ASCII superset)
if strict is zero then literal control characters are allowed
*next_end_ptr is a return-by-reference index of the character
after the end quote
Return value is a new PyUnicode
*/
PyObject *rval;
Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
Py_ssize_t begin = end - 1;
Py_ssize_t next = begin;
const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
PyObject *chunks = PyList_New(0);
if (chunks == NULL) {
goto bail;
}
if (end < 0 || len <= end) {
PyErr_SetString(PyExc_ValueError, "end is out of bounds");
goto bail;
}
while (1) {
/* Find the end of the string or the next escape */
Py_UNICODE c = 0;
PyObject *chunk = NULL;
for (next = end; next < len; next++) {
c = buf[next];
if (c == '"' || c == '\\') {
break;
}
else if (strict && c <= 0x1f) {
raise_errmsg("Invalid control character at", pystr, next);
goto bail;
}
}
if (!(c == '"' || c == '\\')) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
/* Pick up this chunk if it's not zero length */
if (next != end) {
chunk = PyUnicode_FromUnicode(&buf[end], next - end);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
next++;
if (c == '"') {
end = next;
break;
}
if (next == len) {
raise_errmsg("Unterminated string starting at", pystr, begin);
goto bail;
}
c = buf[next];
if (c != 'u') {
/* Non-unicode backslash escapes */
end = next + 1;
switch (c) {
case '"': break;
case '\\': break;
case '/': break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default: c = 0;
}
if (c == 0) {
raise_errmsg("Invalid \\escape", pystr, end - 2);
goto bail;
}
}
else {
c = 0;
next++;
end = next + 4;
if (end >= len) {
raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
goto bail;
}
/* Decode 4 hex digits */
for (; next < end; next++) {
Py_UNICODE digit = buf[next];
c <<= 4;
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
#ifdef Py_UNICODE_WIDE
/* Surrogate pair */
if ((c & 0xfc00) == 0xd800) {
Py_UNICODE c2 = 0;
if (end + 6 >= len) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
if (buf[next++] != '\\' || buf[next++] != 'u') {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
end += 6;
/* Decode 4 hex digits */
for (; next < end; next++) {
c2 <<= 4;
Py_UNICODE digit = buf[next];
switch (digit) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c2 |= (digit - '0'); break;
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f':
c2 |= (digit - 'a' + 10); break;
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F':
c2 |= (digit - 'A' + 10); break;
default:
raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
goto bail;
}
}
if ((c2 & 0xfc00) != 0xdc00) {
raise_errmsg("Unpaired high surrogate", pystr, end - 5);
goto bail;
}
c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
}
else if ((c & 0xfc00) == 0xdc00) {
raise_errmsg("Unpaired low surrogate", pystr, end - 5);
goto bail;
}
#endif
}
chunk = PyUnicode_FromUnicode(&c, 1);
if (chunk == NULL) {
goto bail;
}
if (PyList_Append(chunks, chunk)) {
Py_DECREF(chunk);
goto bail;
}
Py_DECREF(chunk);
}
rval = join_list_unicode(chunks);
if (rval == NULL) {
goto bail;
}
Py_DECREF(chunks);
*next_end_ptr = end;
return rval;
bail:
*next_end_ptr = -1;
Py_XDECREF(chunks);
return NULL;
}
PyDoc_STRVAR(pydoc_scanstring,
"scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
"\n"
"Scan the string s for a JSON string. End is the index of the\n"
"character in s after the quote that started the JSON string.\n"
"Unescapes all valid JSON string escape sequences and raises ValueError\n"
"on attempt to decode an invalid string. If strict is False then literal\n"
"control characters are allowed in the string.\n"
"\n"
"Returns a tuple of the decoded string and the index of the character in s\n"
"after the end quote."
);
static PyObject *
py_scanstring(PyObject* self UNUSED, PyObject *args)
{
PyObject *pystr;
PyObject *rval;
Py_ssize_t end;
Py_ssize_t next_end = -1;
char *encoding = NULL;
int strict = 1;
if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
return NULL;
}
if (encoding == NULL) {
encoding = DEFAULT_ENCODING;
}
if (PyString_Check(pystr)) {
rval = scanstring_str(pystr, end, encoding, strict, &next_end);
}
else if (PyUnicode_Check(pystr)) {
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_end);
}
PyDoc_STRVAR(pydoc_encode_basestring_ascii,
"encode_basestring_ascii(basestring) -> str\n"
"\n"
"Return an ASCII-only JSON representation of a Python string"
);
static PyObject *
py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
{
/* Return an ASCII-only JSON representation of a Python string */
/* METH_O */
if (PyString_Check(pystr)) {
return ascii_escape_str(pystr);
}
else if (PyUnicode_Check(pystr)) {
return ascii_escape_unicode(pystr);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
}
static void
scanner_dealloc(PyObject *self)
{
/* Deallocate scanner object */
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
self->ob_type->tp_free(self);
}
static PyObject *
_parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyString pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *rval = PyDict_New();
PyObject *key = NULL;
PyObject *val = NULL;
char *encoding = PyString_AS_STRING(s->encoding);
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON data type */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyDict_SetItem(rval, key, val) == -1)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON object from PyUnicode pystr.
idx is the index of the first character after the opening curly brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing curly brace.
Returns a new PyObject (usually a dict, but object_hook can change that)
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyDict_New();
PyObject *key = NULL;
int strict = PyObject_IsTrue(s->strict);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after { */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the object is non-empty */
if (idx <= end_idx && str[idx] != '}') {
while (idx <= end_idx) {
/* read key */
if (str[idx] != '"') {
raise_errmsg("Expecting property name", pystr, idx);
goto bail;
}
key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
if (key == NULL)
goto bail;
idx = next_idx;
/* skip whitespace between key and : delimiter, read :, skip whitespace */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
if (idx > end_idx || str[idx] != ':') {
raise_errmsg("Expecting : delimiter", pystr, idx);
goto bail;
}
idx++;
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyDict_SetItem(rval, key, val) == -1)
goto bail;
Py_CLEAR(key);
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace before } or , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the object is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == '}') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , delimiter */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be '}' */
if (idx > end_idx || str[idx] != '}') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
/* if object_hook is not None: rval = object_hook(rval) */
if (s->object_hook != Py_None) {
val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
if (val == NULL)
goto bail;
Py_DECREF(rval);
rval = val;
val = NULL;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(key);
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term and de-tuplefy the (rval, idx) */
val = scan_once_str(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON array from PyString pystr.
idx is the index of the first character after the opening brace.
*next_idx_ptr is a return-by-reference index to the first character after
the closing brace.
Returns a new PyList
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
PyObject *val = NULL;
PyObject *rval = PyList_New(0);
Py_ssize_t next_idx;
if (rval == NULL)
return NULL;
/* skip whitespace after [ */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* only loop if the array is non-empty */
if (idx <= end_idx && str[idx] != ']') {
while (idx <= end_idx) {
/* read any JSON term */
val = scan_once_unicode(s, pystr, idx, &next_idx);
if (val == NULL)
goto bail;
if (PyList_Append(rval, val) == -1)
goto bail;
Py_CLEAR(val);
idx = next_idx;
/* skip whitespace between term and , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
/* bail if the array is closed or we didn't get the , delimiter */
if (idx > end_idx) break;
if (str[idx] == ']') {
break;
}
else if (str[idx] != ',') {
raise_errmsg("Expecting , delimiter", pystr, idx);
goto bail;
}
idx++;
/* skip whitespace after , */
while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
}
}
/* verify that idx < end_idx, str[idx] should be ']' */
if (idx > end_idx || str[idx] != ']') {
raise_errmsg("Expecting object", pystr, end_idx);
goto bail;
}
*next_idx_ptr = idx + 1;
return rval;
bail:
Py_XDECREF(val);
Py_DECREF(rval);
return NULL;
}
static PyObject *
_parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
/* Read a JSON constant from PyString pystr.
constant is the constant string that was found
("NaN", "Infinity", "-Infinity").
idx is the index of the first character of the constant
*next_idx_ptr is a return-by-reference index to the first character after
the constant.
Returns the result of parse_constant
*/
PyObject *cstr;
PyObject *rval;
/* constant is "NaN", "Infinity", or "-Infinity" */
cstr = PyString_InternFromString(constant);
if (cstr == NULL)
return NULL;
/* rval = parse_constant(constant) */
rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
idx += PyString_GET_SIZE(cstr);
Py_DECREF(cstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyString pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
/* save the index of the 'e' or 'E' just in case we need to backtrack */
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyString_FromStringAndSize(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromDouble(PyOS_ascii_atof(PyString_AS_STRING(numstr)));
}
}
else {
/* parse as an int using a fast path if available, otherwise call user defined method */
if (s->parse_int != (PyObject *)&PyInt_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
else {
rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
}
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
_match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
/* Read a JSON number from PyUnicode pystr.
idx is the index of the first character of the number
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of that number:
PyInt, PyLong, or PyFloat.
May return other types if parse_int or parse_float are set
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
Py_ssize_t idx = start;
int is_float = 0;
PyObject *rval;
PyObject *numstr;
/* read a sign if it's there, make sure it's not the end of the string */
if (str[idx] == '-') {
idx++;
if (idx > end_idx) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
/* read as many integer digits as we find as long as it doesn't start with 0 */
if (str[idx] >= '1' && str[idx] <= '9') {
idx++;
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if it starts with 0 we only expect one integer digit */
else if (str[idx] == '0') {
idx++;
}
/* no integer digits, error */
else {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
/* if the next char is '.' followed by a digit then read all float digits */
if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
is_float = 1;
idx += 2;
while (idx < end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
}
/* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
Py_ssize_t e_start = idx;
idx++;
/* read an exponent sign if present */
if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
/* read all digits */
while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
/* if we got a digit, then parse as float. if not, backtrack */
if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
is_float = 1;
}
else {
idx = e_start;
}
}
/* copy the section we determined to be a number */
numstr = PyUnicode_FromUnicode(&str[start], idx - start);
if (numstr == NULL)
return NULL;
if (is_float) {
/* parse as a float using a fast path if available, otherwise call user defined method */
if (s->parse_float != (PyObject *)&PyFloat_Type) {
rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
}
else {
rval = PyFloat_FromString(numstr, NULL);
}
}
else {
/* no fast path for unicode -> int, just call */
rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
}
Py_DECREF(numstr);
*next_idx_ptr = idx;
return rval;
}
static PyObject *
scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyString pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
char *str = PyString_AS_STRING(pystr);
Py_ssize_t length = PyString_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_str(pystr, idx + 1,
PyString_AS_STRING(s->encoding),
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
return _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
case '[':
/* array */
return _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_str(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
{
/* Read one JSON term (of any kind) from PyUnicode pystr.
idx is the index of the first character of the term
*next_idx_ptr is a return-by-reference index to the first character after
the number.
Returns a new PyObject representation of the term.
*/
Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
if (idx >= length) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
switch (str[idx]) {
case '"':
/* string */
return scanstring_unicode(pystr, idx + 1,
PyObject_IsTrue(s->strict),
next_idx_ptr);
case '{':
/* object */
return _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
case '[':
/* array */
return _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
case 'n':
/* null */
if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
Py_INCREF(Py_None);
*next_idx_ptr = idx + 4;
return Py_None;
}
break;
case 't':
/* true */
if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
Py_INCREF(Py_True);
*next_idx_ptr = idx + 4;
return Py_True;
}
break;
case 'f':
/* false */
if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
Py_INCREF(Py_False);
*next_idx_ptr = idx + 5;
return Py_False;
}
break;
case 'N':
/* NaN */
if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
return _parse_constant(s, "NaN", idx, next_idx_ptr);
}
break;
case 'I':
/* Infinity */
if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
return _parse_constant(s, "Infinity", idx, next_idx_ptr);
}
break;
case '-':
/* -Infinity */
if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
}
break;
}
/* Didn't find a string, object, array, or named constant. Look for a number. */
return _match_number_unicode(s, pystr, idx, next_idx_ptr);
}
static PyObject *
scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to scan_once_{str,unicode} */
PyObject *pystr;
PyObject *rval;
Py_ssize_t idx;
Py_ssize_t next_idx = -1;
static char *kwlist[] = {"string", "idx", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
return NULL;
if (PyString_Check(pystr)) {
rval = scan_once_str(s, pystr, idx, &next_idx);
}
else if (PyUnicode_Check(pystr)) {
rval = scan_once_unicode(s, pystr, idx, &next_idx);
}
else {
PyErr_Format(PyExc_TypeError,
"first argument must be a string, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
}
return _build_rval_index_tuple(rval, next_idx);
}
static int
scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Initialize Scanner object */
PyObject *ctx;
static char *kwlist[] = {"context", NULL};
PyScannerObject *s;
assert(PyScanner_Check(self));
s = (PyScannerObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
return -1;
s->encoding = NULL;
s->strict = NULL;
s->object_hook = NULL;
s->parse_float = NULL;
s->parse_int = NULL;
s->parse_constant = NULL;
/* PyString_AS_STRING is used on encoding */
s->encoding = PyObject_GetAttrString(ctx, "encoding");
if (s->encoding == Py_None) {
Py_DECREF(Py_None);
s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
}
else if (PyUnicode_Check(s->encoding)) {
PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
Py_DECREF(s->encoding);
s->encoding = tmp;
}
if (s->encoding == NULL || !PyString_Check(s->encoding))
goto bail;
/* All of these will fail "gracefully" so we don't need to verify them */
s->strict = PyObject_GetAttrString(ctx, "strict");
if (s->strict == NULL)
goto bail;
s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
if (s->object_hook == NULL)
goto bail;
s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
if (s->parse_float == NULL)
goto bail;
s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
if (s->parse_int == NULL)
goto bail;
s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
if (s->parse_constant == NULL)
goto bail;
return 0;
bail:
Py_CLEAR(s->encoding);
Py_CLEAR(s->strict);
Py_CLEAR(s->object_hook);
Py_CLEAR(s->parse_float);
Py_CLEAR(s->parse_int);
Py_CLEAR(s->parse_constant);
return -1;
}
PyDoc_STRVAR(scanner_doc, "JSON scanner object");
static
PyTypeObject PyScannerType = {
PyObject_HEAD_INIT(0)
0, /* tp_internal */
"Scanner", /* tp_name */
sizeof(PyScannerObject), /* tp_basicsize */
0, /* tp_itemsize */
scanner_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
scanner_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
scanner_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
scanner_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
scanner_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
0,/* PyType_GenericNew, */ /* tp_new */
0,/* _PyObject_Del, */ /* tp_free */
};
static int
encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
/* initialize Encoder object */
static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};
PyEncoderObject *s;
PyObject *allow_nan;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
s->markers = NULL;
s->defaultfn = NULL;
s->encoder = NULL;
s->indent = NULL;
s->key_separator = NULL;
s->item_separator = NULL;
s->sort_keys = NULL;
s->skipkeys = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist,
&s->markers, &s->defaultfn, &s->encoder, &s->indent, &s->key_separator, &s->item_separator, &s->sort_keys, &s->skipkeys, &allow_nan))
return -1;
Py_INCREF(s->markers);
Py_INCREF(s->defaultfn);
Py_INCREF(s->encoder);
Py_INCREF(s->indent);
Py_INCREF(s->key_separator);
Py_INCREF(s->item_separator);
Py_INCREF(s->sort_keys);
Py_INCREF(s->skipkeys);
s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
s->allow_nan = PyObject_IsTrue(allow_nan);
return 0;
}
static PyObject *
encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
{
/* Python callable interface to encode_listencode_obj */
static char *kwlist[] = {"obj", "_current_indent_level", NULL};
PyObject *obj;
PyObject *rval;
Py_ssize_t indent_level;
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
&obj, _convertPyInt_AsSsize_t, &indent_level))
return NULL;
rval = PyList_New(0);
if (rval == NULL)
return NULL;
if (encoder_listencode_obj(s, rval, obj, indent_level)) {
Py_DECREF(rval);
return NULL;
}
return rval;
}
static PyObject *
_encoded_const(PyObject *obj)
{
/* Return the JSON string representation of None, True, False */
if (obj == Py_None) {
static PyObject *s_null = NULL;
if (s_null == NULL) {
s_null = PyString_InternFromString("null");
}
Py_INCREF(s_null);
return s_null;
}
else if (obj == Py_True) {
static PyObject *s_true = NULL;
if (s_true == NULL) {
s_true = PyString_InternFromString("true");
}
Py_INCREF(s_true);
return s_true;
}
else if (obj == Py_False) {
static PyObject *s_false = NULL;
if (s_false == NULL) {
s_false = PyString_InternFromString("false");
}
Py_INCREF(s_false);
return s_false;
}
else {
PyErr_SetString(PyExc_ValueError, "not a const");
return NULL;
}
}
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a PyFloat */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
return NULL;
}
if (i > 0) {
return PyString_FromString("Infinity");
}
else if (i < 0) {
return PyString_FromString("-Infinity");
}
else {
return PyString_FromString("NaN");
}
}
/* Use a better float format here? */
return PyObject_Repr(obj);
}
static PyObject *
encoder_encode_string(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a string */
if (s->fast_encode)
return py_encode_basestring_ascii(NULL, obj);
else
return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
}
static int
_steal_list_append(PyObject *lst, PyObject *stolen)
{
/* Append stolen and then decrement its reference count */
int rval = PyList_Append(lst, stolen);
Py_DECREF(stolen);
return rval;
}
static int
encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
{
/* Encode Python object obj to a JSON term, rval is a PyList */
PyObject *newobj;
int rv;
if (obj == Py_None || obj == Py_True || obj == Py_False) {
PyObject *cstr = _encoded_const(obj);
if (cstr == NULL)
return -1;
return _steal_list_append(rval, cstr);
}
else if (PyString_Check(obj) || PyUnicode_Check(obj))
{
PyObject *encoded = encoder_encode_string(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyInt_Check(obj) || PyLong_Check(obj)) {
PyObject *encoded = PyObject_Str(obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyFloat_Check(obj)) {
PyObject *encoded = encoder_encode_float(s, obj);
if (encoded == NULL)
return -1;
return _steal_list_append(rval, encoded);
}
else if (PyList_Check(obj) || PyTuple_Check(obj)) {
return encoder_listencode_list(s, rval, obj, indent_level);
}
else if (PyDict_Check(obj)) {
return encoder_listencode_dict(s, rval, obj, indent_level);
}
else {
PyObject *ident = NULL;
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(obj);
if (ident == NULL)
return -1;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
Py_DECREF(ident);
return -1;
}
if (PyDict_SetItem(s->markers, ident, obj)) {
Py_DECREF(ident);
return -1;
}
}
newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
if (newobj == NULL) {
Py_XDECREF(ident);
return -1;
}
rv = encoder_listencode_obj(s, rval, newobj, indent_level);
Py_DECREF(newobj);
if (rv) {
Py_XDECREF(ident);
return -1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident)) {
Py_XDECREF(ident);
return -1;
}
Py_XDECREF(ident);
}
return rv;
}
}
static int
encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
{
/* Encode Python dict dct a JSON term, rval is a PyList */
static PyObject *open_dict = NULL;
static PyObject *close_dict = NULL;
static PyObject *empty_dict = NULL;
PyObject *kstr = NULL;
PyObject *ident = NULL;
PyObject *key, *value;
Py_ssize_t pos;
int skipkeys;
Py_ssize_t idx;
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) {
open_dict = PyString_InternFromString("{");
close_dict = PyString_InternFromString("}");
empty_dict = PyString_InternFromString("{}");
if (open_dict == NULL || close_dict == NULL || empty_dict == NULL)
return -1;
}
if (PyDict_Size(dct) == 0)
return PyList_Append(rval, empty_dict);
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(dct);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, dct)) {
goto bail;
}
}
if (PyList_Append(rval, open_dict))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
/* TODO: C speedup not implemented for sort_keys */
pos = 0;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
while (PyDict_Next(dct, &pos, &key, &value)) {
PyObject *encoded;
if (PyString_Check(key) || PyUnicode_Check(key)) {
Py_INCREF(key);
kstr = key;
}
else if (PyFloat_Check(key)) {
kstr = encoder_encode_float(s, key);
if (kstr == NULL)
goto bail;
}
else if (PyInt_Check(key) || PyLong_Check(key)) {
kstr = PyObject_Str(key);
if (kstr == NULL)
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
}
else if (skipkeys) {
continue;
}
else {
/* TODO: include repr of key */
PyErr_SetString(PyExc_ValueError, "keys must be a string");
goto bail;
}
if (idx) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
encoded = encoder_encode_string(s, kstr);
Py_CLEAR(kstr);
if (encoded == NULL)
goto bail;
if (PyList_Append(rval, encoded)) {
Py_DECREF(encoded);
goto bail;
}
Py_DECREF(encoded);
if (PyList_Append(rval, s->key_separator))
goto bail;
if (encoder_listencode_obj(s, rval, value, indent_level))
goto bail;
idx += 1;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_dict))
goto bail;
return 0;
bail:
Py_XDECREF(kstr);
Py_XDECREF(ident);
return -1;
}
static int
encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
{
/* Encode Python list seq to a JSON term, rval is a PyList */
static PyObject *open_array = NULL;
static PyObject *close_array = NULL;
static PyObject *empty_array = NULL;
PyObject *ident = NULL;
PyObject *s_fast = NULL;
Py_ssize_t num_items;
PyObject **seq_items;
Py_ssize_t i;
if (open_array == NULL || close_array == NULL || empty_array == NULL) {
open_array = PyString_InternFromString("[");
close_array = PyString_InternFromString("]");
empty_array = PyString_InternFromString("[]");
if (open_array == NULL || close_array == NULL || empty_array == NULL)
return -1;
}
ident = NULL;
s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence");
if (s_fast == NULL)
return -1;
num_items = PySequence_Fast_GET_SIZE(s_fast);
if (num_items == 0) {
Py_DECREF(s_fast);
return PyList_Append(rval, empty_array);
}
if (s->markers != Py_None) {
int has_key;
ident = PyLong_FromVoidPtr(seq);
if (ident == NULL)
goto bail;
has_key = PyDict_Contains(s->markers, ident);
if (has_key) {
if (has_key != -1)
PyErr_SetString(PyExc_ValueError, "Circular reference detected");
goto bail;
}
if (PyDict_SetItem(s->markers, ident, seq)) {
goto bail;
}
}
seq_items = PySequence_Fast_ITEMS(s_fast);
if (PyList_Append(rval, open_array))
goto bail;
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level += 1;
/*
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
*/
}
for (i = 0; i < num_items; i++) {
PyObject *obj = seq_items[i];
if (i) {
if (PyList_Append(rval, s->item_separator))
goto bail;
}
if (encoder_listencode_obj(s, rval, obj, indent_level))
goto bail;
}
if (ident != NULL) {
if (PyDict_DelItem(s->markers, ident))
goto bail;
Py_CLEAR(ident);
}
if (s->indent != Py_None) {
/* TODO: DOES NOT RUN */
indent_level -= 1;
/*
yield '\n' + (' ' * (_indent * _current_indent_level))
*/
}
if (PyList_Append(rval, close_array))
goto bail;
Py_DECREF(s_fast);
return 0;
bail:
Py_XDECREF(ident);
Py_DECREF(s_fast);
return -1;
}
static void
encoder_dealloc(PyObject *self)
{
/* Deallocate Encoder */
PyEncoderObject *s;
assert(PyEncoder_Check(self));
s = (PyEncoderObject *)self;
Py_CLEAR(s->markers);
Py_CLEAR(s->defaultfn);
Py_CLEAR(s->encoder);
Py_CLEAR(s->indent);
Py_CLEAR(s->key_separator);
Py_CLEAR(s->item_separator);
Py_CLEAR(s->sort_keys);
Py_CLEAR(s->skipkeys);
self->ob_type->tp_free(self);
}
PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
static
PyTypeObject PyEncoderType = {
PyObject_HEAD_INIT(0)
0, /* tp_internal */
"Encoder", /* tp_name */
sizeof(PyEncoderObject), /* tp_basicsize */
0, /* tp_itemsize */
encoder_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
encoder_call, /* tp_call */
0, /* tp_str */
0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
encoder_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
encoder_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
encoder_init, /* tp_init */
0,/* PyType_GenericAlloc, */ /* tp_alloc */
0,/* PyType_GenericNew, */ /* tp_new */
0,/* _PyObject_Del, */ /* tp_free */
};
static PyMethodDef speedups_methods[] = {
{"encode_basestring_ascii",
(PyCFunction)py_encode_basestring_ascii,
METH_O,
pydoc_encode_basestring_ascii},
{"scanstring",
(PyCFunction)py_scanstring,
METH_VARARGS,
pydoc_scanstring},
{NULL, NULL, 0, NULL}
};
PyDoc_STRVAR(module_doc,
"simplejson speedups\n");
void
init_speedups(void)
{
PyObject *m;
PyScannerType.tp_getattro = PyObject_GenericGetAttr;
PyScannerType.tp_setattro = PyObject_GenericSetAttr;
PyScannerType.tp_alloc = PyType_GenericAlloc;
PyScannerType.tp_new = PyType_GenericNew;
PyScannerType.tp_free = _PyObject_Del;
if (PyType_Ready(&PyScannerType) < 0)
return;
PyEncoderType.tp_getattro = PyObject_GenericGetAttr;
PyEncoderType.tp_setattro = PyObject_GenericSetAttr;
PyEncoderType.tp_alloc = PyType_GenericAlloc;
PyEncoderType.tp_new = PyType_GenericNew;
PyEncoderType.tp_free = _PyObject_Del;
if (PyType_Ready(&PyEncoderType) < 0)
return;
m = Py_InitModule3("_speedups", speedups_methods, module_doc);
Py_INCREF((PyObject*)&PyScannerType);
PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
Py_INCREF((PyObject*)&PyEncoderType);
PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
}
|
1101391i-python-twitter
|
simplejson/_speedups.c
|
C
|
asf20
| 75,169
|
"""Implementation of JSONDecoder
"""
import re
import sys
import struct
from simplejson.scanner import make_scanner
try:
from simplejson._speedups import scanstring as c_scanstring
except ImportError:
c_scanstring = None
__all__ = ['JSONDecoder']
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _floatconstants():
_BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
if sys.byteorder != 'big':
_BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
nan, inf = struct.unpack('dd', _BYTES)
return nan, inf, -inf
NaN, PosInf, NegInf = _floatconstants()
def linecol(doc, pos):
lineno = doc.count('\n', 0, pos) + 1
if lineno == 1:
colno = pos
else:
colno = pos - doc.rindex('\n', 0, pos)
return lineno, colno
def errmsg(msg, doc, pos, end=None):
# Note that this function is called from _speedups
lineno, colno = linecol(doc, pos)
if end is None:
return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)
endlineno, endcolno = linecol(doc, end)
return '%s: line %d column %d - line %d column %d (char %d - %d)' % (
msg, lineno, colno, endlineno, endcolno, pos, end)
_CONSTANTS = {
'-Infinity': NegInf,
'Infinity': PosInf,
'NaN': NaN,
}
STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
BACKSLASH = {
'"': u'"', '\\': u'\\', '/': u'/',
'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
}
DEFAULT_ENCODING = "utf-8"
def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
"""Scan the string s for a JSON string. End is the index of the
character in s after the quote that started the JSON string.
Unescapes all valid JSON string escape sequences and raises ValueError
on attempt to decode an invalid string. If strict is False then literal
control characters are allowed in the string.
Returns a tuple of the decoded string and the index of the character in s
after the end quote."""
if encoding is None:
encoding = DEFAULT_ENCODING
chunks = []
_append = chunks.append
begin = end - 1
while 1:
chunk = _m(s, end)
if chunk is None:
raise ValueError(
errmsg("Unterminated string starting at", s, begin))
end = chunk.end()
content, terminator = chunk.groups()
# Content is contains zero or more unescaped string characters
if content:
if not isinstance(content, unicode):
content = unicode(content, encoding)
_append(content)
# Terminator is the end of string, a literal control character,
# or a backslash denoting that an escape sequence follows
if terminator == '"':
break
elif terminator != '\\':
if strict:
msg = "Invalid control character %r at" % (terminator,)
raise ValueError(msg, s, end)
else:
_append(terminator)
continue
try:
esc = s[end]
except IndexError:
raise ValueError(
errmsg("Unterminated string starting at", s, begin))
# If not a unicode escape sequence, must be in the lookup table
if esc != 'u':
try:
char = _b[esc]
except KeyError:
raise ValueError(
errmsg("Invalid \\escape: %r" % (esc,), s, end))
end += 1
else:
# Unicode escape sequence
esc = s[end + 1:end + 5]
next_end = end + 5
if len(esc) != 4:
msg = "Invalid \\uXXXX escape"
raise ValueError(errmsg(msg, s, end))
uni = int(esc, 16)
# Check for surrogate pair on UCS-4 systems
if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
if not s[end + 5:end + 7] == '\\u':
raise ValueError(errmsg(msg, s, end))
esc2 = s[end + 7:end + 11]
if len(esc2) != 4:
raise ValueError(errmsg(msg, s, end))
uni2 = int(esc2, 16)
uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
next_end += 6
char = unichr(uni)
end = next_end
# Append the unescaped character
_append(char)
return u''.join(chunks), end
# Use speedup if available
scanstring = c_scanstring or py_scanstring
WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
WHITESPACE_STR = ' \t\n\r'
def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
pairs = {}
# Use a slice to prevent IndexError from being raised, the following
# check will raise a more specific ValueError if the string is empty
nextchar = s[end:end + 1]
# Normally we expect nextchar == '"'
if nextchar != '"':
if nextchar in _ws:
end = _w(s, end).end()
nextchar = s[end:end + 1]
# Trivial empty object
if nextchar == '}':
return pairs, end + 1
elif nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end))
end += 1
while True:
key, end = scanstring(s, end, encoding, strict)
# To skip some function call overhead we optimize the fast paths where
# the JSON key separator is ": " or just ":".
if s[end:end + 1] != ':':
end = _w(s, end).end()
if s[end:end + 1] != ':':
raise ValueError(errmsg("Expecting : delimiter", s, end))
end += 1
try:
if s[end] in _ws:
end += 1
if s[end] in _ws:
end = _w(s, end + 1).end()
except IndexError:
pass
try:
value, end = scan_once(s, end)
except StopIteration:
raise ValueError(errmsg("Expecting object", s, end))
pairs[key] = value
try:
nextchar = s[end]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end]
except IndexError:
nextchar = ''
end += 1
if nextchar == '}':
break
elif nextchar != ',':
raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
try:
nextchar = s[end]
if nextchar in _ws:
end += 1
nextchar = s[end]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end]
except IndexError:
nextchar = ''
end += 1
if nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end - 1))
if object_hook is not None:
pairs = object_hook(pairs)
return pairs, end
def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
values = []
nextchar = s[end:end + 1]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end:end + 1]
# Look-ahead for trivial empty array
if nextchar == ']':
return values, end + 1
_append = values.append
while True:
try:
value, end = scan_once(s, end)
except StopIteration:
raise ValueError(errmsg("Expecting object", s, end))
_append(value)
nextchar = s[end:end + 1]
if nextchar in _ws:
end = _w(s, end + 1).end()
nextchar = s[end:end + 1]
end += 1
if nextchar == ']':
break
elif nextchar != ',':
raise ValueError(errmsg("Expecting , delimiter", s, end))
try:
if s[end] in _ws:
end += 1
if s[end] in _ws:
end = _w(s, end + 1).end()
except IndexError:
pass
return values, end
class JSONDecoder(object):
"""Simple JSON <http://json.org> decoder
Performs the following translations in decoding by default:
+---------------+-------------------+
| JSON | Python |
+===============+===================+
| object | dict |
+---------------+-------------------+
| array | list |
+---------------+-------------------+
| string | unicode |
+---------------+-------------------+
| number (int) | int, long |
+---------------+-------------------+
| number (real) | float |
+---------------+-------------------+
| true | True |
+---------------+-------------------+
| false | False |
+---------------+-------------------+
| null | None |
+---------------+-------------------+
It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
their corresponding ``float`` values, which is outside the JSON spec.
"""
def __init__(self, encoding=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, strict=True):
"""``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook``, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given ``dict``. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
"""
self.encoding = encoding
self.object_hook = object_hook
self.parse_float = parse_float or float
self.parse_int = parse_int or int
self.parse_constant = parse_constant or _CONSTANTS.__getitem__
self.strict = strict
self.parse_object = JSONObject
self.parse_array = JSONArray
self.parse_string = scanstring
self.scan_once = make_scanner(self)
def decode(self, s, _w=WHITESPACE.match):
"""Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)
"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if end != len(s):
raise ValueError(errmsg("Extra data", s, end, len(s)))
return obj
def raw_decode(self, s, idx=0):
"""Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
try:
obj, end = self.scan_once(s, idx)
except StopIteration:
raise ValueError("No JSON object could be decoded")
return obj, end
|
1101391i-python-twitter
|
simplejson/decoder.py
|
Python
|
asf20
| 12,032
|
"""Implementation of JSONEncoder
"""
import re
try:
from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
except ImportError:
c_encode_basestring_ascii = None
try:
from simplejson._speedups import make_encoder as c_make_encoder
except ImportError:
c_make_encoder = None
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
HAS_UTF8 = re.compile(r'[\x80-\xff]')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
# Assume this produces an infinity on all machines (probably not guaranteed)
INFINITY = float('1e66666')
FLOAT_REPR = repr
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
def py_encode_basestring_ascii(s):
"""Return an ASCII-only JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
n = ord(s)
if n < 0x10000:
return '\\u%04x' % (n,)
else:
# surrogate pair
n -= 0x10000
s1 = 0xd800 | ((n >> 10) & 0x3ff)
s2 = 0xdc00 | (n & 0x3ff)
return '\\u%04x\\u%04x' % (s1, s2)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
class JSONEncoder(object):
"""Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
item_separator = ', '
key_separator = ': '
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is False, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is True, the output is guaranteed to be str
objects with all incoming unicode characters escaped. If
ensure_ascii is false, the output will be unicode object.
If check_circular is True, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is True, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is True, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (', ', ': '). To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
if default is not None:
self.default = default
self.encoding = encoding
def default(self, o):
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
"""
raise TypeError("%r is not JSON serializable" % (o,))
def encode(self, o):
"""Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if (_encoding is not None
and not (_encoding == 'utf-8')):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
return encode_basestring(o)
# This doesn't pass the iterator directly to ''.join() because the
# exceptions aren't as detailed. The list call should be roughly
# equivalent to the PySequence_Fast that ''.join() would do.
chunks = self.iterencode(o, _one_shot=True)
if not isinstance(chunks, (list, tuple)):
chunks = list(chunks)
return ''.join(chunks)
def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor- and/or
# platform-specific, so do tests which don't depend on the internals.
if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError("Out of range float values are not JSON compliant: %r"
% (o,))
return text
if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
_iterencode = c_make_encoder(
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
## HACK: hand-optimized bytecode; turn globals into locals
False=False,
True=True,
ValueError=ValueError,
basestring=basestring,
dict=dict,
float=float,
id=id,
int=int,
isinstance=isinstance,
list=list,
long=long,
str=str,
tuple=tuple,
):
def _iterencode_list(lst, _current_indent_level):
if not lst:
yield '[]'
return
if markers is not None:
markerid = id(lst)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = lst
buf = '['
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
else:
newline_indent = None
separator = _item_separator
first = True
for value in lst:
if first:
first = False
else:
buf = separator
if isinstance(value, basestring):
yield buf + _encoder(value)
elif value is None:
yield buf + 'null'
elif value is True:
yield buf + 'true'
elif value is False:
yield buf + 'false'
elif isinstance(value, (int, long)):
yield buf + str(value)
elif isinstance(value, float):
yield buf + _floatstr(value)
else:
yield buf
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield ']'
if markers is not None:
del markers[markerid]
def _iterencode_dict(dct, _current_indent_level):
if not dct:
yield '{}'
return
if markers is not None:
markerid = id(dct)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = dct
yield '{'
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
item_separator = _item_separator + newline_indent
yield newline_indent
else:
newline_indent = None
item_separator = _item_separator
first = True
if _sort_keys:
items = dct.items()
items.sort(key=lambda kv: kv[0])
else:
items = dct.iteritems()
for key, value in items:
if isinstance(key, basestring):
pass
# JavaScript is weakly typed for these, so it makes sense to
# also allow them. Many encoders seem to do something like this.
elif isinstance(key, float):
key = _floatstr(key)
elif isinstance(key, (int, long)):
key = str(key)
elif key is True:
key = 'true'
elif key is False:
key = 'false'
elif key is None:
key = 'null'
elif _skipkeys:
continue
else:
raise TypeError("key %r is not a string" % (key,))
if first:
first = False
else:
yield item_separator
yield _encoder(key)
yield _key_separator
if isinstance(value, basestring):
yield _encoder(value)
elif value is None:
yield 'null'
elif value is True:
yield 'true'
elif value is False:
yield 'false'
elif isinstance(value, (int, long)):
yield str(value)
elif isinstance(value, float):
yield _floatstr(value)
else:
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield '}'
if markers is not None:
del markers[markerid]
def _iterencode(o, _current_indent_level):
if isinstance(o, basestring):
yield _encoder(o)
elif o is None:
yield 'null'
elif o is True:
yield 'true'
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
yield str(o)
elif isinstance(o, float):
yield _floatstr(o)
elif isinstance(o, (list, tuple)):
for chunk in _iterencode_list(o, _current_indent_level):
yield chunk
elif isinstance(o, dict):
for chunk in _iterencode_dict(o, _current_indent_level):
yield chunk
else:
if markers is not None:
markerid = id(o)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = o
o = _default(o)
for chunk in _iterencode(o, _current_indent_level):
yield chunk
if markers is not None:
del markers[markerid]
return _iterencode
|
1101391i-python-twitter
|
simplejson/encoder.py
|
Python
|
asf20
| 15,836
|
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`simplejson` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of the :mod:`json` library contained in Python 2.6, but maintains
compatibility with Python 2.4 and Python 2.5 and (currently) has
significant performance advantages, even without using the optional C
extension for speedups.
Encoding basic Python object hierarchies::
>>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import simplejson as json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import simplejson as json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
>>> print '\n'.join([l.rstrip() for l in s.splitlines()])
{
"4": 5,
"6": 7
}
Decoding JSON::
>>> import simplejson as json
>>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
Specializing JSON object decoding::
>>> import simplejson as json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1')
True
Specializing JSON object encoding::
>>> import simplejson as json
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... raise TypeError("%r is not JSON serializable" % (o,))
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'
Using simplejson.tool from the shell to validate and pretty-print::
$ echo '{"json":"obj"}' | python -msimplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -msimplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
__version__ = '2.0.7'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONEncoder',
]
from decoder import JSONDecoder
from encoder import JSONEncoder
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
encoding='utf-8',
default=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and object
members will be pretty-printed with that indent level. An indent level
of 0 will only insert newlines. ``None`` is the most compact representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding,
default=default, **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (skipkeys is False and ensure_ascii is True and
check_circular is True and allow_nan is True and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
**kw).encode(obj)
_default_decoder = JSONDecoder(encoding=None, object_hook=None)
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
return loads(fp.read(),
encoding=encoding, cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, **kw)
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(encoding=encoding, **kw).decode(s)
|
1101391i-python-twitter
|
simplejson/__init__.py
|
Python
|
asf20
| 12,503
|
r"""Using simplejson from the shell to validate and
pretty-print::
$ echo '{"json":"obj"}' | python -msimplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -msimplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
import simplejson
def main():
import sys
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit("%s [infile [outfile]]" % (sys.argv[0],))
try:
obj = simplejson.load(infile)
except ValueError, e:
raise SystemExit(e)
simplejson.dump(obj, outfile, sort_keys=True, indent=4)
outfile.write('\n')
if __name__ == '__main__':
main()
|
1101391i-python-twitter
|
simplejson/tool.py
|
Python
|
asf20
| 908
|
#!/usr/bin/python2.4
#
# Copyright 2007 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''The setup and build script for the python-twitter library.'''
__author__ = 'python-twitter@googlegroups.com'
__version__ = '0.8.5'
# The base package metadata to be used by both distutils and setuptools
METADATA = dict(
name = "python-twitter",
version = __version__,
py_modules = ['twitter'],
author='The Python-Twitter Developers',
author_email='python-twitter@googlegroups.com',
description='A python wrapper around the Twitter API',
license='Apache License 2.0',
url='https://github.com/bear/python-twitter',
keywords='twitter api',
)
# Extra package metadata to be used only if setuptools is installed
SETUPTOOLS_METADATA = dict(
install_requires = ['setuptools', 'simplejson', 'oauth2'],
include_package_data = True,
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet',
],
test_suite = 'twitter_test.suite',
)
def Read(file):
return open(file).read()
def BuildLongDescription():
return '\n'.join([Read('README.md'), Read('CHANGES')])
def Main():
# Build the long_description from the README and CHANGES
METADATA['long_description'] = BuildLongDescription()
# Use setuptools if available, otherwise fallback and use distutils
try:
import setuptools
METADATA.update(SETUPTOOLS_METADATA)
setuptools.setup(**METADATA)
except ImportError:
import distutils.core
distutils.core.setup(**METADATA)
if __name__ == '__main__':
Main()
|
1101391i-python-twitter
|
setup.py
|
Python
|
asf20
| 2,254
|
#!/usr/bin/python2.4
#
# Copyright 2007 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''A library that provides a Python interface to the Twitter API'''
__author__ = 'python-twitter@googlegroups.com'
__version__ = '0.8.5'
import calendar
import datetime
import httplib
import os
import rfc822
import sys
import tempfile
import textwrap
import time
import urllib
import urllib2
import urlparse
import gzip
import StringIO
try:
# Python >= 2.6
import json as simplejson
except ImportError:
try:
# Python < 2.6
import simplejson
except ImportError:
try:
# Google App Engine
from django.utils import simplejson
except ImportError:
raise ImportError, "Unable to load a json library"
# parse_qsl moved to urlparse module in v2.6
try:
from urlparse import parse_qsl, parse_qs
except ImportError:
from cgi import parse_qsl, parse_qs
try:
from hashlib import md5
except ImportError:
from md5 import md5
import oauth2 as oauth
CHARACTER_LIMIT = 140
# A singleton representing a lazily instantiated FileCache.
DEFAULT_CACHE = object()
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token'
AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize'
SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate'
class TwitterError(Exception):
'''Base class for Twitter errors'''
@property
def message(self):
'''Returns the first argument used to construct this error.'''
return self.args[0]
class Status(object):
'''A class representing the Status structure used by the twitter API.
The Status structure exposes the following properties:
status.created_at
status.created_at_in_seconds # read only
status.favorited
status.in_reply_to_screen_name
status.in_reply_to_user_id
status.in_reply_to_status_id
status.truncated
status.source
status.id
status.text
status.location
status.relative_created_at # read only
status.user
status.urls
status.user_mentions
status.hashtags
status.geo
status.place
status.coordinates
status.contributors
'''
def __init__(self,
created_at=None,
favorited=None,
id=None,
text=None,
location=None,
user=None,
in_reply_to_screen_name=None,
in_reply_to_user_id=None,
in_reply_to_status_id=None,
truncated=None,
source=None,
now=None,
urls=None,
user_mentions=None,
hashtags=None,
media=None,
geo=None,
place=None,
coordinates=None,
contributors=None,
retweeted=None,
retweeted_status=None,
retweet_count=None):
'''An object to hold a Twitter status message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
created_at:
The time this status message was posted. [Optional]
favorited:
Whether this is a favorite of the authenticated user. [Optional]
id:
The unique id of this status message. [Optional]
text:
The text of this status message. [Optional]
location:
the geolocation string associated with this message. [Optional]
relative_created_at:
A human readable string representing the posting time. [Optional]
user:
A twitter.User instance representing the person posting the
message. [Optional]
now:
The current time, if the client chooses to set it.
Defaults to the wall clock time. [Optional]
urls:
user_mentions:
hashtags:
geo:
place:
coordinates:
contributors:
retweeted:
retweeted_status:
retweet_count:
'''
self.created_at = created_at
self.favorited = favorited
self.id = id
self.text = text
self.location = location
self.user = user
self.now = now
self.in_reply_to_screen_name = in_reply_to_screen_name
self.in_reply_to_user_id = in_reply_to_user_id
self.in_reply_to_status_id = in_reply_to_status_id
self.truncated = truncated
self.retweeted = retweeted
self.source = source
self.urls = urls
self.user_mentions = user_mentions
self.hashtags = hashtags
self.media = media
self.geo = geo
self.place = place
self.coordinates = coordinates
self.contributors = contributors
self.retweeted_status = retweeted_status
self.retweet_count = retweet_count
def GetCreatedAt(self):
'''Get the time this status message was posted.
Returns:
The time this status message was posted
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set the time this status message was posted.
Args:
created_at:
The time this status message was created
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The time this status message was posted.')
def GetCreatedAtInSeconds(self):
'''Get the time this status message was posted, in seconds since the epoch.
Returns:
The time this status message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
created_at_in_seconds = property(GetCreatedAtInSeconds,
doc="The time this status message was "
"posted, in seconds since the epoch")
def GetFavorited(self):
'''Get the favorited setting of this status message.
Returns:
True if this status message is favorited; False otherwise
'''
return self._favorited
def SetFavorited(self, favorited):
'''Set the favorited state of this status message.
Args:
favorited:
boolean True/False favorited state of this status message
'''
self._favorited = favorited
favorited = property(GetFavorited, SetFavorited,
doc='The favorited state of this status message.')
def GetId(self):
'''Get the unique id of this status message.
Returns:
The unique id of this status message
'''
return self._id
def SetId(self, id):
'''Set the unique id of this status message.
Args:
id:
The unique id of this status message
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this status message.')
def GetInReplyToScreenName(self):
return self._in_reply_to_screen_name
def SetInReplyToScreenName(self, in_reply_to_screen_name):
self._in_reply_to_screen_name = in_reply_to_screen_name
in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName,
doc='')
def GetInReplyToUserId(self):
return self._in_reply_to_user_id
def SetInReplyToUserId(self, in_reply_to_user_id):
self._in_reply_to_user_id = in_reply_to_user_id
in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId,
doc='')
def GetInReplyToStatusId(self):
return self._in_reply_to_status_id
def SetInReplyToStatusId(self, in_reply_to_status_id):
self._in_reply_to_status_id = in_reply_to_status_id
in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId,
doc='')
def GetTruncated(self):
return self._truncated
def SetTruncated(self, truncated):
self._truncated = truncated
truncated = property(GetTruncated, SetTruncated,
doc='')
def GetRetweeted(self):
return self._retweeted
def SetRetweeted(self, retweeted):
self._retweeted = retweeted
retweeted = property(GetRetweeted, SetRetweeted,
doc='')
def GetSource(self):
return self._source
def SetSource(self, source):
self._source = source
source = property(GetSource, SetSource,
doc='')
def GetText(self):
'''Get the text of this status message.
Returns:
The text of this status message.
'''
return self._text
def SetText(self, text):
'''Set the text of this status message.
Args:
text:
The text of this status message
'''
self._text = text
text = property(GetText, SetText,
doc='The text of this status message')
def GetLocation(self):
'''Get the geolocation associated with this status message
Returns:
The geolocation string of this status message.
'''
return self._location
def SetLocation(self, location):
'''Set the geolocation associated with this status message
Args:
location:
The geolocation string of this status message
'''
self._location = location
location = property(GetLocation, SetLocation,
doc='The geolocation string of this status message')
def GetRelativeCreatedAt(self):
'''Get a human readable string representing the posting time
Returns:
A human readable string representing the posting time
'''
fudge = 1.25
delta = long(self.now) - long(self.created_at_in_seconds)
if delta < (1 * fudge):
return 'about a second ago'
elif delta < (60 * (1/fudge)):
return 'about %d seconds ago' % (delta)
elif delta < (60 * fudge):
return 'about a minute ago'
elif delta < (60 * 60 * (1/fudge)):
return 'about %d minutes ago' % (delta / 60)
elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1:
return 'about an hour ago'
elif delta < (60 * 60 * 24 * (1/fudge)):
return 'about %d hours ago' % (delta / (60 * 60))
elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1:
return 'about a day ago'
else:
return 'about %d days ago' % (delta / (60 * 60 * 24))
relative_created_at = property(GetRelativeCreatedAt,
doc='Get a human readable string representing '
'the posting time')
def GetUser(self):
'''Get a twitter.User representing the entity posting this status message.
Returns:
A twitter.User representing the entity posting this status message
'''
return self._user
def SetUser(self, user):
'''Set a twitter.User representing the entity posting this status message.
Args:
user:
A twitter.User representing the entity posting this status message
'''
self._user = user
user = property(GetUser, SetUser,
doc='A twitter.User representing the entity posting this '
'status message')
def GetNow(self):
'''Get the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Returns:
Whatever the status instance believes the current time to be,
in seconds since the epoch.
'''
if self._now is None:
self._now = time.time()
return self._now
def SetNow(self, now):
'''Set the wallclock time for this status message.
Used to calculate relative_created_at. Defaults to the time
the object was instantiated.
Args:
now:
The wallclock time for this instance.
'''
self._now = now
now = property(GetNow, SetNow,
doc='The wallclock time for this status instance.')
def GetGeo(self):
return self._geo
def SetGeo(self, geo):
self._geo = geo
geo = property(GetGeo, SetGeo,
doc='')
def GetPlace(self):
return self._place
def SetPlace(self, place):
self._place = place
place = property(GetPlace, SetPlace,
doc='')
def GetCoordinates(self):
return self._coordinates
def SetCoordinates(self, coordinates):
self._coordinates = coordinates
coordinates = property(GetCoordinates, SetCoordinates,
doc='')
def GetContributors(self):
return self._contributors
def SetContributors(self, contributors):
self._contributors = contributors
contributors = property(GetContributors, SetContributors,
doc='')
def GetRetweeted_status(self):
return self._retweeted_status
def SetRetweeted_status(self, retweeted_status):
self._retweeted_status = retweeted_status
retweeted_status = property(GetRetweeted_status, SetRetweeted_status,
doc='')
def GetRetweetCount(self):
return self._retweet_count
def SetRetweetCount(self, retweet_count):
self._retweet_count = retweet_count
retweet_count = property(GetRetweetCount, SetRetweetCount,
doc='')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.created_at == other.created_at and \
self.id == other.id and \
self.text == other.text and \
self.location == other.location and \
self.user == other.user and \
self.in_reply_to_screen_name == other.in_reply_to_screen_name and \
self.in_reply_to_user_id == other.in_reply_to_user_id and \
self.in_reply_to_status_id == other.in_reply_to_status_id and \
self.truncated == other.truncated and \
self.retweeted == other.retweeted and \
self.favorited == other.favorited and \
self.source == other.source and \
self.geo == other.geo and \
self.place == other.place and \
self.coordinates == other.coordinates and \
self.contributors == other.contributors and \
self.retweeted_status == other.retweeted_status and \
self.retweet_count == other.retweet_count
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.Status instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.Status instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.Status instance.
Returns:
A JSON string representation of this twitter.Status instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.Status instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.Status instance
'''
data = {}
if self.created_at:
data['created_at'] = self.created_at
if self.favorited:
data['favorited'] = self.favorited
if self.id:
data['id'] = self.id
if self.text:
data['text'] = self.text
if self.location:
data['location'] = self.location
if self.user:
data['user'] = self.user.AsDict()
if self.in_reply_to_screen_name:
data['in_reply_to_screen_name'] = self.in_reply_to_screen_name
if self.in_reply_to_user_id:
data['in_reply_to_user_id'] = self.in_reply_to_user_id
if self.in_reply_to_status_id:
data['in_reply_to_status_id'] = self.in_reply_to_status_id
if self.truncated is not None:
data['truncated'] = self.truncated
if self.retweeted is not None:
data['retweeted'] = self.retweeted
if self.favorited is not None:
data['favorited'] = self.favorited
if self.source:
data['source'] = self.source
if self.geo:
data['geo'] = self.geo
if self.place:
data['place'] = self.place
if self.coordinates:
data['coordinates'] = self.coordinates
if self.contributors:
data['contributors'] = self.contributors
if self.hashtags:
data['hashtags'] = [h.text for h in self.hashtags]
if self.retweeted_status:
data['retweeted_status'] = self.retweeted_status.AsDict()
if self.retweet_count:
data['retweet_count'] = self.retweet_count
if self.urls:
data['urls'] = dict([(url.url, url.expanded_url) for url in self.urls])
if self.user_mentions:
data['user_mentions'] = [um.AsDict() for um in self.user_mentions]
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data: A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Status instance
'''
if 'user' in data:
user = User.NewFromJsonDict(data['user'])
else:
user = None
if 'retweeted_status' in data:
retweeted_status = Status.NewFromJsonDict(data['retweeted_status'])
else:
retweeted_status = None
urls = None
user_mentions = None
hashtags = None
media = None
if 'entities' in data:
if 'urls' in data['entities']:
urls = [Url.NewFromJsonDict(u) for u in data['entities']['urls']]
if 'user_mentions' in data['entities']:
user_mentions = [User.NewFromJsonDict(u) for u in data['entities']['user_mentions']]
if 'hashtags' in data['entities']:
hashtags = [Hashtag.NewFromJsonDict(h) for h in data['entities']['hashtags']]
if 'media' in data['entities']:
media = data['entities']['media']
else:
media = []
return Status(created_at=data.get('created_at', None),
favorited=data.get('favorited', None),
id=data.get('id', None),
text=data.get('text', None),
location=data.get('location', None),
in_reply_to_screen_name=data.get('in_reply_to_screen_name', None),
in_reply_to_user_id=data.get('in_reply_to_user_id', None),
in_reply_to_status_id=data.get('in_reply_to_status_id', None),
truncated=data.get('truncated', None),
retweeted=data.get('retweeted', None),
source=data.get('source', None),
user=user,
urls=urls,
user_mentions=user_mentions,
hashtags=hashtags,
media=media,
geo=data.get('geo', None),
place=data.get('place', None),
coordinates=data.get('coordinates', None),
contributors=data.get('contributors', None),
retweeted_status=retweeted_status,
retweet_count=data.get('retweet_count', None))
class User(object):
'''A class representing the User structure used by the twitter API.
The User structure exposes the following properties:
user.id
user.name
user.screen_name
user.location
user.description
user.profile_image_url
user.profile_background_tile
user.profile_background_image_url
user.profile_sidebar_fill_color
user.profile_background_color
user.profile_link_color
user.profile_text_color
user.protected
user.utc_offset
user.time_zone
user.url
user.status
user.statuses_count
user.followers_count
user.friends_count
user.favourites_count
user.geo_enabled
user.verified
user.lang
user.notifications
user.contributors_enabled
user.created_at
user.listed_count
'''
def __init__(self,
id=None,
name=None,
screen_name=None,
location=None,
description=None,
profile_image_url=None,
profile_background_tile=None,
profile_background_image_url=None,
profile_sidebar_fill_color=None,
profile_background_color=None,
profile_link_color=None,
profile_text_color=None,
protected=None,
utc_offset=None,
time_zone=None,
followers_count=None,
friends_count=None,
statuses_count=None,
favourites_count=None,
url=None,
status=None,
geo_enabled=None,
verified=None,
lang=None,
notifications=None,
contributors_enabled=None,
created_at=None,
listed_count=None):
self.id = id
self.name = name
self.screen_name = screen_name
self.location = location
self.description = description
self.profile_image_url = profile_image_url
self.profile_background_tile = profile_background_tile
self.profile_background_image_url = profile_background_image_url
self.profile_sidebar_fill_color = profile_sidebar_fill_color
self.profile_background_color = profile_background_color
self.profile_link_color = profile_link_color
self.profile_text_color = profile_text_color
self.protected = protected
self.utc_offset = utc_offset
self.time_zone = time_zone
self.followers_count = followers_count
self.friends_count = friends_count
self.statuses_count = statuses_count
self.favourites_count = favourites_count
self.url = url
self.status = status
self.geo_enabled = geo_enabled
self.verified = verified
self.lang = lang
self.notifications = notifications
self.contributors_enabled = contributors_enabled
self.created_at = created_at
self.listed_count = listed_count
def GetId(self):
'''Get the unique id of this user.
Returns:
The unique id of this user
'''
return self._id
def SetId(self, id):
'''Set the unique id of this user.
Args:
id: The unique id of this user.
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this user.')
def GetName(self):
'''Get the real name of this user.
Returns:
The real name of this user
'''
return self._name
def SetName(self, name):
'''Set the real name of this user.
Args:
name: The real name of this user
'''
self._name = name
name = property(GetName, SetName,
doc='The real name of this user.')
def GetScreenName(self):
'''Get the short twitter name of this user.
Returns:
The short twitter name of this user
'''
return self._screen_name
def SetScreenName(self, screen_name):
'''Set the short twitter name of this user.
Args:
screen_name: the short twitter name of this user
'''
self._screen_name = screen_name
screen_name = property(GetScreenName, SetScreenName,
doc='The short twitter name of this user.')
def GetLocation(self):
'''Get the geographic location of this user.
Returns:
The geographic location of this user
'''
return self._location
def SetLocation(self, location):
'''Set the geographic location of this user.
Args:
location: The geographic location of this user
'''
self._location = location
location = property(GetLocation, SetLocation,
doc='The geographic location of this user.')
def GetDescription(self):
'''Get the short text description of this user.
Returns:
The short text description of this user
'''
return self._description
def SetDescription(self, description):
'''Set the short text description of this user.
Args:
description: The short text description of this user
'''
self._description = description
description = property(GetDescription, SetDescription,
doc='The short text description of this user.')
def GetUrl(self):
'''Get the homepage url of this user.
Returns:
The homepage url of this user
'''
return self._url
def SetUrl(self, url):
'''Set the homepage url of this user.
Args:
url: The homepage url of this user
'''
self._url = url
url = property(GetUrl, SetUrl,
doc='The homepage url of this user.')
def GetProfileImageUrl(self):
'''Get the url of the thumbnail of this user.
Returns:
The url of the thumbnail of this user
'''
return self._profile_image_url
def SetProfileImageUrl(self, profile_image_url):
'''Set the url of the thumbnail of this user.
Args:
profile_image_url: The url of the thumbnail of this user
'''
self._profile_image_url = profile_image_url
profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl,
doc='The url of the thumbnail of this user.')
def GetProfileBackgroundTile(self):
'''Boolean for whether to tile the profile background image.
Returns:
True if the background is to be tiled, False if not, None if unset.
'''
return self._profile_background_tile
def SetProfileBackgroundTile(self, profile_background_tile):
'''Set the boolean flag for whether to tile the profile background image.
Args:
profile_background_tile: Boolean flag for whether to tile or not.
'''
self._profile_background_tile = profile_background_tile
profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile,
doc='Boolean for whether to tile the background image.')
def GetProfileBackgroundImageUrl(self):
return self._profile_background_image_url
def SetProfileBackgroundImageUrl(self, profile_background_image_url):
self._profile_background_image_url = profile_background_image_url
profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl,
doc='The url of the profile background of this user.')
def GetProfileSidebarFillColor(self):
return self._profile_sidebar_fill_color
def SetProfileSidebarFillColor(self, profile_sidebar_fill_color):
self._profile_sidebar_fill_color = profile_sidebar_fill_color
profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor)
def GetProfileBackgroundColor(self):
return self._profile_background_color
def SetProfileBackgroundColor(self, profile_background_color):
self._profile_background_color = profile_background_color
profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor)
def GetProfileLinkColor(self):
return self._profile_link_color
def SetProfileLinkColor(self, profile_link_color):
self._profile_link_color = profile_link_color
profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor)
def GetProfileTextColor(self):
return self._profile_text_color
def SetProfileTextColor(self, profile_text_color):
self._profile_text_color = profile_text_color
profile_text_color = property(GetProfileTextColor, SetProfileTextColor)
def GetProtected(self):
return self._protected
def SetProtected(self, protected):
self._protected = protected
protected = property(GetProtected, SetProtected)
def GetUtcOffset(self):
return self._utc_offset
def SetUtcOffset(self, utc_offset):
self._utc_offset = utc_offset
utc_offset = property(GetUtcOffset, SetUtcOffset)
def GetTimeZone(self):
'''Returns the current time zone string for the user.
Returns:
The descriptive time zone string for the user.
'''
return self._time_zone
def SetTimeZone(self, time_zone):
'''Sets the user's time zone string.
Args:
time_zone:
The descriptive time zone to assign for the user.
'''
self._time_zone = time_zone
time_zone = property(GetTimeZone, SetTimeZone)
def GetStatus(self):
'''Get the latest twitter.Status of this user.
Returns:
The latest twitter.Status of this user
'''
return self._status
def SetStatus(self, status):
'''Set the latest twitter.Status of this user.
Args:
status:
The latest twitter.Status of this user
'''
self._status = status
status = property(GetStatus, SetStatus,
doc='The latest twitter.Status of this user.')
def GetFriendsCount(self):
'''Get the friend count for this user.
Returns:
The number of users this user has befriended.
'''
return self._friends_count
def SetFriendsCount(self, count):
'''Set the friend count for this user.
Args:
count:
The number of users this user has befriended.
'''
self._friends_count = count
friends_count = property(GetFriendsCount, SetFriendsCount,
doc='The number of friends for this user.')
def GetListedCount(self):
'''Get the listed count for this user.
Returns:
The number of lists this user belongs to.
'''
return self._listed_count
def SetListedCount(self, count):
'''Set the listed count for this user.
Args:
count:
The number of lists this user belongs to.
'''
self._listed_count = count
listed_count = property(GetListedCount, SetListedCount,
doc='The number of lists this user belongs to.')
def GetFollowersCount(self):
'''Get the follower count for this user.
Returns:
The number of users following this user.
'''
return self._followers_count
def SetFollowersCount(self, count):
'''Set the follower count for this user.
Args:
count:
The number of users following this user.
'''
self._followers_count = count
followers_count = property(GetFollowersCount, SetFollowersCount,
doc='The number of users following this user.')
def GetStatusesCount(self):
'''Get the number of status updates for this user.
Returns:
The number of status updates for this user.
'''
return self._statuses_count
def SetStatusesCount(self, count):
'''Set the status update count for this user.
Args:
count:
The number of updates for this user.
'''
self._statuses_count = count
statuses_count = property(GetStatusesCount, SetStatusesCount,
doc='The number of updates for this user.')
def GetFavouritesCount(self):
'''Get the number of favourites for this user.
Returns:
The number of favourites for this user.
'''
return self._favourites_count
def SetFavouritesCount(self, count):
'''Set the favourite count for this user.
Args:
count:
The number of favourites for this user.
'''
self._favourites_count = count
favourites_count = property(GetFavouritesCount, SetFavouritesCount,
doc='The number of favourites for this user.')
def GetGeoEnabled(self):
'''Get the setting of geo_enabled for this user.
Returns:
True/False if Geo tagging is enabled
'''
return self._geo_enabled
def SetGeoEnabled(self, geo_enabled):
'''Set the latest twitter.geo_enabled of this user.
Args:
geo_enabled:
True/False if Geo tagging is to be enabled
'''
self._geo_enabled = geo_enabled
geo_enabled = property(GetGeoEnabled, SetGeoEnabled,
doc='The value of twitter.geo_enabled for this user.')
def GetVerified(self):
'''Get the setting of verified for this user.
Returns:
True/False if user is a verified account
'''
return self._verified
def SetVerified(self, verified):
'''Set twitter.verified for this user.
Args:
verified:
True/False if user is a verified account
'''
self._verified = verified
verified = property(GetVerified, SetVerified,
doc='The value of twitter.verified for this user.')
def GetLang(self):
'''Get the setting of lang for this user.
Returns:
language code of the user
'''
return self._lang
def SetLang(self, lang):
'''Set twitter.lang for this user.
Args:
lang:
language code for the user
'''
self._lang = lang
lang = property(GetLang, SetLang,
doc='The value of twitter.lang for this user.')
def GetNotifications(self):
'''Get the setting of notifications for this user.
Returns:
True/False for the notifications setting of the user
'''
return self._notifications
def SetNotifications(self, notifications):
'''Set twitter.notifications for this user.
Args:
notifications:
True/False notifications setting for the user
'''
self._notifications = notifications
notifications = property(GetNotifications, SetNotifications,
doc='The value of twitter.notifications for this user.')
def GetContributorsEnabled(self):
'''Get the setting of contributors_enabled for this user.
Returns:
True/False contributors_enabled of the user
'''
return self._contributors_enabled
def SetContributorsEnabled(self, contributors_enabled):
'''Set twitter.contributors_enabled for this user.
Args:
contributors_enabled:
True/False contributors_enabled setting for the user
'''
self._contributors_enabled = contributors_enabled
contributors_enabled = property(GetContributorsEnabled, SetContributorsEnabled,
doc='The value of twitter.contributors_enabled for this user.')
def GetCreatedAt(self):
'''Get the setting of created_at for this user.
Returns:
created_at value of the user
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set twitter.created_at for this user.
Args:
created_at:
created_at value for the user
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The value of twitter.created_at for this user.')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.name == other.name and \
self.screen_name == other.screen_name and \
self.location == other.location and \
self.description == other.description and \
self.profile_image_url == other.profile_image_url and \
self.profile_background_tile == other.profile_background_tile and \
self.profile_background_image_url == other.profile_background_image_url and \
self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \
self.profile_background_color == other.profile_background_color and \
self.profile_link_color == other.profile_link_color and \
self.profile_text_color == other.profile_text_color and \
self.protected == other.protected and \
self.utc_offset == other.utc_offset and \
self.time_zone == other.time_zone and \
self.url == other.url and \
self.statuses_count == other.statuses_count and \
self.followers_count == other.followers_count and \
self.favourites_count == other.favourites_count and \
self.friends_count == other.friends_count and \
self.status == other.status and \
self.geo_enabled == other.geo_enabled and \
self.verified == other.verified and \
self.lang == other.lang and \
self.notifications == other.notifications and \
self.contributors_enabled == other.contributors_enabled and \
self.created_at == other.created_at and \
self.listed_count == other.listed_count
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.User instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.User instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.User instance.
Returns:
A JSON string representation of this twitter.User instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.User instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.User instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.name:
data['name'] = self.name
if self.screen_name:
data['screen_name'] = self.screen_name
if self.location:
data['location'] = self.location
if self.description:
data['description'] = self.description
if self.profile_image_url:
data['profile_image_url'] = self.profile_image_url
if self.profile_background_tile is not None:
data['profile_background_tile'] = self.profile_background_tile
if self.profile_background_image_url:
data['profile_sidebar_fill_color'] = self.profile_background_image_url
if self.profile_background_color:
data['profile_background_color'] = self.profile_background_color
if self.profile_link_color:
data['profile_link_color'] = self.profile_link_color
if self.profile_text_color:
data['profile_text_color'] = self.profile_text_color
if self.protected is not None:
data['protected'] = self.protected
if self.utc_offset:
data['utc_offset'] = self.utc_offset
if self.time_zone:
data['time_zone'] = self.time_zone
if self.url:
data['url'] = self.url
if self.status:
data['status'] = self.status.AsDict()
if self.friends_count:
data['friends_count'] = self.friends_count
if self.followers_count:
data['followers_count'] = self.followers_count
if self.statuses_count:
data['statuses_count'] = self.statuses_count
if self.favourites_count:
data['favourites_count'] = self.favourites_count
if self.geo_enabled:
data['geo_enabled'] = self.geo_enabled
if self.verified:
data['verified'] = self.verified
if self.lang:
data['lang'] = self.lang
if self.notifications:
data['notifications'] = self.notifications
if self.contributors_enabled:
data['contributors_enabled'] = self.contributors_enabled
if self.created_at:
data['created_at'] = self.created_at
if self.listed_count:
data['listed_count'] = self.listed_count
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.User instance
'''
if 'status' in data:
status = Status.NewFromJsonDict(data['status'])
else:
status = None
return User(id=data.get('id', None),
name=data.get('name', None),
screen_name=data.get('screen_name', None),
location=data.get('location', None),
description=data.get('description', None),
statuses_count=data.get('statuses_count', None),
followers_count=data.get('followers_count', None),
favourites_count=data.get('favourites_count', None),
friends_count=data.get('friends_count', None),
profile_image_url=data.get('profile_image_url', None),
profile_background_tile = data.get('profile_background_tile', None),
profile_background_image_url = data.get('profile_background_image_url', None),
profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None),
profile_background_color = data.get('profile_background_color', None),
profile_link_color = data.get('profile_link_color', None),
profile_text_color = data.get('profile_text_color', None),
protected = data.get('protected', None),
utc_offset = data.get('utc_offset', None),
time_zone = data.get('time_zone', None),
url=data.get('url', None),
status=status,
geo_enabled=data.get('geo_enabled', None),
verified=data.get('verified', None),
lang=data.get('lang', None),
notifications=data.get('notifications', None),
contributors_enabled=data.get('contributors_enabled', None),
created_at=data.get('created_at', None),
listed_count=data.get('listed_count', None))
class List(object):
'''A class representing the List structure used by the twitter API.
The List structure exposes the following properties:
list.id
list.name
list.slug
list.description
list.full_name
list.mode
list.uri
list.member_count
list.subscriber_count
list.following
'''
def __init__(self,
id=None,
name=None,
slug=None,
description=None,
full_name=None,
mode=None,
uri=None,
member_count=None,
subscriber_count=None,
following=None,
user=None):
self.id = id
self.name = name
self.slug = slug
self.description = description
self.full_name = full_name
self.mode = mode
self.uri = uri
self.member_count = member_count
self.subscriber_count = subscriber_count
self.following = following
self.user = user
def GetId(self):
'''Get the unique id of this list.
Returns:
The unique id of this list
'''
return self._id
def SetId(self, id):
'''Set the unique id of this list.
Args:
id:
The unique id of this list.
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this list.')
def GetName(self):
'''Get the real name of this list.
Returns:
The real name of this list
'''
return self._name
def SetName(self, name):
'''Set the real name of this list.
Args:
name:
The real name of this list
'''
self._name = name
name = property(GetName, SetName,
doc='The real name of this list.')
def GetSlug(self):
'''Get the slug of this list.
Returns:
The slug of this list
'''
return self._slug
def SetSlug(self, slug):
'''Set the slug of this list.
Args:
slug:
The slug of this list.
'''
self._slug = slug
slug = property(GetSlug, SetSlug,
doc='The slug of this list.')
def GetDescription(self):
'''Get the description of this list.
Returns:
The description of this list
'''
return self._description
def SetDescription(self, description):
'''Set the description of this list.
Args:
description:
The description of this list.
'''
self._description = description
description = property(GetDescription, SetDescription,
doc='The description of this list.')
def GetFull_name(self):
'''Get the full_name of this list.
Returns:
The full_name of this list
'''
return self._full_name
def SetFull_name(self, full_name):
'''Set the full_name of this list.
Args:
full_name:
The full_name of this list.
'''
self._full_name = full_name
full_name = property(GetFull_name, SetFull_name,
doc='The full_name of this list.')
def GetMode(self):
'''Get the mode of this list.
Returns:
The mode of this list
'''
return self._mode
def SetMode(self, mode):
'''Set the mode of this list.
Args:
mode:
The mode of this list.
'''
self._mode = mode
mode = property(GetMode, SetMode,
doc='The mode of this list.')
def GetUri(self):
'''Get the uri of this list.
Returns:
The uri of this list
'''
return self._uri
def SetUri(self, uri):
'''Set the uri of this list.
Args:
uri:
The uri of this list.
'''
self._uri = uri
uri = property(GetUri, SetUri,
doc='The uri of this list.')
def GetMember_count(self):
'''Get the member_count of this list.
Returns:
The member_count of this list
'''
return self._member_count
def SetMember_count(self, member_count):
'''Set the member_count of this list.
Args:
member_count:
The member_count of this list.
'''
self._member_count = member_count
member_count = property(GetMember_count, SetMember_count,
doc='The member_count of this list.')
def GetSubscriber_count(self):
'''Get the subscriber_count of this list.
Returns:
The subscriber_count of this list
'''
return self._subscriber_count
def SetSubscriber_count(self, subscriber_count):
'''Set the subscriber_count of this list.
Args:
subscriber_count:
The subscriber_count of this list.
'''
self._subscriber_count = subscriber_count
subscriber_count = property(GetSubscriber_count, SetSubscriber_count,
doc='The subscriber_count of this list.')
def GetFollowing(self):
'''Get the following status of this list.
Returns:
The following status of this list
'''
return self._following
def SetFollowing(self, following):
'''Set the following status of this list.
Args:
following:
The following of this list.
'''
self._following = following
following = property(GetFollowing, SetFollowing,
doc='The following status of this list.')
def GetUser(self):
'''Get the user of this list.
Returns:
The owner of this list
'''
return self._user
def SetUser(self, user):
'''Set the user of this list.
Args:
user:
The owner of this list.
'''
self._user = user
user = property(GetUser, SetUser,
doc='The owner of this list.')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.name == other.name and \
self.slug == other.slug and \
self.description == other.description and \
self.full_name == other.full_name and \
self.mode == other.mode and \
self.uri == other.uri and \
self.member_count == other.member_count and \
self.subscriber_count == other.subscriber_count and \
self.following == other.following and \
self.user == other.user
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.List instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.List instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.List instance.
Returns:
A JSON string representation of this twitter.List instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.List instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.List instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.name:
data['name'] = self.name
if self.slug:
data['slug'] = self.slug
if self.description:
data['description'] = self.description
if self.full_name:
data['full_name'] = self.full_name
if self.mode:
data['mode'] = self.mode
if self.uri:
data['uri'] = self.uri
if self.member_count is not None:
data['member_count'] = self.member_count
if self.subscriber_count is not None:
data['subscriber_count'] = self.subscriber_count
if self.following is not None:
data['following'] = self.following
if self.user is not None:
data['user'] = self.user
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.List instance
'''
if 'user' in data:
user = User.NewFromJsonDict(data['user'])
else:
user = None
return List(id=data.get('id', None),
name=data.get('name', None),
slug=data.get('slug', None),
description=data.get('description', None),
full_name=data.get('full_name', None),
mode=data.get('mode', None),
uri=data.get('uri', None),
member_count=data.get('member_count', None),
subscriber_count=data.get('subscriber_count', None),
following=data.get('following', None),
user=user)
class DirectMessage(object):
'''A class representing the DirectMessage structure used by the twitter API.
The DirectMessage structure exposes the following properties:
direct_message.id
direct_message.created_at
direct_message.created_at_in_seconds # read only
direct_message.sender_id
direct_message.sender_screen_name
direct_message.recipient_id
direct_message.recipient_screen_name
direct_message.text
'''
def __init__(self,
id=None,
created_at=None,
sender_id=None,
sender_screen_name=None,
recipient_id=None,
recipient_screen_name=None,
text=None):
'''An object to hold a Twitter direct message.
This class is normally instantiated by the twitter.Api class and
returned in a sequence.
Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007"
Args:
id:
The unique id of this direct message. [Optional]
created_at:
The time this direct message was posted. [Optional]
sender_id:
The id of the twitter user that sent this message. [Optional]
sender_screen_name:
The name of the twitter user that sent this message. [Optional]
recipient_id:
The id of the twitter that received this message. [Optional]
recipient_screen_name:
The name of the twitter that received this message. [Optional]
text:
The text of this direct message. [Optional]
'''
self.id = id
self.created_at = created_at
self.sender_id = sender_id
self.sender_screen_name = sender_screen_name
self.recipient_id = recipient_id
self.recipient_screen_name = recipient_screen_name
self.text = text
def GetId(self):
'''Get the unique id of this direct message.
Returns:
The unique id of this direct message
'''
return self._id
def SetId(self, id):
'''Set the unique id of this direct message.
Args:
id:
The unique id of this direct message
'''
self._id = id
id = property(GetId, SetId,
doc='The unique id of this direct message.')
def GetCreatedAt(self):
'''Get the time this direct message was posted.
Returns:
The time this direct message was posted
'''
return self._created_at
def SetCreatedAt(self, created_at):
'''Set the time this direct message was posted.
Args:
created_at:
The time this direct message was created
'''
self._created_at = created_at
created_at = property(GetCreatedAt, SetCreatedAt,
doc='The time this direct message was posted.')
def GetCreatedAtInSeconds(self):
'''Get the time this direct message was posted, in seconds since the epoch.
Returns:
The time this direct message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
created_at_in_seconds = property(GetCreatedAtInSeconds,
doc="The time this direct message was "
"posted, in seconds since the epoch")
def GetSenderId(self):
'''Get the unique sender id of this direct message.
Returns:
The unique sender id of this direct message
'''
return self._sender_id
def SetSenderId(self, sender_id):
'''Set the unique sender id of this direct message.
Args:
sender_id:
The unique sender id of this direct message
'''
self._sender_id = sender_id
sender_id = property(GetSenderId, SetSenderId,
doc='The unique sender id of this direct message.')
def GetSenderScreenName(self):
'''Get the unique sender screen name of this direct message.
Returns:
The unique sender screen name of this direct message
'''
return self._sender_screen_name
def SetSenderScreenName(self, sender_screen_name):
'''Set the unique sender screen name of this direct message.
Args:
sender_screen_name:
The unique sender screen name of this direct message
'''
self._sender_screen_name = sender_screen_name
sender_screen_name = property(GetSenderScreenName, SetSenderScreenName,
doc='The unique sender screen name of this direct message.')
def GetRecipientId(self):
'''Get the unique recipient id of this direct message.
Returns:
The unique recipient id of this direct message
'''
return self._recipient_id
def SetRecipientId(self, recipient_id):
'''Set the unique recipient id of this direct message.
Args:
recipient_id:
The unique recipient id of this direct message
'''
self._recipient_id = recipient_id
recipient_id = property(GetRecipientId, SetRecipientId,
doc='The unique recipient id of this direct message.')
def GetRecipientScreenName(self):
'''Get the unique recipient screen name of this direct message.
Returns:
The unique recipient screen name of this direct message
'''
return self._recipient_screen_name
def SetRecipientScreenName(self, recipient_screen_name):
'''Set the unique recipient screen name of this direct message.
Args:
recipient_screen_name:
The unique recipient screen name of this direct message
'''
self._recipient_screen_name = recipient_screen_name
recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName,
doc='The unique recipient screen name of this direct message.')
def GetText(self):
'''Get the text of this direct message.
Returns:
The text of this direct message.
'''
return self._text
def SetText(self, text):
'''Set the text of this direct message.
Args:
text:
The text of this direct message
'''
self._text = text
text = property(GetText, SetText,
doc='The text of this direct message')
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.id == other.id and \
self.created_at == other.created_at and \
self.sender_id == other.sender_id and \
self.sender_screen_name == other.sender_screen_name and \
self.recipient_id == other.recipient_id and \
self.recipient_screen_name == other.recipient_screen_name and \
self.text == other.text
except AttributeError:
return False
def __str__(self):
'''A string representation of this twitter.DirectMessage instance.
The return value is the same as the JSON string representation.
Returns:
A string representation of this twitter.DirectMessage instance.
'''
return self.AsJsonString()
def AsJsonString(self):
'''A JSON string representation of this twitter.DirectMessage instance.
Returns:
A JSON string representation of this twitter.DirectMessage instance
'''
return simplejson.dumps(self.AsDict(), sort_keys=True)
def AsDict(self):
'''A dict representation of this twitter.DirectMessage instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this twitter.DirectMessage instance
'''
data = {}
if self.id:
data['id'] = self.id
if self.created_at:
data['created_at'] = self.created_at
if self.sender_id:
data['sender_id'] = self.sender_id
if self.sender_screen_name:
data['sender_screen_name'] = self.sender_screen_name
if self.recipient_id:
data['recipient_id'] = self.recipient_id
if self.recipient_screen_name:
data['recipient_screen_name'] = self.recipient_screen_name
if self.text:
data['text'] = self.text
return data
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.DirectMessage instance
'''
return DirectMessage(created_at=data.get('created_at', None),
recipient_id=data.get('recipient_id', None),
sender_id=data.get('sender_id', None),
text=data.get('text', None),
sender_screen_name=data.get('sender_screen_name', None),
id=data.get('id', None),
recipient_screen_name=data.get('recipient_screen_name', None))
class Hashtag(object):
''' A class representing a twitter hashtag
'''
def __init__(self,
text=None):
self.text = text
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Hashtag instance
'''
return Hashtag(text = data.get('text', None))
class Trend(object):
''' A class representing a trending topic
'''
def __init__(self, name=None, query=None, timestamp=None):
self.name = name
self.query = query
self.timestamp = timestamp
def __str__(self):
return 'Name: %s\nQuery: %s\nTimestamp: %s\n' % (self.name, self.query, self.timestamp)
def __ne__(self, other):
return not self.__eq__(other)
def __eq__(self, other):
try:
return other and \
self.name == other.name and \
self.query == other.query and \
self.timestamp == other.timestamp
except AttributeError:
return False
@staticmethod
def NewFromJsonDict(data, timestamp = None):
'''Create a new instance based on a JSON dict
Args:
data:
A JSON dict
timestamp:
Gets set as the timestamp property of the new object
Returns:
A twitter.Trend object
'''
return Trend(name=data.get('name', None),
query=data.get('query', None),
timestamp=timestamp)
class Url(object):
'''A class representing an URL contained in a tweet'''
def __init__(self,
url=None,
expanded_url=None):
self.url = url
self.expanded_url = expanded_url
@staticmethod
def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Url instance
'''
return Url(url=data.get('url', None),
expanded_url=data.get('expanded_url', None))
class Api(object):
'''A python interface into the Twitter API
By default, the Api caches results for 1 minute.
Example usage:
To create an instance of the twitter.Api class, with no authentication:
>>> import twitter
>>> api = twitter.Api()
To fetch the most recently posted public twitter status messages:
>>> statuses = api.GetPublicTimeline()
>>> print [s.user.name for s in statuses]
[u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #...
To fetch a single user's public status messages, where "user" is either
a Twitter "short name" or their user id.
>>> statuses = api.GetUserTimeline(user)
>>> print [s.text for s in statuses]
To use authentication, instantiate the twitter.Api class with a
consumer key and secret; and the oAuth key and secret:
>>> api = twitter.Api(consumer_key='twitter consumer key',
consumer_secret='twitter consumer secret',
access_token_key='the_key_given',
access_token_secret='the_key_secret')
To fetch your friends (after being authenticated):
>>> users = api.GetFriends()
>>> print [u.name for u in users]
To post a twitter status message (after being authenticated):
>>> status = api.PostUpdate('I love python-twitter!')
>>> print status.text
I love python-twitter!
There are many other methods, including:
>>> api.PostUpdates(status)
>>> api.PostDirectMessage(user, text)
>>> api.GetUser(user)
>>> api.GetReplies()
>>> api.GetUserTimeline(user)
>>> api.GetStatus(id)
>>> api.DestroyStatus(id)
>>> api.GetFriendsTimeline(user)
>>> api.GetFriends(user)
>>> api.GetFollowers()
>>> api.GetFeatured()
>>> api.GetDirectMessages()
>>> api.GetSentDirectMessages()
>>> api.PostDirectMessage(user, text)
>>> api.DestroyDirectMessage(id)
>>> api.DestroyFriendship(user)
>>> api.CreateFriendship(user)
>>> api.GetUserByEmail(email)
>>> api.VerifyCredentials()
'''
DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute
_API_REALM = 'Twitter API'
def __init__(self,
consumer_key=None,
consumer_secret=None,
access_token_key=None,
access_token_secret=None,
input_encoding=None,
request_headers=None,
cache=DEFAULT_CACHE,
shortner=None,
base_url=None,
use_gzip_compression=False,
debugHTTP=False):
'''Instantiate a new twitter.Api object.
Args:
consumer_key:
Your Twitter user's consumer_key.
consumer_secret:
Your Twitter user's consumer_secret.
access_token_key:
The oAuth access token key value you retrieved
from running get_access_token.py.
access_token_secret:
The oAuth access token's secret, also retrieved
from the get_access_token.py run.
input_encoding:
The encoding used to encode input strings. [Optional]
request_header:
A dictionary of additional HTTP request headers. [Optional]
cache:
The cache instance to use. Defaults to DEFAULT_CACHE.
Use None to disable caching. [Optional]
shortner:
The shortner instance to use. Defaults to None.
See shorten_url.py for an example shortner. [Optional]
base_url:
The base URL to use to contact the Twitter API.
Defaults to https://api.twitter.com. [Optional]
use_gzip_compression:
Set to True to tell enable gzip compression for any call
made to Twitter. Defaults to False. [Optional]
debugHTTP:
Set to True to enable debug output from urllib2 when performing
any HTTP requests. Defaults to False. [Optional]
'''
self.SetCache(cache)
self._urllib = urllib2
self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
self._input_encoding = input_encoding
self._use_gzip = use_gzip_compression
self._debugHTTP = debugHTTP
self._oauth_consumer = None
self._shortlink_size = 19
self._InitializeRequestHeaders(request_headers)
self._InitializeUserAgent()
self._InitializeDefaultParameters()
if base_url is None:
self.base_url = 'https://api.twitter.com/1'
else:
self.base_url = base_url
if consumer_key is not None and (access_token_key is None or
access_token_secret is None):
print >> sys.stderr, 'Twitter now requires an oAuth Access Token for API calls.'
print >> sys.stderr, 'If your using this library from a command line utility, please'
print >> sys.stderr, 'run the the included get_access_token.py tool to generate one.'
raise TwitterError('Twitter requires oAuth Access Token for all API access')
self.SetCredentials(consumer_key, consumer_secret, access_token_key, access_token_secret)
def SetCredentials(self,
consumer_key,
consumer_secret,
access_token_key=None,
access_token_secret=None):
'''Set the consumer_key and consumer_secret for this instance
Args:
consumer_key:
The consumer_key of the twitter account.
consumer_secret:
The consumer_secret for the twitter account.
access_token_key:
The oAuth access token key value you retrieved
from running get_access_token.py.
access_token_secret:
The oAuth access token's secret, also retrieved
from the get_access_token.py run.
'''
self._consumer_key = consumer_key
self._consumer_secret = consumer_secret
self._access_token_key = access_token_key
self._access_token_secret = access_token_secret
self._oauth_consumer = None
if consumer_key is not None and consumer_secret is not None and \
access_token_key is not None and access_token_secret is not None:
self._signature_method_plaintext = oauth.SignatureMethod_PLAINTEXT()
self._signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
self._oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret)
self._oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
def ClearCredentials(self):
'''Clear the any credentials for this instance
'''
self._consumer_key = None
self._consumer_secret = None
self._access_token_key = None
self._access_token_secret = None
self._oauth_consumer = None
def GetSearch(self,
term=None,
geocode=None,
since_id=None,
max_id=None,
until=None,
per_page=15,
page=1,
lang=None,
show_user="true",
result_type="mixed",
include_entities=None,
query_users=False):
'''Return twitter search results for a given term.
Args:
term:
term to search by. Optional if you include geocode.
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns only statuses with an ID less than (that is, older
than) or equal to the specified ID. [Optional]
until:
Returns tweets generated before the given date. Date should be
formatted as YYYY-MM-DD. [Optional]
geocode:
geolocation information in the form (latitude, longitude, radius)
[Optional]
per_page:
number of results to return. Default is 15 [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
lang:
language for results as ISO 639-1 code. Default is None (all languages)
[Optional]
show_user:
prefixes screen name in status
result_type:
Type of result which should be returned. Default is "mixed". Other
valid options are "recent" and "popular". [Optional]
include_entities:
If True, each tweet will include a node called "entities,".
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
query_users:
If set to False, then all users only have screen_name and
profile_image_url available.
If set to True, all information of users are available,
but it uses lots of request quota, one per status.
Returns:
A sequence of twitter.Status instances, one for each message containing
the term
'''
# Build request parameters
parameters = {}
if since_id:
try:
parameters['since_id'] = long(since_id)
except:
raise TwitterError("since_id must be an integer")
if max_id:
try:
parameters['max_id'] = long(max_id)
except:
raise TwitterError("max_id must be an integer")
if until:
parameters['until'] = until
if lang:
parameters['lang'] = lang
if term is None and geocode is None:
return []
if term is not None:
parameters['q'] = term
if geocode is not None:
parameters['geocode'] = ','.join(map(str, geocode))
if include_entities:
parameters['include_entities'] = 1
parameters['show_user'] = show_user
parameters['rpp'] = per_page
parameters['page'] = page
if result_type in ["mixed", "popular", "recent"]:
parameters['result_type'] = result_type
# Make and send requests
url = 'http://search.twitter.com/search.json'
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
results = []
for x in data['results']:
temp = Status.NewFromJsonDict(x)
if query_users:
# Build user object with new request
temp.user = self.GetUser(urllib.quote(x['from_user']))
else:
temp.user = User(screen_name=x['from_user'], profile_image_url=x['profile_image_url'])
results.append(temp)
# Return built list of statuses
return results # [Status.NewFromJsonDict(x) for x in data['results']]
def GetTrendsCurrent(self, exclude=None):
'''Get the current top trending topics
Args:
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 10 entries. Each entry contains the twitter.
'''
parameters = {}
if exclude:
parameters['exclude'] = exclude
url = '%s/trends/current.json' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
trends = []
for t in data['trends']:
for item in data['trends'][t]:
trends.append(Trend.NewFromJsonDict(item, timestamp = t))
return trends
def GetTrendsWoeid(self, woeid, exclude=None):
'''Return the top 10 trending topics for a specific WOEID, if trending
information is available for it.
Args:
woeid:
the Yahoo! Where On Earth ID for a location.
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 10 entries. Each entry contains a Trend.
'''
parameters = {}
if exclude:
parameters['exclude'] = exclude
url = '%s/trends/%s.json' % (self.base_url, woeid)
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
trends = []
timestamp = data[0]['as_of']
for trend in data[0]['trends']:
trends.append(Trend.NewFromJsonDict(trend, timestamp = timestamp))
return trends
def GetTrendsDaily(self, exclude=None, startdate=None):
'''Get the current top trending topics for each hour in a given day
Args:
startdate:
The start date for the report.
Should be in the format YYYY-MM-DD. [Optional]
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with 24 entries. Each entry contains the twitter.
Trend elements that were trending at the corresponding hour of the day.
'''
parameters = {}
if exclude:
parameters['exclude'] = exclude
if not startdate:
startdate = time.strftime('%Y-%m-%d', time.gmtime())
parameters['date'] = startdate
url = '%s/trends/daily.json' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
trends = []
for i in xrange(24):
trends.append(None)
for t in data['trends']:
idx = int(time.strftime('%H', time.strptime(t, '%Y-%m-%d %H:%M')))
trends[idx] = [Trend.NewFromJsonDict(x, timestamp = t)
for x in data['trends'][t]]
return trends
def GetTrendsWeekly(self, exclude=None, startdate=None):
'''Get the top 30 trending topics for each day in a given week.
Args:
startdate:
The start date for the report.
Should be in the format YYYY-MM-DD. [Optional]
exclude:
Appends the exclude parameter as a request parameter.
Currently only exclude=hashtags is supported. [Optional]
Returns:
A list with each entry contains the twitter.
Trend elements of trending topics for the corresponding day of the week
'''
parameters = {}
if exclude:
parameters['exclude'] = exclude
if not startdate:
startdate = time.strftime('%Y-%m-%d', time.gmtime())
parameters['date'] = startdate
url = '%s/trends/weekly.json' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
trends = []
for i in xrange(7):
trends.append(None)
# use the epochs of the dates as keys for a dictionary
times = dict([(calendar.timegm(time.strptime(t, '%Y-%m-%d')),t)
for t in data['trends']])
cnt = 0
# create the resulting structure ordered by the epochs of the dates
for e in sorted(times.keys()):
trends[cnt] = [Trend.NewFromJsonDict(x, timestamp = times[e])
for x in data['trends'][times[e]]]
cnt +=1
return trends
def GetFriendsTimeline(self,
user=None,
count=None,
page=None,
since_id=None,
retweets=None,
include_entities=None):
'''Fetch the sequence of twitter.Status messages for a user's friends
The twitter.Api instance must be authenticated if the user is private.
Args:
user:
Specifies the ID or screen name of the user for whom to return
the friends_timeline. If not specified then the authenticated
user set in the twitter.Api instance will be used. [Optional]
count:
Specifies the number of statuses to retrieve. May not be
greater than 100. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
retweets:
If True, the timeline will contain native retweets. [Optional]
include_entities:
If True, each tweet will include a node called "entities,".
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message
'''
if not user and not self._oauth_consumer:
raise TwitterError("User must be specified if API is not authenticated.")
url = '%s/statuses/friends_timeline' % self.base_url
if user:
url = '%s/%s.json' % (url, user)
else:
url = '%s.json' % url
parameters = {}
if count is not None:
try:
if int(count) > 100:
raise TwitterError("'count' may not be greater than 100")
except ValueError:
raise TwitterError("'count' must be an integer")
parameters['count'] = count
if page is not None:
try:
parameters['page'] = int(page)
except ValueError:
raise TwitterError("'page' must be an integer")
if since_id:
parameters['since_id'] = since_id
if retweets:
parameters['include_rts'] = True
if include_entities:
parameters['include_entities'] = 1
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(x) for x in data]
def GetUserTimeline(self,
id=None,
user_id=None,
screen_name=None,
since_id=None,
max_id=None,
count=None,
page=None,
include_rts=None,
trim_user=None,
include_entities=None,
exclude_replies=None):
'''Fetch the sequence of public Status messages for a single user.
The twitter.Api instance must be authenticated if the user is private.
Args:
id:
Specifies the ID or screen name of the user for whom to return
the user_timeline. [Optional]
user_id:
Specifies the ID of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid user ID
is also a valid screen name. [Optional]
screen_name:
Specifies the screen name of the user for whom to return the
user_timeline. Helpful for disambiguating when a valid screen
name is also a user ID. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns only statuses with an ID less than (that is, older
than) or equal to the specified ID. [Optional]
count:
Specifies the number of statuses to retrieve. May not be
greater than 200. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
include_rts:
If True, the timeline will contain native retweets (if they
exist) in addition to the standard stream of tweets. [Optional]
trim_user:
If True, statuses will only contain the numerical user ID only.
Otherwise a full user object will be returned for each status.
[Optional]
include_entities:
If True, each tweet will include a node called "entities,".
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
exclude_replies:
If True, this will prevent replies from appearing in the returned
timeline. Using exclude_replies with the count parameter will mean you
will receive up-to count tweets - this is because the count parameter
retrieves that many tweets before filtering out retweets and replies.
This parameter is only supported for JSON and XML responses. [Optional]
Returns:
A sequence of Status instances, one for each message up to count
'''
parameters = {}
if id:
url = '%s/statuses/user_timeline/%s.json' % (self.base_url, id)
elif user_id:
url = '%s/statuses/user_timeline.json?user_id=%d' % (self.base_url, user_id)
elif screen_name:
url = ('%s/statuses/user_timeline.json?screen_name=%s' % (self.base_url,
screen_name))
elif not self._oauth_consumer:
raise TwitterError("User must be specified if API is not authenticated.")
else:
url = '%s/statuses/user_timeline.json' % self.base_url
if since_id:
try:
parameters['since_id'] = long(since_id)
except:
raise TwitterError("since_id must be an integer")
if max_id:
try:
parameters['max_id'] = long(max_id)
except:
raise TwitterError("max_id must be an integer")
if count:
try:
parameters['count'] = int(count)
except:
raise TwitterError("count must be an integer")
if page:
try:
parameters['page'] = int(page)
except:
raise TwitterError("page must be an integer")
if include_rts:
parameters['include_rts'] = 1
if include_entities:
parameters['include_entities'] = 1
if trim_user:
parameters['trim_user'] = 1
if exclude_replies:
parameters['exclude_replies'] = 1
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(x) for x in data]
def GetStatus(self, id, include_entities=None):
'''Returns a single status message.
The twitter.Api instance must be authenticated if the
status message is private.
Args:
id:
The numeric ID of the status you are trying to retrieve.
include_entities:
If True, each tweet will include a node called "entities".
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
Returns:
A twitter.Status instance representing that status message
'''
try:
if id:
long(id)
except:
raise TwitterError("id must be an long integer")
parameters = {}
if include_entities:
parameters['include_entities'] = 1
url = '%s/statuses/show/%s.json' % (self.base_url, id)
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return Status.NewFromJsonDict(data)
def DestroyStatus(self, id):
'''Destroys the status specified by the required ID parameter.
The twitter.Api instance must be authenticated and the
authenticating user must be the author of the specified status.
Args:
id:
The numerical ID of the status you're trying to destroy.
Returns:
A twitter.Status instance representing the destroyed status message
'''
try:
if id:
long(id)
except:
raise TwitterError("id must be an integer")
url = '%s/statuses/destroy/%s.json' % (self.base_url, id)
json = self._FetchUrl(url, post_data={'id': id})
data = self._ParseAndCheckTwitter(json)
return Status.NewFromJsonDict(data)
@classmethod
def _calculate_status_length(cls, status, linksize=19):
dummy_link_replacement = 'https://-%d-chars%s/' % (linksize, '-'*(linksize - 18))
shortened = ' '.join([x if not (x.startswith('http://') or
x.startswith('https://'))
else
dummy_link_replacement
for x in status.split(' ')])
return len(shortened)
def PostUpdate(self, status, in_reply_to_status_id=None, latitude=None, longitude=None):
'''Post a twitter status message from the authenticated user.
The twitter.Api instance must be authenticated.
Args:
status:
The message text to be posted.
Must be less than or equal to 140 characters.
in_reply_to_status_id:
The ID of an existing status that the status to be posted is
in reply to. This implicitly sets the in_reply_to_user_id
attribute of the resulting status to the user ID of the
message being replied to. Invalid/missing status IDs will be
ignored. [Optional]
latitude:
Latitude coordinate of the tweet in degrees. Will only work
in conjunction with longitude argument. Both longitude and
latitude will be ignored by twitter if the user has a false
geo_enabled setting. [Optional]
longitude:
Longitude coordinate of the tweet in degrees. Will only work
in conjunction with latitude argument. Both longitude and
latitude will be ignored by twitter if the user has a false
geo_enabled setting. [Optional]
Returns:
A twitter.Status instance representing the message posted.
'''
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = '%s/statuses/update.json' % self.base_url
if isinstance(status, unicode) or self._input_encoding is None:
u_status = status
else:
u_status = unicode(status, self._input_encoding)
if self._calculate_status_length(u_status, self._shortlink_size) > CHARACTER_LIMIT:
raise TwitterError("Text must be less than or equal to %d characters. "
"Consider using PostUpdates." % CHARACTER_LIMIT)
data = {'status': status}
if in_reply_to_status_id:
data['in_reply_to_status_id'] = in_reply_to_status_id
if latitude != None and longitude != None:
data['lat'] = str(latitude)
data['long'] = str(longitude)
json = self._FetchUrl(url, post_data=data)
data = self._ParseAndCheckTwitter(json)
return Status.NewFromJsonDict(data)
def PostUpdates(self, status, continuation=None, **kwargs):
'''Post one or more twitter status messages from the authenticated user.
Unlike api.PostUpdate, this method will post multiple status updates
if the message is longer than 140 characters.
The twitter.Api instance must be authenticated.
Args:
status:
The message text to be posted.
May be longer than 140 characters.
continuation:
The character string, if any, to be appended to all but the
last message. Note that Twitter strips trailing '...' strings
from messages. Consider using the unicode \u2026 character
(horizontal ellipsis) instead. [Defaults to None]
**kwargs:
See api.PostUpdate for a list of accepted parameters.
Returns:
A of list twitter.Status instance representing the messages posted.
'''
results = list()
if continuation is None:
continuation = ''
line_length = CHARACTER_LIMIT - len(continuation)
lines = textwrap.wrap(status, line_length)
for line in lines[0:-1]:
results.append(self.PostUpdate(line + continuation, **kwargs))
results.append(self.PostUpdate(lines[-1], **kwargs))
return results
def GetUserRetweets(self, count=None, since_id=None, max_id=None, include_entities=False):
'''Fetch the sequence of retweets made by a single user.
The twitter.Api instance must be authenticated.
Args:
count:
The number of status messages to retrieve. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns results with an ID less than (that is, older than) or
equal to the specified ID. [Optional]
include_entities:
If True, each tweet will include a node called "entities,".
This node offers a variety of metadata about the tweet in a
discreet structure, including: user_mentions, urls, and
hashtags. [Optional]
Returns:
A sequence of twitter.Status instances, one for each message up to count
'''
url = '%s/statuses/retweeted_by_me.json' % self.base_url
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if count is not None:
try:
if int(count) > 100:
raise TwitterError("'count' may not be greater than 100")
except ValueError:
raise TwitterError("'count' must be an integer")
if count:
parameters['count'] = count
if since_id:
parameters['since_id'] = since_id
if include_entities:
parameters['include_entities'] = True
if max_id:
try:
parameters['max_id'] = long(max_id)
except:
raise TwitterError("max_id must be an integer")
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(x) for x in data]
def GetReplies(self, since=None, since_id=None, page=None):
'''Get a sequence of status messages representing the 20 most
recent replies (status updates prefixed with @twitterID) to the
authenticating user.
Args:
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
since:
Returns:
A sequence of twitter.Status instances, one for each reply to the user.
'''
url = '%s/statuses/replies.json' % self.base_url
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(x) for x in data]
def GetRetweets(self, statusid):
'''Returns up to 100 of the first retweets of the tweet identified
by statusid
Args:
statusid:
The ID of the tweet for which retweets should be searched for
Returns:
A list of twitter.Status instances, which are retweets of statusid
'''
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instsance must be authenticated.")
url = '%s/statuses/retweets/%s.json?include_entities=true&include_rts=true' % (self.base_url, statusid)
parameters = {}
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(s) for s in data]
def GetRetweetsOfMe(self,
count=None,
since_id=None,
max_id=None,
trim_user=False,
include_entities=True,
include_user_entities=True):
'''Returns up to 100 of the most recent tweets of the user that have been
retweeted by others.
Args:
count:
The number of retweets to retrieve, up to 100. If omitted, 20 is
assumed.
since_id:
Returns results with an ID greater than (newer than) this ID.
max_id:
Returns results with an ID less than or equal to this ID.
trim_user:
When True, the user object for each tweet will only be an ID.
include_entities:
When True, the tweet entities will be included.
include_user_entities:
When True, the user entities will be included.
'''
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = '%s/statuses/retweets_of_me.json' % self.base_url
parameters = {}
if count is not None:
try:
if int(count) > 100:
raise TwitterError("'count' may not be greater than 100")
except ValueError:
raise TwitterError("'count' must be an integer")
if count:
parameters['count'] = count
if since_id:
parameters['since_id'] = since_id
if max_id:
parameters['max_id'] = max_id
if trim_user:
parameters['trim_user'] = trim_user
if not include_entities:
parameters['include_entities'] = include_entities
if not include_user_entities:
parameters['include_user_entities'] = include_user_entities
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(s) for s in data]
def GetFriends(self, user=None, cursor=-1):
'''Fetch the sequence of twitter.User instances, one for each friend.
The twitter.Api instance must be authenticated.
Args:
user:
The twitter name or id of the user whose friends you are fetching.
If not specified, defaults to the authenticated user. [Optional]
Returns:
A sequence of twitter.User instances, one for each friend
'''
if not user and not self._oauth_consumer:
raise TwitterError("twitter.Api instance must be authenticated")
if user:
url = '%s/statuses/friends/%s.json' % (self.base_url, user)
else:
url = '%s/statuses/friends.json' % self.base_url
result = []
parameters = {}
while True:
parameters['cursor'] = cursor
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
result += [User.NewFromJsonDict(x) for x in data['users']]
if 'next_cursor' in data:
if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
break
else:
cursor = data['next_cursor']
else:
break
return result
def GetFriendIDs(self, user=None, cursor=-1):
'''Returns a list of twitter user id's for every person
the specified user is following.
Args:
user:
The id or screen_name of the user to retrieve the id list for
[Optional]
Returns:
A list of integers, one for each user id.
'''
if not user and not self._oauth_consumer:
raise TwitterError("twitter.Api instance must be authenticated")
if user:
url = '%s/friends/ids/%s.json' % (self.base_url, user)
else:
url = '%s/friends/ids.json' % self.base_url
parameters = {}
parameters['cursor'] = cursor
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return data
def GetFollowerIDs(self, user=None, cursor=-1):
'''Returns a list of twitter user id's for every person
that is following the specified user.
Args:
user:
The id or screen_name of the user to retrieve the id list for
[Optional]
Returns:
A list of integers, one for each user id.
'''
if not user and not self._oauth_consumer:
raise TwitterError("twitter.Api instance must be authenticated")
if user:
url = '%s/followers/ids/%s.json' % (self.base_url, user)
else:
url = '%s/followers/ids.json' % self.base_url
parameters = {}
parameters['cursor'] = cursor
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return data
def GetFollowers(self, user=None, cursor=-1):
'''Fetch the sequence of twitter.User instances, one for each follower
The twitter.Api instance must be authenticated.
Args:
cursor:
Specifies the Twitter API Cursor location to start at. [Optional]
Note: there are pagination limits.
Returns:
A sequence of twitter.User instances, one for each follower
'''
if not self._oauth_consumer:
raise TwitterError("twitter.Api instance must be authenticated")
if user:
url = '%s/statuses/followers/%s.json' % (self.base_url, user.GetId())
else:
url = '%s/statuses/followers.json' % self.base_url
result = []
parameters = {}
while True:
parameters = { 'cursor': cursor }
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
result += [User.NewFromJsonDict(x) for x in data['users']]
if 'next_cursor' in data:
if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
break
else:
cursor = data['next_cursor']
else:
break
return result
def GetFeatured(self):
'''Fetch the sequence of twitter.User instances featured on twitter.com
The twitter.Api instance must be authenticated.
Returns:
A sequence of twitter.User instances
'''
url = '%s/statuses/featured.json' % self.base_url
json = self._FetchUrl(url)
data = self._ParseAndCheckTwitter(json)
return [User.NewFromJsonDict(x) for x in data]
def UsersLookup(self, user_id=None, screen_name=None, users=None):
'''Fetch extended information for the specified users.
Users may be specified either as lists of either user_ids,
screen_names, or twitter.User objects. The list of users that
are queried is the union of all specified parameters.
The twitter.Api instance must be authenticated.
Args:
user_id:
A list of user_ids to retrieve extended information.
[Optional]
screen_name:
A list of screen_names to retrieve extended information.
[Optional]
users:
A list of twitter.User objects to retrieve extended information.
[Optional]
Returns:
A list of twitter.User objects for the requested users
'''
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
if not user_id and not screen_name and not users:
raise TwitterError("Specify at least one of user_id, screen_name, or users.")
url = '%s/users/lookup.json' % self.base_url
parameters = {}
uids = list()
if user_id:
uids.extend(user_id)
if users:
uids.extend([u.id for u in users])
if len(uids):
parameters['user_id'] = ','.join(["%s" % u for u in uids])
if screen_name:
parameters['screen_name'] = ','.join(screen_name)
json = self._FetchUrl(url, parameters=parameters)
try:
data = self._ParseAndCheckTwitter(json)
except TwitterError as e:
t = e.args[0]
if len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 34):
data = []
else:
raise
return [User.NewFromJsonDict(u) for u in data]
def GetUser(self, user):
'''Returns a single user.
The twitter.Api instance must be authenticated.
Args:
user: The twitter name or id of the user to retrieve.
Returns:
A twitter.User instance representing that user
'''
url = '%s/users/show/%s.json' % (self.base_url, user)
json = self._FetchUrl(url)
data = self._ParseAndCheckTwitter(json)
return User.NewFromJsonDict(data)
def GetDirectMessages(self, since=None, since_id=None, page=None):
'''Returns a list of the direct messages sent to the authenticating user.
The twitter.Api instance must be authenticated.
Args:
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
Returns:
A sequence of twitter.DirectMessage instances
'''
url = '%s/direct_messages.json' % self.base_url
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [DirectMessage.NewFromJsonDict(x) for x in data]
def GetSentDirectMessages(self, since=None, since_id=None, page=None):
'''Returns a list of the direct messages sent by the authenticating user.
The twitter.Api instance must be authenticated.
Args:
since:
Narrows the returned results to just those statuses created
after the specified HTTP-formatted date. [Optional]
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occured since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
Returns:
A sequence of twitter.DirectMessage instances
'''
url = '%s/direct_messages/sent.json' % self.base_url
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since:
parameters['since'] = since
if since_id:
parameters['since_id'] = since_id
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [DirectMessage.NewFromJsonDict(x) for x in data]
def PostDirectMessage(self, user, text):
'''Post a twitter direct message from the authenticated user
The twitter.Api instance must be authenticated.
Args:
user: The ID or screen name of the recipient user.
text: The message text to be posted. Must be less than 140 characters.
Returns:
A twitter.DirectMessage instance representing the message posted
'''
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = '%s/direct_messages/new.json' % self.base_url
data = {'text': text, 'user': user}
json = self._FetchUrl(url, post_data=data)
data = self._ParseAndCheckTwitter(json)
return DirectMessage.NewFromJsonDict(data)
def DestroyDirectMessage(self, id):
'''Destroys the direct message specified in the required ID parameter.
The twitter.Api instance must be authenticated, and the
authenticating user must be the recipient of the specified direct
message.
Args:
id: The id of the direct message to be destroyed
Returns:
A twitter.DirectMessage instance representing the message destroyed
'''
url = '%s/direct_messages/destroy/%s.json' % (self.base_url, id)
json = self._FetchUrl(url, post_data={'id': id})
data = self._ParseAndCheckTwitter(json)
return DirectMessage.NewFromJsonDict(data)
def CreateFriendship(self, user):
'''Befriends the user specified in the user parameter as the authenticating user.
The twitter.Api instance must be authenticated.
Args:
The ID or screen name of the user to befriend.
Returns:
A twitter.User instance representing the befriended user.
'''
url = '%s/friendships/create/%s.json' % (self.base_url, user)
json = self._FetchUrl(url, post_data={'user': user})
data = self._ParseAndCheckTwitter(json)
return User.NewFromJsonDict(data)
def DestroyFriendship(self, user):
'''Discontinues friendship with the user specified in the user parameter.
The twitter.Api instance must be authenticated.
Args:
The ID or screen name of the user with whom to discontinue friendship.
Returns:
A twitter.User instance representing the discontinued friend.
'''
url = '%s/friendships/destroy/%s.json' % (self.base_url, user)
json = self._FetchUrl(url, post_data={'user': user})
data = self._ParseAndCheckTwitter(json)
return User.NewFromJsonDict(data)
def CreateFavorite(self, status):
'''Favorites the status specified in the status parameter as the authenticating user.
Returns the favorite status when successful.
The twitter.Api instance must be authenticated.
Args:
The twitter.Status instance to mark as a favorite.
Returns:
A twitter.Status instance representing the newly-marked favorite.
'''
url = '%s/favorites/create/%s.json' % (self.base_url, status.id)
json = self._FetchUrl(url, post_data={'id': status.id})
data = self._ParseAndCheckTwitter(json)
return Status.NewFromJsonDict(data)
def DestroyFavorite(self, status):
'''Un-favorites the status specified in the ID parameter as the authenticating user.
Returns the un-favorited status in the requested format when successful.
The twitter.Api instance must be authenticated.
Args:
The twitter.Status to unmark as a favorite.
Returns:
A twitter.Status instance representing the newly-unmarked favorite.
'''
url = '%s/favorites/destroy/%s.json' % (self.base_url, status.id)
json = self._FetchUrl(url, post_data={'id': status.id})
data = self._ParseAndCheckTwitter(json)
return Status.NewFromJsonDict(data)
def GetFavorites(self,
user=None,
page=None):
'''Return a list of Status objects representing favorited tweets.
By default, returns the (up to) 20 most recent tweets for the
authenticated user.
Args:
user:
The twitter name or id of the user whose favorites you are fetching.
If not specified, defaults to the authenticated user. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
'''
parameters = {}
if page:
parameters['page'] = page
if user:
url = '%s/favorites/%s.json' % (self.base_url, user)
elif not user and not self._oauth_consumer:
raise TwitterError("User must be specified if API is not authenticated.")
else:
url = '%s/favorites.json' % self.base_url
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(x) for x in data]
def GetMentions(self,
since_id=None,
max_id=None,
page=None):
'''Returns the 20 most recent mentions (status containing @twitterID)
for the authenticating user.
Args:
since_id:
Returns results with an ID greater than (that is, more recent
than) the specified ID. There are limits to the number of
Tweets which can be accessed through the API. If the limit of
Tweets has occurred since the since_id, the since_id will be
forced to the oldest ID available. [Optional]
max_id:
Returns only statuses with an ID less than
(that is, older than) the specified ID. [Optional]
page:
Specifies the page of results to retrieve.
Note: there are pagination limits. [Optional]
Returns:
A sequence of twitter.Status instances, one for each mention of the user.
'''
url = '%s/statuses/mentions.json' % self.base_url
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
parameters = {}
if since_id:
parameters['since_id'] = since_id
if max_id:
try:
parameters['max_id'] = long(max_id)
except:
raise TwitterError("max_id must be an integer")
if page:
parameters['page'] = page
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [Status.NewFromJsonDict(x) for x in data]
def CreateList(self, user, name, mode=None, description=None):
'''Creates a new list with the give name
The twitter.Api instance must be authenticated.
Args:
user:
Twitter name to create the list for
name:
New name for the list
mode:
'public' or 'private'.
Defaults to 'public'. [Optional]
description:
Description of the list. [Optional]
Returns:
A twitter.List instance representing the new list
'''
url = '%s/%s/lists.json' % (self.base_url, user)
parameters = {'name': name}
if mode is not None:
parameters['mode'] = mode
if description is not None:
parameters['description'] = description
json = self._FetchUrl(url, post_data=parameters)
data = self._ParseAndCheckTwitter(json)
return List.NewFromJsonDict(data)
def DestroyList(self, user, id):
'''Destroys the list from the given user
The twitter.Api instance must be authenticated.
Args:
user:
The user to remove the list from.
id:
The slug or id of the list to remove.
Returns:
A twitter.List instance representing the removed list.
'''
url = '%s/%s/lists/%s.json' % (self.base_url, user, id)
json = self._FetchUrl(url, post_data={'_method': 'DELETE'})
data = self._ParseAndCheckTwitter(json)
return List.NewFromJsonDict(data)
def CreateSubscription(self, owner, list):
'''Creates a subscription to a list by the authenticated user
The twitter.Api instance must be authenticated.
Args:
owner:
User name or id of the owner of the list being subscribed to.
list:
The slug or list id to subscribe the user to
Returns:
A twitter.List instance representing the list subscribed to
'''
url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list)
json = self._FetchUrl(url, post_data={'list_id': list})
data = self._ParseAndCheckTwitter(json)
return List.NewFromJsonDict(data)
def DestroySubscription(self, owner, list):
'''Destroys the subscription to a list for the authenticated user
The twitter.Api instance must be authenticated.
Args:
owner:
The user id or screen name of the user that owns the
list that is to be unsubscribed from
list:
The slug or list id of the list to unsubscribe from
Returns:
A twitter.List instance representing the removed list.
'''
url = '%s/%s/%s/subscribers.json' % (self.base_url, owner, list)
json = self._FetchUrl(url, post_data={'_method': 'DELETE', 'list_id': list})
data = self._ParseAndCheckTwitter(json)
return List.NewFromJsonDict(data)
def GetSubscriptions(self, user, cursor=-1):
'''Fetch the sequence of Lists that the given user is subscribed to
The twitter.Api instance must be authenticated.
Args:
user:
The twitter name or id of the user
cursor:
"page" value that Twitter will use to start building the
list sequence from. -1 to start at the beginning.
Twitter will return in the result the values for next_cursor
and previous_cursor. [Optional]
Returns:
A sequence of twitter.List instances, one for each list
'''
if not self._oauth_consumer:
raise TwitterError("twitter.Api instance must be authenticated")
url = '%s/%s/lists/subscriptions.json' % (self.base_url, user)
parameters = {}
parameters['cursor'] = cursor
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [List.NewFromJsonDict(x) for x in data['lists']]
def GetLists(self, user, cursor=-1):
'''Fetch the sequence of lists for a user.
The twitter.Api instance must be authenticated.
Args:
user:
The twitter name or id of the user whose friends you are fetching.
If the passed in user is the same as the authenticated user
then you will also receive private list data.
cursor:
"page" value that Twitter will use to start building the
list sequence from. -1 to start at the beginning.
Twitter will return in the result the values for next_cursor
and previous_cursor. [Optional]
Returns:
A sequence of twitter.List instances, one for each list
'''
if not self._oauth_consumer:
raise TwitterError("twitter.Api instance must be authenticated")
url = '%s/%s/lists.json' % (self.base_url, user)
parameters = {}
parameters['cursor'] = cursor
json = self._FetchUrl(url, parameters=parameters)
data = self._ParseAndCheckTwitter(json)
return [List.NewFromJsonDict(x) for x in data['lists']]
def GetUserByEmail(self, email):
'''Returns a single user by email address.
Args:
email:
The email of the user to retrieve.
Returns:
A twitter.User instance representing that user
'''
url = '%s/users/show.json?email=%s' % (self.base_url, email)
json = self._FetchUrl(url)
data = self._ParseAndCheckTwitter(json)
return User.NewFromJsonDict(data)
def VerifyCredentials(self):
'''Returns a twitter.User instance if the authenticating user is valid.
Returns:
A twitter.User instance representing that user if the
credentials are valid, None otherwise.
'''
if not self._oauth_consumer:
raise TwitterError("Api instance must first be given user credentials.")
url = '%s/account/verify_credentials.json' % self.base_url
try:
json = self._FetchUrl(url, no_cache=True)
except urllib2.HTTPError, http_error:
if http_error.code == httplib.UNAUTHORIZED:
return None
else:
raise http_error
data = self._ParseAndCheckTwitter(json)
return User.NewFromJsonDict(data)
def SetCache(self, cache):
'''Override the default cache. Set to None to prevent caching.
Args:
cache:
An instance that supports the same API as the twitter._FileCache
'''
if cache == DEFAULT_CACHE:
self._cache = _FileCache()
else:
self._cache = cache
def SetUrllib(self, urllib):
'''Override the default urllib implementation.
Args:
urllib:
An instance that supports the same API as the urllib2 module
'''
self._urllib = urllib
def SetCacheTimeout(self, cache_timeout):
'''Override the default cache timeout.
Args:
cache_timeout:
Time, in seconds, that responses should be reused.
'''
self._cache_timeout = cache_timeout
def SetUserAgent(self, user_agent):
'''Override the default user agent
Args:
user_agent:
A string that should be send to the server as the User-agent
'''
self._request_headers['User-Agent'] = user_agent
def SetXTwitterHeaders(self, client, url, version):
'''Set the X-Twitter HTTP headers that will be sent to the server.
Args:
client:
The client name as a string. Will be sent to the server as
the 'X-Twitter-Client' header.
url:
The URL of the meta.xml as a string. Will be sent to the server
as the 'X-Twitter-Client-URL' header.
version:
The client version as a string. Will be sent to the server
as the 'X-Twitter-Client-Version' header.
'''
self._request_headers['X-Twitter-Client'] = client
self._request_headers['X-Twitter-Client-URL'] = url
self._request_headers['X-Twitter-Client-Version'] = version
def SetSource(self, source):
'''Suggest the "from source" value to be displayed on the Twitter web site.
The value of the 'source' parameter must be first recognized by
the Twitter server. New source values are authorized on a case by
case basis by the Twitter development team.
Args:
source:
The source name as a string. Will be sent to the server as
the 'source' parameter.
'''
self._default_params['source'] = source
def GetRateLimitStatus(self):
'''Fetch the rate limit status for the currently authorized user.
Returns:
A dictionary containing the time the limit will reset (reset_time),
the number of remaining hits allowed before the reset (remaining_hits),
the number of hits allowed in a 60-minute period (hourly_limit), and
the time of the reset in seconds since The Epoch (reset_time_in_seconds).
'''
url = '%s/account/rate_limit_status.json' % self.base_url
json = self._FetchUrl(url, no_cache=True)
data = self._ParseAndCheckTwitter(json)
return data
def MaximumHitFrequency(self):
'''Determines the minimum number of seconds that a program must wait
before hitting the server again without exceeding the rate_limit
imposed for the currently authenticated user.
Returns:
The minimum second interval that a program must use so as to not
exceed the rate_limit imposed for the user.
'''
rate_status = self.GetRateLimitStatus()
reset_time = rate_status.get('reset_time', None)
limit = rate_status.get('remaining_hits', None)
if reset_time:
# put the reset time into a datetime object
reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7])
# find the difference in time between now and the reset time + 1 hour
delta = reset + datetime.timedelta(hours=1) - datetime.datetime.utcnow()
if not limit:
return int(delta.seconds)
# determine the minimum number of seconds allowed as a regular interval
max_frequency = int(delta.seconds / limit) + 1
# return the number of seconds
return max_frequency
return 60
def _BuildUrl(self, url, path_elements=None, extra_params=None):
# Break url into constituent parts
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
# Add any additional path elements to the path
if path_elements:
# Filter out the path elements that have a value of None
p = [i for i in path_elements if i]
if not path.endswith('/'):
path += '/'
path += '/'.join(p)
# Add any additional query parameters to the query string
if extra_params and len(extra_params) > 0:
extra_query = self._EncodeParameters(extra_params)
# Add it to the existing query
if query:
query += '&' + extra_query
else:
query = extra_query
# Return the rebuilt URL
return urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
def _InitializeRequestHeaders(self, request_headers):
if request_headers:
self._request_headers = request_headers
else:
self._request_headers = {}
def _InitializeUserAgent(self):
user_agent = 'Python-urllib/%s (python-twitter/%s)' % \
(self._urllib.__version__, __version__)
self.SetUserAgent(user_agent)
def _InitializeDefaultParameters(self):
self._default_params = {}
def _DecompressGzippedResponse(self, response):
raw_data = response.read()
if response.headers.get('content-encoding', None) == 'gzip':
url_data = gzip.GzipFile(fileobj=StringIO.StringIO(raw_data)).read()
else:
url_data = raw_data
return url_data
def _Encode(self, s):
if self._input_encoding:
return unicode(s, self._input_encoding).encode('utf-8')
else:
return unicode(s).encode('utf-8')
def _EncodeParameters(self, parameters):
'''Return a string in key=value&key=value form
Values of None are not included in the output string.
Args:
parameters:
A dict of (key, value) tuples, where value is encoded as
specified by self._encoding
Returns:
A URL-encoded string in "key=value&key=value" form
'''
if parameters is None:
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None]))
def _EncodePostData(self, post_data):
'''Return a string in key=value&key=value form
Values are assumed to be encoded in the format specified by self._encoding,
and are subsequently URL encoded.
Args:
post_data:
A dict of (key, value) tuples, where value is encoded as
specified by self._encoding
Returns:
A URL-encoded string in "key=value&key=value" form
'''
if post_data is None:
return None
else:
return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()]))
def _ParseAndCheckTwitter(self, json):
"""Try and parse the JSON returned from Twitter and return
an empty dictionary if there is any error. This is a purely
defensive check because during some Twitter network outages
it will return an HTML failwhale page."""
try:
data = simplejson.loads(json)
self._CheckForTwitterError(data)
except ValueError:
if "<title>Twitter / Over capacity</title>" in json:
raise TwitterError("Capacity Error")
if "<title>Twitter / Error</title>" in json:
raise TwitterError("Technical Error")
raise TwitterError("json decoding")
return data
def _CheckForTwitterError(self, data):
"""Raises a TwitterError if twitter returns an error message.
Args:
data:
A python dict created from the Twitter json response
Raises:
TwitterError wrapping the twitter error message if one exists.
"""
# Twitter errors are relatively unlikely, so it is faster
# to check first, rather than try and catch the exception
if 'error' in data:
raise TwitterError(data['error'])
if 'errors' in data:
raise TwitterError(data['errors'])
def _FetchUrl(self,
url,
post_data=None,
parameters=None,
no_cache=None,
use_gzip_compression=None):
'''Fetch a URL, optionally caching for a specified time.
Args:
url:
The URL to retrieve
post_data:
A dict of (str, unicode) key/value pairs.
If set, POST will be used.
parameters:
A dict whose key/value pairs should encoded and added
to the query string. [Optional]
no_cache:
If true, overrides the cache on the current request
use_gzip_compression:
If True, tells the server to gzip-compress the response.
It does not apply to POST requests.
Defaults to None, which will get the value to use from
the instance variable self._use_gzip [Optional]
Returns:
A string containing the body of the response.
'''
# Build the extra parameters dict
extra_params = {}
if self._default_params:
extra_params.update(self._default_params)
if parameters:
extra_params.update(parameters)
if post_data:
http_method = "POST"
else:
http_method = "GET"
if self._debugHTTP:
_debug = 1
else:
_debug = 0
http_handler = self._urllib.HTTPHandler(debuglevel=_debug)
https_handler = self._urllib.HTTPSHandler(debuglevel=_debug)
http_proxy = os.environ.get('http_proxy')
https_proxy = os.environ.get('https_proxy')
if http_proxy is None or https_proxy is None :
proxy_status = False
else :
proxy_status = True
opener = self._urllib.OpenerDirector()
opener.add_handler(http_handler)
opener.add_handler(https_handler)
if proxy_status is True :
proxy_handler = self._urllib.ProxyHandler({'http':str(http_proxy),'https': str(https_proxy)})
opener.add_handler(proxy_handler)
if use_gzip_compression is None:
use_gzip = self._use_gzip
else:
use_gzip = use_gzip_compression
# Set up compression
if use_gzip and not post_data:
opener.addheaders.append(('Accept-Encoding', 'gzip'))
if self._oauth_consumer is not None:
if post_data and http_method == "POST":
parameters = post_data.copy()
req = oauth.Request.from_consumer_and_token(self._oauth_consumer,
token=self._oauth_token,
http_method=http_method,
http_url=url, parameters=parameters)
req.sign_request(self._signature_method_hmac_sha1, self._oauth_consumer, self._oauth_token)
headers = req.to_header()
if http_method == "POST":
encoded_post_data = req.to_postdata()
else:
encoded_post_data = None
url = req.to_url()
else:
url = self._BuildUrl(url, extra_params=extra_params)
encoded_post_data = self._EncodePostData(post_data)
# Open and return the URL immediately if we're not going to cache
if encoded_post_data or no_cache or not self._cache or not self._cache_timeout:
response = opener.open(url, encoded_post_data)
url_data = self._DecompressGzippedResponse(response)
opener.close()
else:
# Unique keys are a combination of the url and the oAuth Consumer Key
if self._consumer_key:
key = self._consumer_key + ':' + url
else:
key = url
# See if it has been cached before
last_cached = self._cache.GetCachedTime(key)
# If the cached version is outdated then fetch another and store it
if not last_cached or time.time() >= last_cached + self._cache_timeout:
try:
response = opener.open(url, encoded_post_data)
url_data = self._DecompressGzippedResponse(response)
self._cache.Set(key, url_data)
except urllib2.HTTPError, e:
print e
opener.close()
else:
url_data = self._cache.Get(key)
# Always return the latest version
return url_data
class _FileCacheError(Exception):
'''Base exception class for FileCache related errors'''
class _FileCache(object):
DEPTH = 3
def __init__(self,root_directory=None):
self._InitializeRootDirectory(root_directory)
def Get(self,key):
path = self._GetPath(key)
if os.path.exists(path):
return open(path).read()
else:
return None
def Set(self,key,data):
path = self._GetPath(key)
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise _FileCacheError('%s exists but is not a directory' % directory)
temp_fd, temp_path = tempfile.mkstemp()
temp_fp = os.fdopen(temp_fd, 'w')
temp_fp.write(data)
temp_fp.close()
if not path.startswith(self._root_directory):
raise _FileCacheError('%s does not appear to live under %s' %
(path, self._root_directory))
if os.path.exists(path):
os.remove(path)
os.rename(temp_path, path)
def Remove(self,key):
path = self._GetPath(key)
if not path.startswith(self._root_directory):
raise _FileCacheError('%s does not appear to live under %s' %
(path, self._root_directory ))
if os.path.exists(path):
os.remove(path)
def GetCachedTime(self,key):
path = self._GetPath(key)
if os.path.exists(path):
return os.path.getmtime(path)
else:
return None
def _GetUsername(self):
'''Attempt to find the username in a cross-platform fashion.'''
try:
return os.getenv('USER') or \
os.getenv('LOGNAME') or \
os.getenv('USERNAME') or \
os.getlogin() or \
'nobody'
except (AttributeError, IOError, OSError), e:
return 'nobody'
def _GetTmpCachePath(self):
username = self._GetUsername()
cache_directory = 'python.cache_' + username
return os.path.join(tempfile.gettempdir(), cache_directory)
def _InitializeRootDirectory(self, root_directory):
if not root_directory:
root_directory = self._GetTmpCachePath()
root_directory = os.path.abspath(root_directory)
if not os.path.exists(root_directory):
os.mkdir(root_directory)
if not os.path.isdir(root_directory):
raise _FileCacheError('%s exists but is not a directory' %
root_directory)
self._root_directory = root_directory
def _GetPath(self,key):
try:
hashed_key = md5(key).hexdigest()
except TypeError:
hashed_key = md5.new(key).hexdigest()
return os.path.join(self._root_directory,
self._GetPrefix(hashed_key),
hashed_key)
def _GetPrefix(self,hashed_key):
return os.path.sep.join(hashed_key[0:_FileCache.DEPTH])
|
1101391i-python-twitter
|
twitter.py
|
Python
|
asf20
| 129,982
|
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-#
#
# Copyright 2007 The Python-Twitter Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''Unit tests for the twitter.py library'''
__author__ = 'python-twitter@googlegroups.com'
import os
import simplejson
import time
import calendar
import unittest
import urllib
import twitter
class StatusTest(unittest.TestCase):
SAMPLE_JSON = '''{"created_at": "Fri Jan 26 23:17:14 +0000 2007", "id": 4391023, "text": "A l\u00e9gp\u00e1rn\u00e1s haj\u00f3m tele van angoln\u00e1kkal.", "user": {"description": "Canvas. JC Penny. Three ninety-eight.", "id": 718443, "location": "Okinawa, Japan", "name": "Kesuke Miyagi", "profile_image_url": "https://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "https://twitter.com/kesuke"}}'''
def _GetSampleUser(self):
return twitter.User(id=718443,
name='Kesuke Miyagi',
screen_name='kesuke',
description=u'Canvas. JC Penny. Three ninety-eight.',
location='Okinawa, Japan',
url='https://twitter.com/kesuke',
profile_image_url='https://twitter.com/system/user/pro'
'file_image/718443/normal/kesuke.pn'
'g')
def _GetSampleStatus(self):
return twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007',
id=4391023,
text=u'A légpárnás hajóm tele van angolnákkal.',
user=self._GetSampleUser())
def testInit(self):
'''Test the twitter.Status constructor'''
status = twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007',
id=4391023,
text=u'A légpárnás hajóm tele van angolnákkal.',
user=self._GetSampleUser())
def testGettersAndSetters(self):
'''Test all of the twitter.Status getters and setters'''
status = twitter.Status()
status.SetId(4391023)
self.assertEqual(4391023, status.GetId())
created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1))
status.SetCreatedAt('Fri Jan 26 23:17:14 +0000 2007')
self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.GetCreatedAt())
self.assertEqual(created_at, status.GetCreatedAtInSeconds())
status.SetNow(created_at + 10)
self.assertEqual("about 10 seconds ago", status.GetRelativeCreatedAt())
status.SetText(u'A légpárnás hajóm tele van angolnákkal.')
self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.',
status.GetText())
status.SetUser(self._GetSampleUser())
self.assertEqual(718443, status.GetUser().id)
def testProperties(self):
'''Test all of the twitter.Status properties'''
status = twitter.Status()
status.id = 1
self.assertEqual(1, status.id)
created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1))
status.created_at = 'Fri Jan 26 23:17:14 +0000 2007'
self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.created_at)
self.assertEqual(created_at, status.created_at_in_seconds)
status.now = created_at + 10
self.assertEqual('about 10 seconds ago', status.relative_created_at)
status.user = self._GetSampleUser()
self.assertEqual(718443, status.user.id)
def _ParseDate(self, string):
return calendar.timegm(time.strptime(string, '%b %d %H:%M:%S %Y'))
def testRelativeCreatedAt(self):
'''Test various permutations of Status relative_created_at'''
status = twitter.Status(created_at='Fri Jan 01 12:00:00 +0000 2007')
status.now = self._ParseDate('Jan 01 12:00:00 2007')
self.assertEqual('about a second ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:00:01 2007')
self.assertEqual('about a second ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:00:02 2007')
self.assertEqual('about 2 seconds ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:00:05 2007')
self.assertEqual('about 5 seconds ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:00:50 2007')
self.assertEqual('about a minute ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:01:00 2007')
self.assertEqual('about a minute ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:01:10 2007')
self.assertEqual('about a minute ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:02:00 2007')
self.assertEqual('about 2 minutes ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:31:50 2007')
self.assertEqual('about 31 minutes ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 12:50:00 2007')
self.assertEqual('about an hour ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 13:00:00 2007')
self.assertEqual('about an hour ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 13:10:00 2007')
self.assertEqual('about an hour ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 14:00:00 2007')
self.assertEqual('about 2 hours ago', status.relative_created_at)
status.now = self._ParseDate('Jan 01 19:00:00 2007')
self.assertEqual('about 7 hours ago', status.relative_created_at)
status.now = self._ParseDate('Jan 02 11:30:00 2007')
self.assertEqual('about a day ago', status.relative_created_at)
status.now = self._ParseDate('Jan 04 12:00:00 2007')
self.assertEqual('about 3 days ago', status.relative_created_at)
status.now = self._ParseDate('Feb 04 12:00:00 2007')
self.assertEqual('about 34 days ago', status.relative_created_at)
def testAsJsonString(self):
'''Test the twitter.Status AsJsonString method'''
self.assertEqual(StatusTest.SAMPLE_JSON,
self._GetSampleStatus().AsJsonString())
def testAsDict(self):
'''Test the twitter.Status AsDict method'''
status = self._GetSampleStatus()
data = status.AsDict()
self.assertEqual(4391023, data['id'])
self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', data['created_at'])
self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', data['text'])
self.assertEqual(718443, data['user']['id'])
def testEq(self):
'''Test the twitter.Status __eq__ method'''
status = twitter.Status()
status.created_at = 'Fri Jan 26 23:17:14 +0000 2007'
status.id = 4391023
status.text = u'A légpárnás hajóm tele van angolnákkal.'
status.user = self._GetSampleUser()
self.assertEqual(status, self._GetSampleStatus())
def testNewFromJsonDict(self):
'''Test the twitter.Status NewFromJsonDict method'''
data = simplejson.loads(StatusTest.SAMPLE_JSON)
status = twitter.Status.NewFromJsonDict(data)
self.assertEqual(self._GetSampleStatus(), status)
class UserTest(unittest.TestCase):
SAMPLE_JSON = '''{"description": "Indeterminate things", "id": 673483, "location": "San Francisco, CA", "name": "DeWitt", "profile_image_url": "https://twitter.com/system/user/profile_image/673483/normal/me.jpg", "screen_name": "dewitt", "status": {"created_at": "Fri Jan 26 17:28:19 +0000 2007", "id": 4212713, "text": "\\"Select all\\" and archive your Gmail inbox. The page loads so much faster!"}, "url": "http://unto.net/"}'''
def _GetSampleStatus(self):
return twitter.Status(created_at='Fri Jan 26 17:28:19 +0000 2007',
id=4212713,
text='"Select all" and archive your Gmail inbox. '
' The page loads so much faster!')
def _GetSampleUser(self):
return twitter.User(id=673483,
name='DeWitt',
screen_name='dewitt',
description=u'Indeterminate things',
location='San Francisco, CA',
url='http://unto.net/',
profile_image_url='https://twitter.com/system/user/prof'
'ile_image/673483/normal/me.jpg',
status=self._GetSampleStatus())
def testInit(self):
'''Test the twitter.User constructor'''
user = twitter.User(id=673483,
name='DeWitt',
screen_name='dewitt',
description=u'Indeterminate things',
url='https://twitter.com/dewitt',
profile_image_url='https://twitter.com/system/user/prof'
'ile_image/673483/normal/me.jpg',
status=self._GetSampleStatus())
def testGettersAndSetters(self):
'''Test all of the twitter.User getters and setters'''
user = twitter.User()
user.SetId(673483)
self.assertEqual(673483, user.GetId())
user.SetName('DeWitt')
self.assertEqual('DeWitt', user.GetName())
user.SetScreenName('dewitt')
self.assertEqual('dewitt', user.GetScreenName())
user.SetDescription('Indeterminate things')
self.assertEqual('Indeterminate things', user.GetDescription())
user.SetLocation('San Francisco, CA')
self.assertEqual('San Francisco, CA', user.GetLocation())
user.SetProfileImageUrl('https://twitter.com/system/user/profile_im'
'age/673483/normal/me.jpg')
self.assertEqual('https://twitter.com/system/user/profile_image/673'
'483/normal/me.jpg', user.GetProfileImageUrl())
user.SetStatus(self._GetSampleStatus())
self.assertEqual(4212713, user.GetStatus().id)
def testProperties(self):
'''Test all of the twitter.User properties'''
user = twitter.User()
user.id = 673483
self.assertEqual(673483, user.id)
user.name = 'DeWitt'
self.assertEqual('DeWitt', user.name)
user.screen_name = 'dewitt'
self.assertEqual('dewitt', user.screen_name)
user.description = 'Indeterminate things'
self.assertEqual('Indeterminate things', user.description)
user.location = 'San Francisco, CA'
self.assertEqual('San Francisco, CA', user.location)
user.profile_image_url = 'https://twitter.com/system/user/profile_i' \
'mage/673483/normal/me.jpg'
self.assertEqual('https://twitter.com/system/user/profile_image/6734'
'83/normal/me.jpg', user.profile_image_url)
self.status = self._GetSampleStatus()
self.assertEqual(4212713, self.status.id)
def testAsJsonString(self):
'''Test the twitter.User AsJsonString method'''
self.assertEqual(UserTest.SAMPLE_JSON,
self._GetSampleUser().AsJsonString())
def testAsDict(self):
'''Test the twitter.User AsDict method'''
user = self._GetSampleUser()
data = user.AsDict()
self.assertEqual(673483, data['id'])
self.assertEqual('DeWitt', data['name'])
self.assertEqual('dewitt', data['screen_name'])
self.assertEqual('Indeterminate things', data['description'])
self.assertEqual('San Francisco, CA', data['location'])
self.assertEqual('https://twitter.com/system/user/profile_image/6734'
'83/normal/me.jpg', data['profile_image_url'])
self.assertEqual('http://unto.net/', data['url'])
self.assertEqual(4212713, data['status']['id'])
def testEq(self):
'''Test the twitter.User __eq__ method'''
user = twitter.User()
user.id = 673483
user.name = 'DeWitt'
user.screen_name = 'dewitt'
user.description = 'Indeterminate things'
user.location = 'San Francisco, CA'
user.profile_image_url = 'https://twitter.com/system/user/profile_image/67' \
'3483/normal/me.jpg'
user.url = 'http://unto.net/'
user.status = self._GetSampleStatus()
self.assertEqual(user, self._GetSampleUser())
def testNewFromJsonDict(self):
'''Test the twitter.User NewFromJsonDict method'''
data = simplejson.loads(UserTest.SAMPLE_JSON)
user = twitter.User.NewFromJsonDict(data)
self.assertEqual(self._GetSampleUser(), user)
class TrendTest(unittest.TestCase):
SAMPLE_JSON = '''{"name": "Kesuke Miyagi", "query": "Kesuke Miyagi"}'''
def _GetSampleTrend(self):
return twitter.Trend(name='Kesuke Miyagi',
query='Kesuke Miyagi',
timestamp='Fri Jan 26 23:17:14 +0000 2007')
def testInit(self):
'''Test the twitter.Trend constructor'''
trend = twitter.Trend(name='Kesuke Miyagi',
query='Kesuke Miyagi',
timestamp='Fri Jan 26 23:17:14 +0000 2007')
def testProperties(self):
'''Test all of the twitter.Trend properties'''
trend = twitter.Trend()
trend.name = 'Kesuke Miyagi'
self.assertEqual('Kesuke Miyagi', trend.name)
trend.query = 'Kesuke Miyagi'
self.assertEqual('Kesuke Miyagi', trend.query)
trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007'
self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', trend.timestamp)
def testNewFromJsonDict(self):
'''Test the twitter.Trend NewFromJsonDict method'''
data = simplejson.loads(TrendTest.SAMPLE_JSON)
trend = twitter.Trend.NewFromJsonDict(data, timestamp='Fri Jan 26 23:17:14 +0000 2007')
self.assertEqual(self._GetSampleTrend(), trend)
def testEq(self):
'''Test the twitter.Trend __eq__ method'''
trend = twitter.Trend()
trend.name = 'Kesuke Miyagi'
trend.query = 'Kesuke Miyagi'
trend.timestamp = 'Fri Jan 26 23:17:14 +0000 2007'
self.assertEqual(trend, self._GetSampleTrend())
class FileCacheTest(unittest.TestCase):
def testInit(self):
"""Test the twitter._FileCache constructor"""
cache = twitter._FileCache()
self.assert_(cache is not None, 'cache is None')
def testSet(self):
"""Test the twitter._FileCache.Set method"""
cache = twitter._FileCache()
cache.Set("foo",'Hello World!')
cache.Remove("foo")
def testRemove(self):
"""Test the twitter._FileCache.Remove method"""
cache = twitter._FileCache()
cache.Set("foo",'Hello World!')
cache.Remove("foo")
data = cache.Get("foo")
self.assertEqual(data, None, 'data is not None')
def testGet(self):
"""Test the twitter._FileCache.Get method"""
cache = twitter._FileCache()
cache.Set("foo",'Hello World!')
data = cache.Get("foo")
self.assertEqual('Hello World!', data)
cache.Remove("foo")
def testGetCachedTime(self):
"""Test the twitter._FileCache.GetCachedTime method"""
now = time.time()
cache = twitter._FileCache()
cache.Set("foo",'Hello World!')
cached_time = cache.GetCachedTime("foo")
delta = cached_time - now
self.assert_(delta <= 1,
'Cached time differs from clock time by more than 1 second.')
cache.Remove("foo")
class ApiTest(unittest.TestCase):
def setUp(self):
self._urllib = MockUrllib()
api = twitter.Api(consumer_key='CONSUMER_KEY',
consumer_secret='CONSUMER_SECRET',
access_token_key='OAUTH_TOKEN',
access_token_secret='OAUTH_SECRET',
cache=None)
api.SetUrllib(self._urllib)
self._api = api
def testTwitterError(self):
'''Test that twitter responses containing an error message are wrapped.'''
self._AddHandler('https://api.twitter.com/1/statuses/user_timeline.json',
curry(self._OpenTestData, 'public_timeline_error.json'))
# Manually try/catch so we can check the exception's value
try:
statuses = self._api.GetUserTimeline()
except twitter.TwitterError, error:
# If the error message matches, the test passes
self.assertEqual('test error', error.message)
else:
self.fail('TwitterError expected')
def testGetUserTimeline(self):
'''Test the twitter.Api GetUserTimeline method'''
self._AddHandler('https://api.twitter.com/1/statuses/user_timeline/kesuke.json?count=1',
curry(self._OpenTestData, 'user_timeline-kesuke.json'))
statuses = self._api.GetUserTimeline('kesuke', count=1)
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(89512102, statuses[0].id)
self.assertEqual(718443, statuses[0].user.id)
def testGetFriendsTimeline(self):
'''Test the twitter.Api GetFriendsTimeline method'''
self._AddHandler('https://api.twitter.com/1/statuses/friends_timeline/kesuke.json',
curry(self._OpenTestData, 'friends_timeline-kesuke.json'))
statuses = self._api.GetFriendsTimeline('kesuke')
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(20, len(statuses))
self.assertEqual(718443, statuses[0].user.id)
def testGetStatus(self):
'''Test the twitter.Api GetStatus method'''
self._AddHandler('https://api.twitter.com/1/statuses/show/89512102.json',
curry(self._OpenTestData, 'show-89512102.json'))
status = self._api.GetStatus(89512102)
self.assertEqual(89512102, status.id)
self.assertEqual(718443, status.user.id)
def testDestroyStatus(self):
'''Test the twitter.Api DestroyStatus method'''
self._AddHandler('https://api.twitter.com/1/statuses/destroy/103208352.json',
curry(self._OpenTestData, 'status-destroy.json'))
status = self._api.DestroyStatus(103208352)
self.assertEqual(103208352, status.id)
def testPostUpdate(self):
'''Test the twitter.Api PostUpdate method'''
self._AddHandler('https://api.twitter.com/1/statuses/update.json',
curry(self._OpenTestData, 'update.json'))
status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'))
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text)
def testPostUpdateLatLon(self):
'''Test the twitter.Api PostUpdate method, when used in conjunction with latitude and longitude'''
self._AddHandler('https://api.twitter.com/1/statuses/update.json',
curry(self._OpenTestData, 'update_latlong.json'))
#test another update with geo parameters, again test somewhat arbitrary
status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'), latitude=54.2, longitude=-2)
self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text)
self.assertEqual(u'Point',status.GetGeo()['type'])
self.assertEqual(26.2,status.GetGeo()['coordinates'][0])
self.assertEqual(127.5,status.GetGeo()['coordinates'][1])
def testGetReplies(self):
'''Test the twitter.Api GetReplies method'''
self._AddHandler('https://api.twitter.com/1/statuses/replies.json?page=1',
curry(self._OpenTestData, 'replies.json'))
statuses = self._api.GetReplies(page=1)
self.assertEqual(36657062, statuses[0].id)
def testGetRetweetsOfMe(self):
'''Test the twitter.API GetRetweetsOfMe method'''
self._AddHandler('https://api.twitter.com/1/statuses/retweets_of_me.json',
curry(self._OpenTestData, 'retweets_of_me.json'))
retweets = self._api.GetRetweetsOfMe()
self.assertEqual(253650670274637824, retweets[0].id)
def testGetFriends(self):
'''Test the twitter.Api GetFriends method'''
self._AddHandler('https://api.twitter.com/1/statuses/friends.json?cursor=123',
curry(self._OpenTestData, 'friends.json'))
users = self._api.GetFriends(cursor=123)
buzz = [u.status for u in users if u.screen_name == 'buzz']
self.assertEqual(89543882, buzz[0].id)
def testGetFollowers(self):
'''Test the twitter.Api GetFollowers method'''
self._AddHandler('https://api.twitter.com/1/statuses/followers.json?cursor=-1',
curry(self._OpenTestData, 'followers.json'))
users = self._api.GetFollowers()
# This is rather arbitrary, but spot checking is better than nothing
alexkingorg = [u.status for u in users if u.screen_name == 'alexkingorg']
self.assertEqual(89554432, alexkingorg[0].id)
def testGetFeatured(self):
'''Test the twitter.Api GetFeatured method'''
self._AddHandler('https://api.twitter.com/1/statuses/featured.json',
curry(self._OpenTestData, 'featured.json'))
users = self._api.GetFeatured()
# This is rather arbitrary, but spot checking is better than nothing
stevenwright = [u.status for u in users if u.screen_name == 'stevenwright']
self.assertEqual(86991742, stevenwright[0].id)
def testGetDirectMessages(self):
'''Test the twitter.Api GetDirectMessages method'''
self._AddHandler('https://api.twitter.com/1/direct_messages.json?page=1',
curry(self._OpenTestData, 'direct_messages.json'))
statuses = self._api.GetDirectMessages(page=1)
self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text)
def testPostDirectMessage(self):
'''Test the twitter.Api PostDirectMessage method'''
self._AddHandler('https://api.twitter.com/1/direct_messages/new.json',
curry(self._OpenTestData, 'direct_messages-new.json'))
status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8'))
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text)
def testDestroyDirectMessage(self):
'''Test the twitter.Api DestroyDirectMessage method'''
self._AddHandler('https://api.twitter.com/1/direct_messages/destroy/3496342.json',
curry(self._OpenTestData, 'direct_message-destroy.json'))
status = self._api.DestroyDirectMessage(3496342)
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(673483, status.sender_id)
def testCreateFriendship(self):
'''Test the twitter.Api CreateFriendship method'''
self._AddHandler('https://api.twitter.com/1/friendships/create/dewitt.json',
curry(self._OpenTestData, 'friendship-create.json'))
user = self._api.CreateFriendship('dewitt')
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(673483, user.id)
def testDestroyFriendship(self):
'''Test the twitter.Api DestroyFriendship method'''
self._AddHandler('https://api.twitter.com/1/friendships/destroy/dewitt.json',
curry(self._OpenTestData, 'friendship-destroy.json'))
user = self._api.DestroyFriendship('dewitt')
# This is rather arbitrary, but spot checking is better than nothing
self.assertEqual(673483, user.id)
def testGetUser(self):
'''Test the twitter.Api GetUser method'''
self._AddHandler('https://api.twitter.com/1/users/show/dewitt.json',
curry(self._OpenTestData, 'show-dewitt.json'))
user = self._api.GetUser('dewitt')
self.assertEqual('dewitt', user.screen_name)
self.assertEqual(89586072, user.status.id)
def _AddHandler(self, url, callback):
self._urllib.AddHandler(url, callback)
def _GetTestDataPath(self, filename):
directory = os.path.dirname(os.path.abspath(__file__))
test_data_dir = os.path.join(directory, 'testdata')
return os.path.join(test_data_dir, filename)
def _OpenTestData(self, filename):
f = open(self._GetTestDataPath(filename))
# make sure that the returned object contains an .info() method:
# headers are set to {}
return urllib.addinfo(f, {})
class MockUrllib(object):
'''A mock replacement for urllib that hardcodes specific responses.'''
def __init__(self):
self._handlers = {}
self.HTTPBasicAuthHandler = MockHTTPBasicAuthHandler
def AddHandler(self, url, callback):
self._handlers[url] = callback
def build_opener(self, *handlers):
return MockOpener(self._handlers)
def HTTPHandler(self, *args, **kwargs):
return None
def HTTPSHandler(self, *args, **kwargs):
return None
def OpenerDirector(self):
return self.build_opener()
def ProxyHandler(self,*args,**kwargs):
return None
class MockOpener(object):
'''A mock opener for urllib'''
def __init__(self, handlers):
self._handlers = handlers
self._opened = False
def open(self, url, data=None):
if self._opened:
raise Exception('MockOpener already opened.')
# Remove parameters from URL - they're only added by oauth and we
# don't want to test oauth
if '?' in url:
# We split using & and filter on the beginning of each key
# This is crude but we have to keep the ordering for now
(url, qs) = url.split('?')
tokens = [token for token in qs.split('&')
if not token.startswith('oauth')]
if len(tokens) > 0:
url = "%s?%s"%(url, '&'.join(tokens))
if url in self._handlers:
self._opened = True
return self._handlers[url]()
else:
raise Exception('Unexpected URL %s (Checked: %s)' % (url, self._handlers))
def add_handler(self, *args, **kwargs):
pass
def close(self):
if not self._opened:
raise Exception('MockOpener closed before it was opened.')
self._opened = False
class MockHTTPBasicAuthHandler(object):
'''A mock replacement for HTTPBasicAuthHandler'''
def add_password(self, realm, uri, user, passwd):
# TODO(dewitt): Add verification that the proper args are passed
pass
class curry:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
def __init__(self, fun, *args, **kwargs):
self.fun = fun
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
if kwargs and self.kwargs:
kw = self.kwargs.copy()
kw.update(kwargs)
else:
kw = kwargs or self.kwargs
return self.fun(*(self.pending + args), **kw)
def suite():
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(FileCacheTest))
suite.addTests(unittest.makeSuite(StatusTest))
suite.addTests(unittest.makeSuite(UserTest))
suite.addTests(unittest.makeSuite(ApiTest))
return suite
if __name__ == '__main__':
unittest.main()
|
1101391i-python-twitter
|
twitter_test.py
|
Python
|
asf20
| 27,102
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/fashion.php
|
PHP
|
mit
| 2,537
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign up · Online Shopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color:#CCCCCC;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #FFFFFF;
border: 1px solid #666666;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
color: black;
}
.form-signin input[type="text"],
.form-signin input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<h1 align="center">Online Shopping</h1>
<br>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading" align="center">Registeration</h2>
<input type="text" class="input-block-level" name="firstname" <?php $i_agree="fn" ?> placeholder="First Name">
<input type="text" class="input-block-level" name="lastname" <?php $i_agree="ln" ?> placeholder="Last Name">
<input type="text" class="input-block-level" name="username" <?php $i_agree="un" ?> placeholder="User Name">
<input type="text" class="input-block-level" name="email" <?php $i_agree="em" ?> placeholder="E-Mail">
<input type="password" class="input-block-level" name="password" <?php $i_agree="pw" ?> placeholder="Password">
<input type="password" class="input-block-level" name="confirm_password" <?php $i_agree="cpw" ?> placeholder="Confirm Password">
<label class="checkbox">
<input type="checkbox" value="iagree" <?php $i_agree="ig" ?> > I agree all the terms and conditions
</label>
<a href="reg.php"><button class="btn btn-large btn-primary" type="submit" >Sign in</button></a>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/signup.php
|
PHP
|
mit
| 4,471
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/footwear.php
|
PHP
|
mit
| 2,542
|
<?php
$id= $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$con = mysql_connect("localhost", "root", "");
mysql_select_db("onlineshopping");
$sql = "INSERT INTO `onlineshopping`.`users` (`id`, `firstname`, `lastname`, `email`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname', '$email', '$username', '$password');";
$result = mysql_query($sql);
mysql_close($con);
header ("location: index.php");
?>
|
069ka-ambition-cms
|
trunk/base/examples/reg.php
|
PHP
|
mit
| 601
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/computer.php
|
PHP
|
mit
| 2,554
|
<div class="logo_online">
<img src="../assets/img/icon.png" width="397" height="97">
</div>
|
069ka-ambition-cms
|
trunk/base/examples/logo_online.php
|
Hack
|
mit
| 94
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Project name</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/base.html
|
HTML
|
mit
| 3,937
|
<?php $page ='home'; ?>
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li class="<?php if ($page='home') "active";?>" > <a href="index.php">Home</a></li>
<li><a href="womens.php">Womens</a></li>
<li><a href="mens.php">Mens</a></li>
<li><a href="kids.php">Kids</a></li>
<li><a href="footwear.php">Footwear</a></li>
<li><a href="jewellery.php">Jewellery</a></li>
<li><a href="fashion.php">Fashion</a></li>
<li><a href="bags.php">Bags</a></li>
<li><a href="books.php">Books</a></li>
<li><a href="gifts.php">Gifts</a></li>
<li><a href="computer.php">Computer</a></li>
<li><a href="electronics.php">Electronics</a></li>
<li><a href="essentials.php">Essentials</a></li>
</ul>
</div>
</div>
|
069ka-ambition-cms
|
trunk/base/examples/nav_top.php
|
PHP
|
mit
| 773
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<!--<h1>Online Shopping</h1>-->
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
// include "nav_top.php"
include "nav.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!--
<div id="social_network">
<div rel="tooltip" title="Facebook" class="facebook_network">
<img src="D:\PHP Practise\base\assets\img\fa.png" class="img-polaroid">
</div>
<div rel="tooltip" title="Twitter" class="twitter_network">
<img src="D:\PHP Practise\base\assets\img\tw.png" class="img-polaroid">
</div>
<div rel="tooltip" title="Google Plus" class="gplus_network">
<img src="D:\PHP Practise\base\assets\img\gt.png" class="img-polaroid">
</div>
</div> -->
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
</div>
</div>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/index.php
|
PHP
|
mit
| 2,915
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/books.php
|
PHP
|
mit
| 2,540
|
<div id="social_network">
<div class="facebook_network">
<img src="..\assets\img\fa.png" class="img-polaroid">
</div>
<div class="twitter_network">
<img src="..\assets\img\tw.png" class="img-polaroid">
</div>
<div class="gplus_network">
<img src="..\assets\img\gt.png" class="img-polaroid">
</div>
</div>
|
069ka-ambition-cms
|
trunk/base/examples/social_network.php
|
Hack
|
mit
| 347
|
<form class="form-search">
<input type="text" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
</form>
|
069ka-ambition-cms
|
trunk/base/examples/form_search.php
|
Hack
|
mit
| 141
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/essentials.php
|
PHP
|
mit
| 2,543
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/kids.php
|
PHP
|
mit
| 2,540
|
<ul class="nav nav-tabs nav-stacked">
<li><a href="#" >Watches</a>
<!-- <ul>
<li><a href="#">Watches Brand 1</a></li>
<li><a href="#">Watches Brand 2</a></li>
<li><a href="#">Watches Brand 3</a></li>
<li><a href="#">Watches Brand 4</a></li>
<li><a href="#">Watches Brand 5</a></li>
<li><a href="#">Watches Brand 6</a></li>
</ul> -->
</li>
<li><a href="#" >Camera</a>
<!-- <ul>
<li><a href="#">Camera Brand 1</a></li>
<li><a href="#">Camera Brand 2</a></li>
<li><a href="#">Camera Brand 3</a></li>
<li><a href="#">Camera Brand 4</a></li>
<li><a href="#">Camera Brand 5</a></li>
</ul> -->
</li>
<li><a href="#">Sports</a>
<!-- <ul>
<li><a href="#">Football</a></li>
<li><a href="#">Volleyball</a></li>
<li><a href="#">Ping Pong Ball</a></li>
<li><a href="#">Gulf Ball</a></li>
</ul> -->
</li>
<li><a href="#">Toys</a>
<!-- <ul>
<li><a href="#">Toys Category 1</a></li>
<li><a href="#">Toys Category 2</a></li>
</ul> -->
</li>
<li><a href="#">Kitchen</a>
<!-- <ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul> -->
</li>
<li><a href="#">Liquor</a>
<!-- <ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
</ul> -->
</li>
<li><a href="#">Miscellaneous</a></li>
</ul>
|
069ka-ambition-cms
|
trunk/base/examples/left_nav.php
|
Hack
|
mit
| 1,421
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/mens.php
|
PHP
|
mit
| 2,541
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/jewellery.php
|
PHP
|
mit
| 2,541
|
<div class="top_nav">
<a href="login.php">Login</a>
<a>|</a>
<a href="signup.php">Sign Up</a></span>
</a>
</div>
|
069ka-ambition-cms
|
trunk/base/examples/login_signup_nav.php
|
Hack
|
mit
| 147
|
<ul id="nav">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">Womens</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Mens</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Kids</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Footwear</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Jewellery</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Fashion</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Bags</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Books</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Gifts</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Computer</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Electronics</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
<li>
<a href="#">Essentials</a>
<ul>
<li><a href="#"> Category 1</a> </li>
<li><a href="#"> Category 2</a> </li>
<li><a href="#"> Category 3</a> </li>
</ul>
</li>
</ul>
</div>
|
069ka-ambition-cms
|
trunk/base/examples/nav.php
|
Hack
|
mit
| 2,385
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/womens.php
|
PHP
|
mit
| 2,547
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign in · Twitter Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color:#CCCCCC;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #FFFFFF;
border: 1px solid #666666;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
color: black;
}
.form-signin input[type="text"],
.form-signin input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<h1 align="center">Online Shopping</h1>
<br><br><br>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">Login Please</h2>
<input type="text" class="input-block-level" placeholder="Email address">
<input type="password" class="input-block-level" placeholder="Password">
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/login.php
|
Hack
|
mit
| 3,836
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/bags.php
|
PHP
|
mit
| 2,542
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/electronics.php
|
PHP
|
mit
| 2,547
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OnlineShopping</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet" type="text/css">
<style>
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!--
.style1 {color: #FFFFFF}
-->
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<?php
include "login_signup_nav.php";
?>
</div>
</div>
</div>
<div class="container">
<?php
include "form_search.php";
?>
<?php
include "logo_online.php";
?>
<p>Shop here anything.</p>
<?php
include "nav_top.php"
?>
<!-- Social Networking Icons -->
<?php
include "social_network.php";
?>
<!-- Social Networking Icons End -->
<?php
include "left_nav.php";
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/base/examples/gifts.php
|
PHP
|
mit
| 2,537
|
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
!function ($) {
$(function(){
var $window = $(window)
// Disable certain links in docs
$('section [href^=#]').click(function (e) {
e.preventDefault()
})
// side bar
$('.bs-docs-sidenav').affix({
offset: {
top: function () { return $window.width() <= 980 ? 290 : 210 }
, bottom: 270
}
})
// make code pretty
window.prettyPrint && prettyPrint()
// add-ons
$('.add-on :checkbox').on('click', function () {
var $this = $(this)
, method = $this.attr('checked') ? 'addClass' : 'removeClass'
$(this).parents('.add-on')[method]('active')
})
// add tipsies to grid for scaffolding
if ($('#gridSystem').length) {
$('#gridSystem').tooltip({
selector: '.show-grid > div'
, title: function () { return $(this).width() + 'px' }
})
}
// tooltip demo
$('.tooltip-demo').tooltip({
selector: "a[rel=tooltip]"
})
$('.tooltip-test').tooltip()
$('.popover-test').popover()
// popover demo
$("a[rel=popover]")
.popover()
.click(function(e) {
e.preventDefault()
})
// button state demo
$('#fat-btn')
.click(function () {
var btn = $(this)
btn.button('loading')
setTimeout(function () {
btn.button('reset')
}, 3000)
})
// carousel demo
$('#myCarousel').carousel()
// javascript build logic
var inputsComponent = $("#components.download input")
, inputsPlugin = $("#plugins.download input")
, inputsVariables = $("#variables.download input")
// toggle all plugin checkboxes
$('#components.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsComponent.attr('checked', !inputsComponent.is(':checked'))
})
$('#plugins.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsPlugin.attr('checked', !inputsPlugin.is(':checked'))
})
$('#variables.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsVariables.val('')
})
// request built javascript
$('.download-btn .btn').on('click', function () {
var css = $("#components.download input:checked")
.map(function () { return this.value })
.toArray()
, js = $("#plugins.download input:checked")
.map(function () { return this.value })
.toArray()
, vars = {}
, img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png']
$("#variables.download input")
.each(function () {
$(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
})
$.ajax({
type: 'POST'
, url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com'
, dataType: 'jsonpi'
, params: {
js: js
, css: css
, vars: vars
, img: img
}
})
})
})
// Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi
$.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) {
var url = opts.url;
return {
send: function(_, completeCallback) {
var name = 'jQuery_iframe_' + jQuery.now()
, iframe, form
iframe = $('<iframe>')
.attr('name', name)
.appendTo('head')
form = $('<form>')
.attr('method', opts.type) // GET or POST
.attr('action', url)
.attr('target', name)
$.each(opts.params, function(k, v) {
$('<input>')
.attr('type', 'hidden')
.attr('name', k)
.attr('value', typeof v == 'string' ? v : JSON.stringify(v))
.appendTo(form)
})
form.appendTo('body').submit()
}
}
})
}(window.jQuery)
|
069ka-ambition-cms
|
trunk/base/assets/js/application.js
|
JavaScript
|
mit
| 3,954
|
/*
Holder - 1.6 - client side image placeholders
(c) 2012 Ivan Malopinsky / http://imsky.co
Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
Commercial use requires attribution.
*/
var Holder = Holder || {};
(function (app, win) {
var preempted = false,
fallback = false,
canvas = document.createElement('canvas');
//getElementsByClassName polyfill
document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s})
//getComputedStyle polyfill
window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this})
//http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications
function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}};
//https://gist.github.com/991057 by Jed Schmidt with modifications
function selector(a){
a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]);
var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret;
}
//shallow object property extend
function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}
function text_size(width, height, template) {
var dimension_arr = [height, width].sort();
var maxFactor = Math.round(dimension_arr[1] / 16),
minFactor = Math.round(dimension_arr[0] / 16);
var text_height = Math.max(template.size, maxFactor);
return {
height: text_height
}
}
function draw(ctx, dimensions, template, ratio) {
var ts = text_size(dimensions.width, dimensions.height, template);
var text_height = ts.height;
var width = dimensions.width * ratio, height = dimensions.height * ratio;
canvas.width = width;
canvas.height = height;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = template.background;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = template.foreground;
ctx.font = "bold " + text_height + "px sans-serif";
var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height);
if (ctx.measureText(text).width / width > 1) {
text_height = template.size / (ctx.measureText(text).width / width);
}
ctx.font = "bold " + (text_height * ratio) + "px sans-serif";
ctx.fillText(text, (width / 2), (height / 2), width);
return canvas.toDataURL("image/png");
}
function render(mode, el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
var ratio = 1;
if(window.devicePixelRatio && window.devicePixelRatio > 1){
ratio = window.devicePixelRatio;
}
if (mode == "image") {
el.setAttribute("data-src", src);
el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
el.style.width = dimensions.width + "px";
el.style.height = dimensions.height + "px";
if (fallback) {
el.style.backgroundColor = theme.background;
}
else{
el.setAttribute("src", draw(ctx, dimensions, theme, ratio));
}
} else {
if (!fallback) {
el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")";
el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px";
}
}
};
function fluid(el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
var fluid = document.createElement("table");
fluid.setAttribute("cellspacing",0)
fluid.setAttribute("cellpadding",0)
fluid.setAttribute("border",0)
var row = document.createElement("tr")
.appendChild(document.createElement("td")
.appendChild(document.createTextNode(theme.text)));
fluid.style.backgroundColor = theme.background;
fluid.style.color = theme.foreground;
fluid.className = el.className + " holderjs-fluid";
fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px");
fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px");
fluid.id = el.id;
var frag = document.createDocumentFragment(),
tbody = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
tr.appendChild(td);
tbody.appendChild(tr);
frag.appendChild(tbody);
if (theme.text) {
td.appendChild(document.createTextNode(theme.text))
fluid.appendChild(frag);
} else {
td.appendChild(document.createTextNode(dimensions_caption))
fluid.appendChild(frag);
fluid_images.push(fluid);
setTimeout(fluid_update, 0);
}
el.parentNode.replaceChild(fluid, el);
}
function fluid_update() {
for (i in fluid_images) {
var el = fluid_images[i];
var label = el.getElementsByTagName("td")[0].firstChild;
label.data = el.offsetWidth + "x" + el.offsetHeight;
}
}
function parse_flags(flags, options) {
var ret = {
theme: settings.themes.gray
}, render = false;
for (sl = flags.length, j = 0; j < sl; j++) {
var flag = flags[j];
if (app.flags.dimensions.match(flag)) {
render = true;
ret.dimensions = app.flags.dimensions.output(flag);
} else if (app.flags.fluid.match(flag)) {
render = true;
ret.dimensions = app.flags.fluid.output(flag);
ret.fluid = true;
} else if (app.flags.colors.match(flag)) {
ret.theme = app.flags.colors.output(flag);
} else if (options.themes[flag]) {
//If a theme is specified, it will override custom colors
ret.theme = options.themes[flag];
} else if (app.flags.text.match(flag)) {
ret.text = app.flags.text.output(flag);
}
}
return render ? ret : false;
};
if (!canvas.getContext) {
fallback = true;
} else {
if (canvas.toDataURL("image/png")
.indexOf("data:image/png") < 0) {
//Android doesn't support data URI
fallback = true;
} else {
var ctx = canvas.getContext("2d");
}
}
var fluid_images = [];
var settings = {
domain: "holder.js",
images: "img",
elements: ".holderjs",
themes: {
"gray": {
background: "#eee",
foreground: "#aaa",
size: 12
},
"social": {
background: "#3a5a97",
foreground: "#fff",
size: 12
},
"industrial": {
background: "#434A52",
foreground: "#C2F200",
size: 12
}
},
stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}"
};
app.flags = {
dimensions: {
regex: /(\d+)x(\d+)/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: +exec[1],
height: +exec[2]
}
}
},
fluid: {
regex: /([0-9%]+)x([0-9%]+)/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: exec[1],
height: exec[2]
}
}
},
colors: {
regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i,
output: function (val) {
var exec = this.regex.exec(val);
return {
size: settings.themes.gray.size,
foreground: "#" + exec[2],
background: "#" + exec[1]
}
}
},
text: {
regex: /text\:(.*)/,
output: function (val) {
return this.regex.exec(val)[1];
}
}
}
for (var flag in app.flags) {
app.flags[flag].match = function (val) {
return val.match(this.regex)
}
}
app.add_theme = function (name, theme) {
name != null && theme != null && (settings.themes[name] = theme);
return app;
};
app.add_image = function (src, el) {
var node = selector(el);
if (node.length) {
for (var i = 0, l = node.length; i < l; i++) {
var img = document.createElement("img")
img.setAttribute("data-src", src);
node[i].appendChild(img);
}
}
return app;
};
app.run = function (o) {
var options = extend(settings, o),
images_nodes = selector(options.images),
elements = selector(options.elements),
preempted = true,
images = [];
for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]);
var holdercss = document.createElement("style");
holdercss.type = "text/css";
holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet;
document.getElementsByTagName("head")[0].appendChild(holdercss);
var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)");
for (var l = elements.length, i = 0; i < l; i++) {
var src = window.getComputedStyle(elements[i], null)
.getPropertyValue("background-image");
var flags = src.match(cssregex);
if (flags) {
var holder = parse_flags(flags[1].split("/"), options);
if (holder) {
render("background", elements[i], holder, src);
}
}
}
for (var l = images.length, i = 0; i < l; i++) {
var src = images[i].getAttribute("src") || images[i].getAttribute("data-src");
if (src != null && src.indexOf(options.domain) >= 0) {
var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1)
.split("/"), options);
if (holder) {
if (holder.fluid) {
fluid(images[i], holder, src);
} else {
render("image", images[i], holder, src);
}
}
}
}
return app;
};
contentLoaded(win, function () {
if (window.addEventListener) {
window.addEventListener("resize", fluid_update, false);
window.addEventListener("orientationchange", fluid_update, false);
} else {
window.attachEvent("onresize", fluid_update)
}
preempted || app.run();
});
})(Holder, window);
|
069ka-ambition-cms
|
trunk/base/assets/js/holder/holder.js
|
JavaScript
|
mit
| 10,517
|
.com { color: #93a1a1; }
.lit { color: #195f91; }
.pun, .opn, .clo { color: #93a1a1; }
.fun { color: #dc322f; }
.str, .atv { color: #D14; }
.kwd, .prettyprint .tag { color: #1e347b; }
.typ, .atn, .dec, .var { color: teal; }
.pln { color: #48484c; }
.prettyprint {
padding: 8px;
background-color: #f7f7f9;
border: 1px solid #e1e1e8;
}
.prettyprint.linenums {
-webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
-moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
}
/* Specify class=linenums on a pre to get line numbering */
ol.linenums {
margin: 0 0 0 33px; /* IE indents via margin-left */
}
ol.linenums li {
padding-left: 12px;
color: #bebec5;
line-height: 20px;
text-shadow: 0 1px 0 #fff;
}
|
069ka-ambition-cms
|
trunk/base/assets/js/google-code-prettify/prettify.css
|
CSS
|
mit
| 817
|
body {
font: 16px sans-serif;
margin: 20px;
color: white;
background: white url('shell_mound.jpg') no-repeat scroll center;
}
div#menu {
background: black;
height: 27px;
width: 1000px;
margin: auto;
}
div.menu > div > ul.menu > li {
width: 125px;
float: left;
}
li.menu div {
background: transparent url('images/highlight_01.png') no-repeat top;
}
li.menu div {
width: 222px;
}
li.menu > div > div {
width: auto;
background: transparent url('images/highlight_03.png') no-repeat bottom;
padding: 20px 0 20px 0;
}
ul.menu a {
color: white;
text-decoration: none;
width: 100%;
display: inline-block;
height: 100%;
position: relative;
}
ul.menu a:focus {
color: yellow;
}
ul.menu,
ul.menu ul {
background: transparent url('images/highlight_02.png') repeat-y center;
list-style: none;
padding: 0;
margin: 0;
}
div.menu li:target > div {
visibility: visible;
}
ul.menu ul {
width: 222px;
}
li.menu > div {
position: absolute;
top: -20px;
left: 222px;
visibility: hidden;
z-index: 4;
width: 222px;
}
div.menu > div > ul.menu > li.menu > div {
top: 29px;
left: 0;
}
ul.menu li {
position: relative;
padding: 2px;
}
ul.menu li:hover,
li.menu-highlight,
li.menu-link-highlight {
background: transparent url('images/transparent_02.png') repeat-y center;
}
ul.menu span {
display: block;
padding: 2px 10px;
}
li.menu > span.arrow {
position: absolute;
width: 15px;
height: 15px;
top: 5px;
right: 15px;
background: url('arrow.png') no-repeat right;
border: none;
padding: 0;
margin: 0;
}
|
069ka-ambition-cms
|
trunk/base/assets/css/drop_down_menus.css
|
CSS
|
mit
| 1,766
|
/* Add additional stylesheets below
-------------------------------------------------- */
/*
Bootstrap's documentation styles
Special styles for presenting Bootstrap's documentation and examples
*/
/* Body and structure
-------------------------------------------------- */
body {
position: relative;
padding-top: 40px;
}
/* Code in headings */
h3 code {
font-size: 14px;
font-weight: normal;
}
/* Tweak navbar brand link to be super sleek
-------------------------------------------------- */
body > .navbar {
font-size: 13px;
}
/* Change the docs' brand */
body > .navbar .brand {
padding-right: 0;
padding-left: 0;
margin-left: 20px;
float: right;
font-weight: bold;
color: #000;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.125);
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
transition: all .2s linear;
}
body > .navbar .brand:hover {
text-decoration: none;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.4);
}
/* Sections
-------------------------------------------------- */
/* padding for in-page bookmarks and fixed navbar */
section {
padding-top: 30px;
}
section > .page-header,
section > .lead {
color: #5a5a5a;
}
section > ul li {
margin-bottom: 5px;
}
/* Separators (hr) */
.bs-docs-separator {
margin: 40px 0 39px;
}
/* Faded out hr */
hr.soften {
height: 1px;
margin: 70px 0;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
border: 0;
}
/* Jumbotrons
-------------------------------------------------- */
/* Base class
------------------------- */
.jumbotron {
position: relative;
padding: 40px 0;
color: #fff;
text-align: center;
text-shadow: 0 1px 3px rgba(0,0,0,.4), 0 0 30px rgba(0,0,0,.075);
background: #020031; /* Old browsers */
background: -moz-linear-gradient(45deg, #020031 0%, #6d3353 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#020031), color-stop(100%,#6d3353)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* IE10+ */
background: linear-gradient(45deg, #020031 0%,#6d3353 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#020031', endColorstr='#6d3353',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
-webkit-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
}
.jumbotron h1 {
font-size: 80px;
font-weight: bold;
letter-spacing: -1px;
line-height: 1;
}
.jumbotron p {
font-size: 24px;
font-weight: 300;
line-height: 1.25;
margin-bottom: 30px;
}
/* Link styles (used on .masthead-links as well) */
.jumbotron a {
color: #fff;
color: rgba(255,255,255,.5);
-webkit-transition: all .2s ease-in-out;
-moz-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.jumbotron a:hover {
color: #fff;
text-shadow: 0 0 10px rgba(255,255,255,.25);
}
/* Download button */
.masthead .btn {
padding: 19px 24px;
font-size: 24px;
font-weight: 200;
color: #fff; /* redeclare to override the `.jumbotron a` */
border: 0;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.masthead .btn:hover {
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
}
.masthead .btn:active {
-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
}
/* Pattern overlay
------------------------- */
.jumbotron .container {
position: relative;
z-index: 2;
}
.jumbotron:after {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(../img/bs-docs-masthead-pattern.png) repeat center center;
opacity: .4;
}
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1) {
.jumbotron:after {
background-size: 150px 150px;
}
}
/* Masthead (docs home)
------------------------- */
.masthead {
padding: 70px 0 80px;
margin-bottom: 0;
color: #fff;
}
.masthead h1 {
font-size: 120px;
line-height: 1;
letter-spacing: -2px;
}
.masthead p {
font-size: 40px;
font-weight: 200;
line-height: 1.25;
}
/* Textual links in masthead */
.masthead-links {
margin: 0;
list-style: none;
}
.masthead-links li {
display: inline;
padding: 0 10px;
color: rgba(255,255,255,.25);
}
/* Social proof buttons from GitHub & Twitter */
.bs-docs-social {
padding: 15px 0;
text-align: center;
background-color: #f5f5f5;
border-top: 1px solid #fff;
border-bottom: 1px solid #ddd;
}
/* Quick links on Home */
.bs-docs-social-buttons {
margin-left: 0;
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.bs-docs-social-buttons li {
display: inline-block;
padding: 5px 8px;
line-height: 1;
*display: inline;
*zoom: 1;
}
/* Subhead (other pages)
------------------------- */
.subhead {
text-align: left;
border-bottom: 1px solid #ddd;
}
.subhead h1 {
font-size: 60px;
}
.subhead p {
margin-bottom: 20px;
}
.subhead .navbar {
display: none;
}
/* Marketing section of Overview
-------------------------------------------------- */
.marketing {
text-align: center;
color: #5a5a5a;
}
.marketing h1 {
margin: 60px 0 10px;
font-size: 60px;
font-weight: 200;
line-height: 1;
letter-spacing: -1px;
}
.marketing h2 {
font-weight: 200;
margin-bottom: 5px;
}
.marketing p {
font-size: 16px;
line-height: 1.5;
}
.marketing .marketing-byline {
margin-bottom: 40px;
font-size: 20px;
font-weight: 300;
line-height: 1.25;
color: #999;
}
.marketing-img {
display: block;
margin: 0 auto 30px;
max-height: 145px;
}
/* Footer
-------------------------------------------------- */
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
/* Special grid styles
-------------------------------------------------- */
.show-grid {
margin-top: 10px;
margin-bottom: 20px;
}
.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
min-height: 40px;
line-height: 40px;
}
.show-grid:hover [class*="span"] {
background: #ddd;
}
.show-grid .show-grid {
margin-top: 0;
margin-bottom: 0;
}
.show-grid .show-grid [class*="span"] {
margin-top: 5px;
}
.show-grid [class*="span"] [class*="span"] {
background-color: #ccc;
}
.show-grid [class*="span"] [class*="span"] [class*="span"] {
background-color: #999;
}
/* Mini layout previews
-------------------------------------------------- */
.mini-layout {
border: 1px solid #ddd;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.075);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.075);
box-shadow: 0 1px 2px rgba(0,0,0,.075);
}
.mini-layout,
.mini-layout .mini-layout-body,
.mini-layout.fluid .mini-layout-sidebar {
height: 300px;
}
.mini-layout {
margin-bottom: 20px;
padding: 9px;
}
.mini-layout div {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.mini-layout .mini-layout-body {
background-color: #dceaf4;
margin: 0 auto;
width: 70%;
}
.mini-layout.fluid .mini-layout-sidebar,
.mini-layout.fluid .mini-layout-header,
.mini-layout.fluid .mini-layout-body {
float: left;
}
.mini-layout.fluid .mini-layout-sidebar {
background-color: #bbd8e9;
width: 20%;
}
.mini-layout.fluid .mini-layout-body {
width: 77.5%;
margin-left: 2.5%;
}
/* Download page
-------------------------------------------------- */
.download .page-header {
margin-top: 36px;
}
.page-header .toggle-all {
margin-top: 5px;
}
/* Space out h3s when following a section */
.download h3 {
margin-bottom: 5px;
}
.download-builder input + h3,
.download-builder .checkbox + h3 {
margin-top: 9px;
}
/* Fields for variables */
.download-builder input[type=text] {
margin-bottom: 9px;
font-family: Menlo, Monaco, "Courier New", monospace;
font-size: 12px;
color: #d14;
}
.download-builder input[type=text]:focus {
background-color: #fff;
}
/* Custom, larger checkbox labels */
.download .checkbox {
padding: 6px 10px 6px 25px;
font-size: 13px;
line-height: 18px;
color: #555;
background-color: #f9f9f9;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
}
.download .checkbox:hover {
color: #333;
background-color: #f5f5f5;
}
.download .checkbox small {
font-size: 12px;
color: #777;
}
/* Variables section */
#variables label {
margin-bottom: 0;
}
/* Giant download button */
.download-btn {
margin: 36px 0 108px;
}
#download p,
#download h4 {
max-width: 50%;
margin: 0 auto;
color: #999;
text-align: center;
}
#download h4 {
margin-bottom: 0;
}
#download p {
margin-bottom: 18px;
}
.download-btn .btn {
display: block;
width: auto;
padding: 19px 24px;
margin-bottom: 27px;
font-size: 30px;
line-height: 1;
text-align: center;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/* Misc
-------------------------------------------------- */
/* Make tables spaced out a bit more */
h2 + table,
h3 + table,
h4 + table,
h2 + .row {
margin-top: 5px;
}
/* Example sites showcase */
.example-sites {
xmargin-left: 20px;
}
.example-sites img {
max-width: 100%;
margin: 0 auto;
}
.scrollspy-example {
height: 200px;
overflow: auto;
position: relative;
}
/* Fake the :focus state to demo it */
.focused {
border-color: rgba(82,168,236,.8);
-webkit-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
-moz-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
outline: 0;
}
/* For input sizes, make them display block */
.docs-input-sizes select,
.docs-input-sizes input[type=text] {
display: block;
margin-bottom: 9px;
}
/* Icons
------------------------- */
.the-icons {
margin-left: 0;
list-style: none;
}
.the-icons li {
float: left;
width: 25%;
line-height: 25px;
}
.the-icons i:hover {
background-color: rgba(255,0,0,.25);
}
/* Example page
------------------------- */
.bootstrap-examples p {
font-size: 13px;
line-height: 18px;
}
.bootstrap-examples .thumbnail {
margin-bottom: 9px;
background-color: #fff;
}
/* Bootstrap code examples
-------------------------------------------------- */
/* Base class */
.bs-docs-example {
position: relative;
margin: 15px 0;
padding: 39px 19px 14px;
*padding-top: 19px;
background-color: #fff;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
/* Echo out a label for the example */
.bs-docs-example:after {
content: "Example";
position: absolute;
top: -1px;
left: -1px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
background-color: #f5f5f5;
border: 1px solid #ddd;
color: #9da0a4;
-webkit-border-radius: 4px 0 4px 0;
-moz-border-radius: 4px 0 4px 0;
border-radius: 4px 0 4px 0;
}
/* Remove spacing between an example and it's code */
.bs-docs-example + .prettyprint {
margin-top: -20px;
padding-top: 15px;
}
/* Tweak examples
------------------------- */
.bs-docs-example > p:last-child {
margin-bottom: 0;
}
.bs-docs-example .table,
.bs-docs-example .progress,
.bs-docs-example .well,
.bs-docs-example .alert,
.bs-docs-example .hero-unit,
.bs-docs-example .pagination,
.bs-docs-example .navbar,
.bs-docs-example > .nav,
.bs-docs-example blockquote {
margin-bottom: 5px;
}
.bs-docs-example .pagination {
margin-top: 0;
}
.bs-navbar-top-example,
.bs-navbar-bottom-example {
z-index: 1;
padding: 0;
height: 90px;
overflow: hidden; /* cut the drop shadows off */
}
.bs-navbar-top-example .navbar-fixed-top,
.bs-navbar-bottom-example .navbar-fixed-bottom {
margin-left: 0;
margin-right: 0;
}
.bs-navbar-top-example {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
.bs-navbar-top-example:after {
top: auto;
bottom: -1px;
-webkit-border-radius: 0 4px 0 4px;
-moz-border-radius: 0 4px 0 4px;
border-radius: 0 4px 0 4px;
}
.bs-navbar-bottom-example {
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
border-radius: 4px 4px 0 0;
}
.bs-navbar-bottom-example .navbar {
margin-bottom: 0;
}
form.bs-docs-example {
padding-bottom: 19px;
}
/* Images */
.bs-docs-example-images img {
margin: 10px;
display: inline-block;
}
/* Tooltips */
.bs-docs-tooltip-examples {
text-align: center;
margin: 0 0 10px;
list-style: none;
}
.bs-docs-tooltip-examples li {
display: inline;
padding: 0 10px;
}
/* Popovers */
.bs-docs-example-popover {
padding-bottom: 24px;
background-color: #f9f9f9;
}
.bs-docs-example-popover .popover {
position: relative;
display: block;
float: left;
width: 260px;
margin: 20px;
}
/* Dropdowns */
.bs-docs-example-submenus {
min-height: 180px;
}
.bs-docs-example-submenus > .pull-left + .pull-left {
margin-left: 20px;
}
.bs-docs-example-submenus .dropup > .dropdown-menu,
.bs-docs-example-submenus .dropdown > .dropdown-menu {
display: block;
position: static;
margin-bottom: 5px;
*width: 180px;
}
/* Responsive docs
-------------------------------------------------- */
/* Utility classes table
------------------------- */
.responsive-utilities th small {
display: block;
font-weight: normal;
color: #999;
}
.responsive-utilities tbody th {
font-weight: normal;
}
.responsive-utilities td {
text-align: center;
}
.responsive-utilities td.is-visible {
color: #468847;
background-color: #dff0d8 !important;
}
.responsive-utilities td.is-hidden {
color: #ccc;
background-color: #f9f9f9 !important;
}
/* Responsive tests
------------------------- */
.responsive-utilities-test {
margin-top: 5px;
margin-left: 0;
list-style: none;
overflow: hidden; /* clear floats */
}
.responsive-utilities-test li {
position: relative;
float: left;
width: 25%;
height: 43px;
font-size: 14px;
font-weight: bold;
line-height: 43px;
color: #999;
text-align: center;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test li + li {
margin-left: 10px;
}
.responsive-utilities-test span {
position: absolute;
top: -1px;
left: -1px;
right: -1px;
bottom: -1px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test span {
color: #468847;
background-color: #dff0d8;
border: 1px solid #d6e9c6;
}
/* Sidenav for Docs
-------------------------------------------------- */
.bs-docs-sidenav {
width: 228px;
margin: 30px 0 0;
padding: 0;
background-color: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 4px rgba(0,0,0,.065);
-moz-box-shadow: 0 1px 4px rgba(0,0,0,.065);
box-shadow: 0 1px 4px rgba(0,0,0,.065);
}
.bs-docs-sidenav > li > a {
display: block;
width: 190px \9;
margin: 0 0 -1px;
padding: 8px 14px;
border: 1px solid #e5e5e5;
}
.bs-docs-sidenav > li:first-child > a {
-webkit-border-radius: 6px 6px 0 0;
-moz-border-radius: 6px 6px 0 0;
border-radius: 6px 6px 0 0;
}
.bs-docs-sidenav > li:last-child > a {
-webkit-border-radius: 0 0 6px 6px;
-moz-border-radius: 0 0 6px 6px;
border-radius: 0 0 6px 6px;
}
.bs-docs-sidenav > .active > a {
position: relative;
z-index: 2;
padding: 9px 15px;
border: 0;
text-shadow: 0 1px 0 rgba(0,0,0,.15);
-webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
-moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
}
/* Chevrons */
.bs-docs-sidenav .icon-chevron-right {
float: right;
margin-top: 2px;
margin-right: -6px;
opacity: .25;
}
.bs-docs-sidenav > li > a:hover {
background-color: #f5f5f5;
}
.bs-docs-sidenav a:hover .icon-chevron-right {
opacity: .5;
}
.bs-docs-sidenav .active .icon-chevron-right,
.bs-docs-sidenav .active a:hover .icon-chevron-right {
background-image: url(../img/glyphicons-halflings-white.png);
opacity: 1;
}
.bs-docs-sidenav.affix {
top: 40px;
}
.bs-docs-sidenav.affix-bottom {
position: absolute;
top: auto;
bottom: 270px;
}
/* Responsive
-------------------------------------------------- */
/* Desktop large
------------------------- */
@media (min-width: 1200px) {
.bs-docs-container {
max-width: 970px;
}
.bs-docs-sidenav {
width: 258px;
}
.bs-docs-sidenav > li > a {
width: 230px \9; /* Override the previous IE8-9 hack */
}
}
/* Desktop
------------------------- */
@media (max-width: 980px) {
/* Unfloat brand */
body > .navbar-fixed-top .brand {
float: left;
margin-left: 0;
padding-left: 10px;
padding-right: 10px;
}
/* Inline-block quick links for more spacing */
.quick-links li {
display: inline-block;
margin: 5px;
}
/* When affixed, space properly */
.bs-docs-sidenav {
top: 0;
width: 218px;
margin-top: 30px;
margin-right: 0;
}
}
/* Tablet to desktop
------------------------- */
@media (min-width: 768px) and (max-width: 979px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Widen masthead and social buttons to fill body padding */
.jumbotron {
margin-top: -20px; /* Offset bottom margin on .navbar */
}
/* Adjust sidenav width */
.bs-docs-sidenav {
width: 166px;
margin-top: 20px;
}
.bs-docs-sidenav.affix {
top: 0;
}
}
/* Tablet
------------------------- */
@media (max-width: 767px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Widen masthead and social buttons to fill body padding */
.jumbotron {
padding: 40px 20px;
margin-top: -20px; /* Offset bottom margin on .navbar */
margin-right: -20px;
margin-left: -20px;
}
.masthead h1 {
font-size: 90px;
}
.masthead p,
.masthead .btn {
font-size: 24px;
}
.marketing .span4 {
margin-bottom: 40px;
}
.bs-docs-social {
margin: 0 -20px;
}
/* Space out the show-grid examples */
.show-grid [class*="span"] {
margin-bottom: 5px;
}
/* Sidenav */
.bs-docs-sidenav {
width: auto;
margin-bottom: 20px;
}
.bs-docs-sidenav.affix {
position: static;
width: auto;
top: 0;
}
/* Unfloat the back to top link in footer */
.footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
.footer p {
margin-bottom: 9px;
}
}
/* Landscape phones
------------------------- */
@media (max-width: 480px) {
/* Remove padding above jumbotron */
body {
padding-top: 0;
}
/* Change up some type stuff */
h2 small {
display: block;
}
/* Downsize the jumbotrons */
.jumbotron h1 {
font-size: 45px;
}
.jumbotron p,
.jumbotron .btn {
font-size: 18px;
}
.jumbotron .btn {
display: block;
margin: 0 auto;
}
/* center align subhead text like the masthead */
.subhead h1,
.subhead p {
text-align: center;
}
/* Marketing on home */
.marketing h1 {
font-size: 30px;
}
.marketing-byline {
font-size: 18px;
}
/* center example sites */
.example-sites {
margin-left: 0;
}
.example-sites > li {
float: none;
display: block;
max-width: 280px;
margin: 0 auto 18px;
text-align: center;
}
.example-sites .thumbnail > img {
max-width: 270px;
}
/* Do our best to make tables work in narrow viewports */
table code {
white-space: normal;
word-wrap: break-word;
word-break: break-all;
}
/* Examples: dropdowns */
.bs-docs-example-submenus > .pull-left {
float: none;
clear: both;
}
.bs-docs-example-submenus > .pull-left,
.bs-docs-example-submenus > .pull-left + .pull-left {
margin-left: 0;
}
.bs-docs-example-submenus p {
margin-bottom: 0;
}
.bs-docs-example-submenus .dropup > .dropdown-menu,
.bs-docs-example-submenus .dropdown > .dropdown-menu {
margin-bottom: 10px;
float: none;
max-width: 180px;
}
/* Examples: modal */
.modal-example .modal {
position: relative;
top: auto;
right: auto;
bottom: auto;
left: auto;
}
/* Tighten up footer */
.footer {
padding-top: 20px;
padding-bottom: 20px;
}
}
|
069ka-ambition-cms
|
trunk/base/assets/css/docs.css
|
CSS
|
mit
| 22,431
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<li><a href="style.html">Style Demo</a></li>
<li id="current"><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<div class="post no-bg">
<h2><a href="index.html">A Blog Entry</a></h2>
<p class="post-info">Posted by <a href="index.html">erwin</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a> </p>
<div class="image-section">
<img src="images/img-post.jpg" alt="image post"/>
</div>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac <a href="index.html">convallis aliquam</a>, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p>Donec mattis, purus nec placerat bibendum, <a href="index.html">dui pede condimentum</a>
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, <a href="index.html">eget fringilla velit</a> magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra
condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. Curabitur vel urna.
In tristique orci porttitor ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.
</p>
<p class="tags">
<strong>Tagged : </strong>
<a href="#">orci</a>, <a href="#">lectus</a>, <a href="#">varius</a>, <a href="#">turpis</a>
</p>
<p class="postmeta">
<a href="index.html" class="comments">Comments (3)</a> |
<span class="date">April 20, 2009</span> |
<a href="index.html" class="edit">Edit</a>
</p>
<h3 id="comments">3 Responses</h3>
<ol class="commentlist">
<li class="alt" id="comment-63">
<cite>
<img alt="" src="images/gravatar.jpg" class="avatar" height="40" width="40" />
<a href="index.html">Erwin</a> Says: <br />
<span class="comment-data"><a href="#comment-63" title="">April 20th, 2009 at 8:08 am</a> </span>
</cite>
<div class="comment-text">
<p>Comments are great!</p>
</div>
</li>
<li id="comment-67">
<cite>
<img alt="" src="images/gravatar.jpg" class="avatar" height="40" width="40" />
admin Says: <br />
<span class="comment-data"><a href="#comment-67" title="">April 20th, 2009 at 2:17 pm</a> </span>
</cite>
<div class="comment-text">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero.
Suspendisse bibendum.</p>
</div>
</li>
<li class="alt" id="comment-71">
<cite>
<img alt="" src="images/gravatar.jpg" class="avatar" height="40" width="40" />
<a href="index.html">Erwin</a> Says: <br />
<span class="comment-data"><a href="#comment-71" title="">April 20th, 2009 at 3:17 pm</a> </span>
</cite>
<div class="comment-text">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo.</p>
</div>
</li>
</ol>
<h3 id="respond">Leave a Reply</h3>
<form action="index.html" method="post" id="commentform">
<p>
<label for="name">Name (required)</label><br />
<input id="name" name="name" value="Your Name" type="text" tabindex="1" />
</p>
<p>
<label for="email">Email Address (required)</label><br />
<input id="email" name="email" value="Your Email" type="text" tabindex="2" />
</p>
<p>
<label for="website">Website</label><br />
<input id="website" name="website" value="Your Website" type="text" tabindex="3" />
</p>
<p>
<label for="message">Your Message</label><br />
<textarea id="message" name="message" rows="10" cols="20" tabindex="4"></textarea>
</p>
<p class="no-border">
<input class="button" type="submit" value="Submit" tabindex="5" />
</p>
</form>
</div>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/blog.html
|
HTML
|
mit
| 12,853
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
/*$(document).ready(function(){
//write jQuery code inside ready function
$(".delete").click(function(){
//confirm("Delete this ?");
//$("#box").hide("fast");
//$("#box").hide("slow");
//$("#box").show("slow");
//$("#box").fadeIn("slow");
$("#box").fadeOut("slow");
});
}); */
//$(".someclass") jQuery class selector
//$("#content") jQuery id selector
$(document).ready(function(){
$(".delete").click(function(){
$("#box").fadeOut("slow");
});
});
</script>
<style type="text/css">
#box{
width:150px;
height:80px;
background:#69f;
color:#fff;
padding:20px;
}
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Bernhardt College</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome Admin</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<div id="box">
this is some text <a href="#" class="delete">x</a>
</div>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/jq.php
|
Hack
|
mit
| 4,150
|
<?php
include "includes/common.php";
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `settings`";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><?php echo $row['site_name'];?></title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<link media="screen" rel="stylesheet" href="<?php echo $site_url;?>third_party/colorbox/colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="<?php echo $site_url;?>third_party/colorbox/jquery.colorbox.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".cbox").colorbox({transition:"none", width:"85%", height:"85%"});
});
</script>
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="<?php echo $site_url;?>" title=""><?php echo $row['site_name'];?></a></h1>
<p id="slogan"><?php echo $row['site_slogan'];?></p>
<div id="nav">
<ul>
<li class="first" id="current"><a href="index.html">Home</a></li>
<li><a href="style.html">Style</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- featured starts -->
<div id="featured" class="clear">
<a name="TemplateInfo"></a>
<?php
$featured_sql = "SELECT post.*, post_categories.name, users.username from `post`
JOIN `post_categories` ON post.category = post_categories.id
JOIN `users` ON post.user_id = users.id
WHERE post_categories.slug ='featured' order by post.created_at DESC LIMIT 1";
$featured_result = mysql_query($featured_sql);
$featured_post = mysql_fetch_assoc($featured_result);
?>
<div class="image-block">
<img width="330" src="<?php echo UPLOAD_PATH.$featured_post['image'];?>" alt="featured"/>
</div>
<div class="text-block">
<h2><a href="index.html"><?php echo $featured_post['title'];?></a></h2>
<p class="post-info">Posted by <a href="index.html"><?php echo $featured_post['username'];?></a></p>
<p>
<?php echo substr($featured_post['content'],0,300); ?>
</p>
<p><a href="index.html" class="more-link">Read More</a></p>
</div>
<!-- featured ends -->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<?php
$general_sql = "SELECT post.*, post_categories.name, users.username from `post`
JOIN `post_categories` ON post.category = post_categories.id
JOIN `users` ON post.user_id = users.id
WHERE post_categories.slug ='general' order by post.created_at DESC LIMIT 5";
$general_result = mysql_query($general_sql);
while ($post = mysql_fetch_assoc($general_result)) {
?>
<div class="entry">
<h3><a href="index.html"><?php echo $post['title'];?></a></h3>
<p>
<?php echo substr($post['content'],0,300);?>
</p>
<p><a class="more-link" href="index.html">continue reading</a></p>
</div>
<?php } ?>
</div>
<div id="right">
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<?php
$sql = "SELECT * FROM `gallery` LIMIT 8";
$gallery = mysql_query($sql);
if ($gallery && mysql_num_rows($gallery)) {
while ($row = mysql_fetch_assoc($gallery)) {
?>
<a class="cbox" href="<?php echo $upload_url.$row['path'];?>"><img height="40" width="40" src="<?php echo $upload_url.$row['path']; ?>"/> </a>
<?php } } ?>
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/index.php
|
PHP
|
mit
| 8,859
|
<html>
<head>
<title>jQuery</title>
<style type="text/css">
#box{
width:150px;
height:80px;
background:#69f;
color:#fff;
padding:20px;
}
</style>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var url = $(this).attr("href");
alert(url);
//.animate(things to change, speed, callback);
$('#box').animate( {'margin-top': '300px','margin-left': '300px' },1000 );
$("#box").fadeOut("slow");
return false;
});
$(".display").click(function(){
//$("#box").fadeIn("slow");
$("#box").slideToggle("slow");
//$("#box").animate({ backgroundColor: "#fbc7c7" }, "fast");
return false;
});
});
</script>
</head>
<body>
<div id="box">
this is some text
<a href="http://facebook.com" class="delete">x</a>
</div>
<a href="#" class="display">Display</a>
</body>
</html>
|
069ka-ambition-cms
|
trunk/jquery.php
|
Hack
|
mit
| 1,002
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to Database</h1>
<?php
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/base.php
|
PHP
|
mit
| 3,282
|
<?php
if (!$_SESSION['login']) exit;
?>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="admin.php">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href="admin.php">Home</a></li>
<li><a href="navigations.php">Navigations</a></li>
<li><a href="posts.php">Posts</a></li>
<li><a href="settings.php">Settings</a></li>
<li><a href="gallery.php">Gallery</a></li>
<li><a href="#contact">Feedback</a></li>
<li><a href="logout.php">Logout - <?php echo $_SESSION['username']; ?></a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
|
069ka-ambition-cms
|
trunk/admin/views/nav.php
|
PHP
|
mit
| 1,071
|
<?php
include "../includes/common.php";
$id = $_GET['id'];
if ($id) {
$sql = "select * from `gallery` where `id`=$id;";
$r = mysql_query($sql);
$pic = mysql_fetch_assoc($r);
$picture_from_db = $pic['path'];
if ($picture_from_db!= "") {
$filename = "../../uploads/" . $picture_from_db ;
unlink($filename);
}
$delsql = "delete from `gallery` where `id` = $id";
mysql_query ($delsql);
}
header ("location: ../gallery.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/gallery_delete.php
|
PHP
|
mit
| 504
|
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `users` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../database.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/user_delete - Copy.php
|
PHP
|
mit
| 392
|
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$sql = "";
//Step - 4 (Grab / Process / Execute query)
$sql = "delete from `users` where `id` = $id";
mysql_query($sql);
//Step - 5 (Close connection)
mysql_close($con);
//redirect to main page
header ("location: ../database.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/steps.php
|
PHP
|
mit
| 465
|
<?php
if (isset($_POST['submit'])) {
$error = false;
$name = trim($_POST['name']);
$slug = implode("-",explode(" ", strtolower(trim($name))));
if($name == '') {
$error = true;
$name_error = "Please provide username";
}
//if ($username != "" && $password !="" && $email !="" ) {
if(!$error) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$sql = "INSERT INTO `navigation_groups` (`id`, `name`, `slug`) VALUES (NULL, '$name','$slug');";
mysql_query($sql);
header ("location: ../navigations.php");
}
}
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/nav_group_add.php
|
PHP
|
mit
| 627
|
<?php
include "includes/common.php";
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `navigations` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../navigations.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/nav_delete.php
|
PHP
|
mit
| 289
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: ../login.php");
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
$id= $_GET['id'];
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users` where `id` = $id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
$password = md5($password);
$sql_update = "UPDATE `users` SET `username` = '$username', `password` = '$password', `email` = '$email' WHERE `id` = $id";
mysql_query($sql_update);
header ("location: ../database.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>PHP / MySql</h1>
<p>Basic CRUD oparations on Database</p>
<br/>
<h3>Update User '<?php echo $row['username']; ?>' </h3>
<br/><br/>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php echo $row['username']; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="<?php echo $row['password']; ?>" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php echo $row['email']; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Update User" type="submit" class="btn" />
</div>
</div>
</form>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/dbactions/user_edit.php
|
PHP
|
mit
| 5,762
|
<?php
include "../includes/common.php";
if (isset($_POST['submit'])) {
$link_text = $_POST['link_text'];
$url = $_POST['url'];
$description = $_POST['description'];
$group_id = $_POST['group_id'];
//if ($username != "" && $password !="" && $email !="" ) {
if($link_text !="" && $url != "" && $group_id !="") {
$now = time();
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$sql = "INSERT INTO `navigations` (`id`, `link_text`, `url`, `description`, `group_id`, `created_at`) VALUES (NULL, '$link_text','$url', '$description','$group_id', '$now');";
mysql_query($sql);
}
}
header ("location: ../navigations.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/nav_add.php
|
PHP
|
mit
| 742
|
<?php
if(isset($_POST['submit'])) {
include "includes/common.php";
//get user input from GET / POST method
/*
echo "<pre>";
print_r($_POST);
var_export($_POST);
echo "</pre>";
*/
$action = $_GET['action'];
$name = $_POST['name'];
$caption = $_POST['caption'];
$submit = $data['submit'];
if ($name !="" && $caption != "" && isset($_FILES)) {
$upload_dir = '../uploads';
//tmp_name holds temporary file for uploaded file
$source_file = $_FILES['image']['tmp_name'];
//the 'name' key of the array holds original filename
//we can use original file name here as our destination filename. it will be saved inside our upload directory
$destination_file = time()."_".$_FILES['image']['name'];
$ext = substr($_FILES['image']['name'], -3);
if (in_array($ext, array("jpg","gif","bmp","png") )){
if (move_uploaded_file($source_file, $upload_dir."/".$destination_file)){
//file upload done;
}else {
$hasError = true;
$file_error = "Couldn't upload file. Retry later";
}
}else {
$hasError = true;
$file_error = "Only images are allowed";
}
}
/*
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'youremail@yoursite.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} */
if($hasError != true){
if ($action=="update") {
$id = $data['userid'];
$password = md5($password);
//server side validation of input data
//build query
$sql = "update `users` set `username` = \"$username\", `password` = \"$password\", `email` = \"$email\", `first_name`= \"$firstname\", `mid_name` = \"$midname\", `last_name` =\"$lastname\", `phone` = \"$phone\", `address` = \"$address\", `website` = \"$website\", `picture` = \"$destination_file\", `created_at` =$created_at , `user_type`= $usertype where `id` = $id ;";
} else { // insert date
$password = md5($password);
//build query
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `email`, `first_name`, `mid_name`, `last_name`, `phone`, `address`, `website`, `picture`, `created_at`, `user_type`) VALUES (NULL, \"$username\", \"$password\", \"$email\", \"$firstname\", \"$midname\", \"$lastname\", \"$phone\", \"$address\", \"$website\", \"$destination_file\", $created_at, $usertype);";
}
mysql_query ($sql);
header ("location: users.php");
}
}
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/gallery.php
|
PHP
|
mit
| 2,546
|
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$id = $_GET['id'];
$sql = "delete from `users` where `id` = $id";
if (mysql_query($sql)){
echo "SUCCESS";
}else {
echo "ERROR";
}
exit;
//echo "user id ". $_GET['id'] . " deleted";
//header ("location: ../database.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/user_delete.php
|
PHP
|
mit
| 357
|
<?php
include "includes/common.php";
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `navigation_groups` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../navigations.php");
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/nav_group_delete.php
|
PHP
|
mit
| 299
|
<?php
if (!$_SESSION['login']) header ("location: ../index.php");
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("cms");
if (isset($_POST['submit'])) {
$site_name = trim($_POST['site_name']);
$site_slogan = trim($_POST['site_slogan']);
$sql_update = "UPDATE `settings` SET `site_name` = '$site_name', `site_slogan` = '$site_slogan'";
mysql_query($sql_update);
header ("location: settings.php");
}
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/settings_update.php
|
PHP
|
mit
| 528
|
<?php
if (isset($_POST['submit'])) {
$error = false;
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
if($username == '') {
$error = true;
$username_error = "Please provide username";
}
if($password == '') {
$error = true;
$password_error = "Please provide password";
}else {
$password = md5($_POST['password']);
}
if($email == '') {
$error = true;
$email_error = "Please provide email";
}
//if ($username != "" && $password !="" && $email !="" ) {
if(!$error) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, '$username','$password','$email');";
mysql_query($sql);
header ("location: admin.php");
}
}
?>
|
069ka-ambition-cms
|
trunk/admin/dbactions/user_add.php
|
PHP
|
mit
| 904
|
<?php
session_start();
//unset session
$_SESSION['login'] = 0;
$_SESSION['username'] = "";
$_SESSION['user_id'] = 0;
//or
//unset($_SESSION['login']);
//unset($_SESSION['username']);
session_destroy();
//redirect to login page
header ("location: index.php");
?>
|
069ka-ambition-cms
|
trunk/admin/logout.php
|
PHP
|
mit
| 301
|
<?php
session_start();
if ($_SESSION['login']) header ("location: admin.php");
include "includes/common.php";
//$username = addslashes($_POST['username']);
$username = addslashes($_POST['username']);
$password = addslashes($_POST['password']);
if ($_POST['submit'] && ($username !="" && $password !="" )) {
$password = md5($_POST['password']);
$sql = "select * from `users` where `username` = '$username' and `password` = '$password'";
$result = mysql_query($sql);
$count_result = mysql_num_rows($result);
if ($count_result == 1 ) {
//echo "Login Success!";
//set session
$_SESSION['login'] = 1;
$_SESSION['username'] = $username;
$user = mysql_fetch_assoc($result);
$_SESSION['user_id'] = $user['id'];
//redirect to database
header ("location: admin.php");
}else {
echo "Login failed!";
}
} else {
echo "Please provide username & password!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign in · Twitter Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin input[type="text"],
.form-signin input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<div class="container">
<form class="form-signin" action="" method="POST" >
<h2 class="form-signin-heading">Login</h2>
Username: <input name="username" value="" type="text" class="input-block-level" >
Password: <input name="password" value="" type="password" class="input-block-level" >
<button name="submit" value="Sign In" class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/index.php
|
PHP
|
mit
| 4,592
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "dbactions/settings_update.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete this user ?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Settings</h1>
<br/>
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("cms");
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `settings`";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
?>
<table class="table table-hover">
<thead>
<tr>
<th>Sitename</th>
<th>Slogan</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row['site_name'];?></td>
<td><?php echo $row['site_slogan'];?></td>
</tr>
</tbody>
</table>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Update Settings</h3>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Site Name</label>
<div class="controls">
<input type="text" name="site_name" value="<?php if (isset($site_name)) {echo $site_name; } else {echo $row['site_name'];} ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Site Slgan</label>
<div class="controls">
<input type="text" id="site_slogan" name="site_slogan" value="<?php if (isset($site_slogan)) {echo $site_slogan;} else {echo $row['site_slogan'];} ?>" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Update Settings" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/settings.php
|
PHP
|
mit
| 4,957
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "dbactions/user_add.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var url = $(this).attr("href"); //alert(url);
var btn = $(this);
//$(this).closest('tr').fadeOut("slow");
$.ajax({
type: "GET",
url: url,
success: function(res) {
if (res == "SUCCESS") {
$(btn).closest('tr').fadeOut('slow');
}else {
alert("Couldn't delete ! Retry.");
}
}
});
return false;
});
});
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Users</h1>
<br/>
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("cms");
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users`";
$result = mysql_query($sql);
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo $row['email'];?></td>
<td>
<a href="">View</a> |
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a class="delete" href="dbactions/user_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Add New Users</h3>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php if (isset($username)) echo $username; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php if (isset($email)) echo $email; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add User" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/admin.php
|
PHP
|
mit
| 6,048
|
<?php
$site_url = "http://localhost/ambition/class/";
$upload_url = "http://localhost/ambition/class/uploads/";
define('UPLOAD_PATH', 'http://localhost/ambition/class/uploads/' );
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
?>
|
069ka-ambition-cms
|
trunk/admin/includes/common.php
|
PHP
|
mit
| 269
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "includes/common.php";
include "dbactions/user_add.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Navigations</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
/*
$sql = "SELECT navigation_groups.*,navigations.* from `navigations`
JOIN `navigation_group`
ON navigations.group_id = navigation_groups.id
"; */
$sql = "SELECT * FROM `navigations`
LEFT JOIN `navigation_groups`
ON navigations.group_id = navigation_groups.id ";
$result = mysql_query($sql);
if ($result && mysql_num_rows($result)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Link</th>
<th>Description</th>
<th>Group</th>
<th>Click Count</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><a href="<?php echo $site_url.$row['url'];?>"><?php echo $row['link_text'];?> </a></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['click_count']; ?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/nav_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No navigation links found";
}
//Step - 5 (Close connection)
?>
<h3>Add New Link</h3>
<form class="form-horizontal" action="dbactions/nav_add.php" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Link Text</label>
<div class="controls">
<input type="text" name="link_text" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">URL</label>
<div class="controls">
<input type="text" name="url" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Description</label>
<div class="controls">
<input type="text" name="description" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Group</label>
<div class="controls">
<select name="group_id">
<option value="">Select Group</option>
<?php
$sql_group = "SELECT * from `navigation_groups`";
$result_group = mysql_query($sql_group);
while ($row = mysql_fetch_assoc($result_group)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add Link" type="submit" class="btn" />
</div>
</div>
</form>
<h1>Navigation Groups</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
$sql_group = "SELECT * from `navigation_groups`";
$result_group = mysql_query($sql_group);
if ($result_group && mysql_num_rows($result_group)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Slug</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result_group)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['slug']; ?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/nav_group_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No navigation groups found";
}
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Add New Navigation Group</h3>
<form class="form-horizontal" action="dbactions/nav_group_add.php" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Name</label>
<div class="controls">
<input type="text" name="name" value="">
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add Link" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/navigations.php
|
PHP
|
mit
| 8,151
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "includes/common.php";
if(isset($_POST['submit'])) {
/* echo "<pre>";
echo "post";
print_r($_POST);
echo "files";
print_r($_FILES);
echo "session";
print_r($_SESSION);
echo "</pre>";
exit; */
$title = $_POST['title'];
$content = $_POST['content'];
$category = $_POST['category'];
$status = $_POST['status'];
$error = "";
if ($title !="" && $content != "") {
$upload_dir = '../uploads';
//tmp_name holds temporary file for uploaded file
$source_file = $_FILES['image']['tmp_name'];
//the 'name' key of the array holds original filename
//we can use original file name here as our destination filename. it will be saved inside our upload directory
$destination_file = time()."_".$_FILES['image']['name'];
if (move_uploaded_file($source_file, $upload_dir."/".$destination_file)){
//file upload done;
$now = time();
$user_id = $_SESSION['user_id'];
$sql = "INSERT INTO `post` VALUES (NULL, \"$user_id\", \"$title\", \"$content\",\"$category\",\"$destination_file\",\"$now\", '$status');";
mysql_query ($sql);
//header ("location: gallery.php");
}else {
$error .= "Couldn't upload file. Retry later";
}
}else {
$error .= "Please provide title and content.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script src="../third_party/ckeditor/ckeditor.js"></script>
<link rel="stylesheet" href="../third_party/ckeditor/sample.css">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>POSTS</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
$sql = "SELECT post.*, post_categories.name, users.username from `post`
JOIN `post_categories` ON post.category = post_categories.id
JOIN `users` ON post.user_id = users.id
";
//$sql = "SELECT * FROM `post`";
$result = mysql_query($sql);
if ($result && mysql_num_rows($result)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Image</th>
<th>Category</th>
<th>Posted By</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['title']; ?></td>
<td><img width="100" height="100" src="<?php echo UPLOAD_PATH.$row['image']; ?>" /></td>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo ($row['status'])? "Published" : "Draft";?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/gallery_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No posts found";
}
//Step - 5 (Close connection)
?>
<h3>Add Post</h3>
<?php
if (isset($error)) {
echo "<p style='color:red;'>$error<br/></p>";
}
?>
<form class="form-horizontal" enctype="multipart/form-data" action="" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Title</label>
<div class="controls">
<input type="text" name="title" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Image</label>
<div class="controls">
<input type="file" name="image" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Publish</label>
<div class="controls">
<input type="checkbox" name="status" value="1">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Category</label>
<div class="controls">
<select name="category">
<option value="">Select Category</option>
<?php
$sql_group = "SELECT * from `post_categories`";
$result_group = mysql_query($sql_group);
while ($row = mysql_fetch_assoc($result_group)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Content</label>
<div class="controls">
<textarea class="ckeditor input-xxlarge" name="content" rows="10" col="80"></textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add Post" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/posts.php
|
PHP
|
mit
| 7,986
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: index.php");
include "includes/common.php";
if(isset($_POST['submit'])) {
/*
echo "<pre>";
print_r($_POST);
print_r($_FILES);
echo "</pre>";
*/
$name = $_POST['name'];
$caption = $_POST['caption'];
$status = $_POST['status'];
$error = "";
if ($name !="" && $caption != "" && isset($_FILES)) {
$upload_dir = '../uploads';
//tmp_name holds temporary file for uploaded file
$source_file = $_FILES['image']['tmp_name'];
//the 'name' key of the array holds original filename
//we can use original file name here as our destination filename. it will be saved inside our upload directory
$destination_file = time()."_".$_FILES['image']['name'];
$ext = substr($_FILES['image']['name'], -3);
if (in_array($ext, array("jpg","gif","bmp","png") )){
if (move_uploaded_file($source_file, $upload_dir."/".$destination_file)){
//file upload done;
$now = time();
$sql = "INSERT INTO `gallery` (`id`, `name`, `path`, `caption`, `status`, `created_at`) VALUES (NULL, \"$name\", \"$destination_file\", \"$caption\",\"$status\", '$now');";
mysql_query ($sql);
//header ("location: gallery.php");
}else {
$error .= "Couldn't upload file. Retry later";
}
}else {
$error .= "Only images are allowed";
}
}else {
$error .= "Please provide all info.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<!-- include navigation here -->
<?php include "views/nav.php"; ?>
<div class="container">
<h1>Gallery</h1>
<br/>
<?php
//Step - 3 (SQL / Get result)
/*
$sql = "SELECT navigation_groups.*,navigations.* from `navigations`
JOIN `navigation_group`
ON navigations.group_id = navigation_groups.id
"; */
$sql = "SELECT * FROM `gallery`";
$result = mysql_query($sql);
if ($result && mysql_num_rows($result)) {
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Image</th>
<th>Name</th>
<th>Caption</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><a href="<?php echo $upload_url."/".$row['path'];?>"><img height="100" width="100" src="<?php echo $upload_url.$row['path']; ?>"/> </a></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['caption'];?></td>
<td><?php echo ($row['status'])? "Published" : "Draft";?></td>
<td>
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/gallery_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
} else {
echo "No images found";
}
//Step - 5 (Close connection)
?>
<h3>Add New Image</h3>
<?php
if (isset($error)) {
echo "<p style='color:red;'>$error<br/></p>";
}
?>
<form class="form-horizontal" enctype="multipart/form-data" action="" method="POST">
<div class="control-group">
<label class="control-label" for="first_name">Name</label>
<div class="controls">
<input type="text" name="name" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Image</label>
<div class="controls">
<input type="file" name="image" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Caption</label>
<div class="controls">
<input type="text" class="span4" name="caption" value="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="first_name">Publish</label>
<div class="controls">
<input type="checkbox" name="status" value="1">
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Upload Image" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/admin/gallery.php
|
PHP
|
mit
| 7,247
|
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
!function ($) {
$(function(){
var $window = $(window)
// Disable certain links in docs
$('section [href^=#]').click(function (e) {
e.preventDefault()
})
// side bar
$('.bs-docs-sidenav').affix({
offset: {
top: function () { return $window.width() <= 980 ? 290 : 210 }
, bottom: 270
}
})
// make code pretty
window.prettyPrint && prettyPrint()
// add-ons
$('.add-on :checkbox').on('click', function () {
var $this = $(this)
, method = $this.attr('checked') ? 'addClass' : 'removeClass'
$(this).parents('.add-on')[method]('active')
})
// add tipsies to grid for scaffolding
if ($('#gridSystem').length) {
$('#gridSystem').tooltip({
selector: '.show-grid > div'
, title: function () { return $(this).width() + 'px' }
})
}
// tooltip demo
$('.tooltip-demo').tooltip({
selector: "a[rel=tooltip]"
})
$('.tooltip-test').tooltip()
$('.popover-test').popover()
// popover demo
$("a[rel=popover]")
.popover()
.click(function(e) {
e.preventDefault()
})
// button state demo
$('#fat-btn')
.click(function () {
var btn = $(this)
btn.button('loading')
setTimeout(function () {
btn.button('reset')
}, 3000)
})
// carousel demo
$('#myCarousel').carousel()
// javascript build logic
var inputsComponent = $("#components.download input")
, inputsPlugin = $("#plugins.download input")
, inputsVariables = $("#variables.download input")
// toggle all plugin checkboxes
$('#components.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsComponent.attr('checked', !inputsComponent.is(':checked'))
})
$('#plugins.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsPlugin.attr('checked', !inputsPlugin.is(':checked'))
})
$('#variables.download .toggle-all').on('click', function (e) {
e.preventDefault()
inputsVariables.val('')
})
// request built javascript
$('.download-btn .btn').on('click', function () {
var css = $("#components.download input:checked")
.map(function () { return this.value })
.toArray()
, js = $("#plugins.download input:checked")
.map(function () { return this.value })
.toArray()
, vars = {}
, img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png']
$("#variables.download input")
.each(function () {
$(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
})
$.ajax({
type: 'POST'
, url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com'
, dataType: 'jsonpi'
, params: {
js: js
, css: css
, vars: vars
, img: img
}
})
})
})
// Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi
$.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) {
var url = opts.url;
return {
send: function(_, completeCallback) {
var name = 'jQuery_iframe_' + jQuery.now()
, iframe, form
iframe = $('<iframe>')
.attr('name', name)
.appendTo('head')
form = $('<form>')
.attr('method', opts.type) // GET or POST
.attr('action', url)
.attr('target', name)
$.each(opts.params, function(k, v) {
$('<input>')
.attr('type', 'hidden')
.attr('name', k)
.attr('value', typeof v == 'string' ? v : JSON.stringify(v))
.appendTo(form)
})
form.appendTo('body').submit()
}
}
})
}(window.jQuery)
|
069ka-ambition-cms
|
trunk/admin/assets/js/application.js
|
JavaScript
|
mit
| 3,954
|
/*
Holder - 1.6 - client side image placeholders
(c) 2012 Ivan Malopinsky / http://imsky.co
Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
Commercial use requires attribution.
*/
var Holder = Holder || {};
(function (app, win) {
var preempted = false,
fallback = false,
canvas = document.createElement('canvas');
//getElementsByClassName polyfill
document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s})
//getComputedStyle polyfill
window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this})
//http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications
function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}};
//https://gist.github.com/991057 by Jed Schmidt with modifications
function selector(a){
a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]);
var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret;
}
//shallow object property extend
function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}
function text_size(width, height, template) {
var dimension_arr = [height, width].sort();
var maxFactor = Math.round(dimension_arr[1] / 16),
minFactor = Math.round(dimension_arr[0] / 16);
var text_height = Math.max(template.size, maxFactor);
return {
height: text_height
}
}
function draw(ctx, dimensions, template, ratio) {
var ts = text_size(dimensions.width, dimensions.height, template);
var text_height = ts.height;
var width = dimensions.width * ratio, height = dimensions.height * ratio;
canvas.width = width;
canvas.height = height;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = template.background;
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = template.foreground;
ctx.font = "bold " + text_height + "px sans-serif";
var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height);
if (ctx.measureText(text).width / width > 1) {
text_height = template.size / (ctx.measureText(text).width / width);
}
ctx.font = "bold " + (text_height * ratio) + "px sans-serif";
ctx.fillText(text, (width / 2), (height / 2), width);
return canvas.toDataURL("image/png");
}
function render(mode, el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
var ratio = 1;
if(window.devicePixelRatio && window.devicePixelRatio > 1){
ratio = window.devicePixelRatio;
}
if (mode == "image") {
el.setAttribute("data-src", src);
el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
el.style.width = dimensions.width + "px";
el.style.height = dimensions.height + "px";
if (fallback) {
el.style.backgroundColor = theme.background;
}
else{
el.setAttribute("src", draw(ctx, dimensions, theme, ratio));
}
} else {
if (!fallback) {
el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")";
el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px";
}
}
};
function fluid(el, holder, src) {
var dimensions = holder.dimensions,
theme = holder.theme,
text = holder.text;
var dimensions_caption = dimensions.width + "x" + dimensions.height;
theme = (text ? extend(theme, {
text: text
}) : theme);
var fluid = document.createElement("table");
fluid.setAttribute("cellspacing",0)
fluid.setAttribute("cellpadding",0)
fluid.setAttribute("border",0)
var row = document.createElement("tr")
.appendChild(document.createElement("td")
.appendChild(document.createTextNode(theme.text)));
fluid.style.backgroundColor = theme.background;
fluid.style.color = theme.foreground;
fluid.className = el.className + " holderjs-fluid";
fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px");
fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px");
fluid.id = el.id;
var frag = document.createDocumentFragment(),
tbody = document.createElement("tbody"),
tr = document.createElement("tr"),
td = document.createElement("td");
tr.appendChild(td);
tbody.appendChild(tr);
frag.appendChild(tbody);
if (theme.text) {
td.appendChild(document.createTextNode(theme.text))
fluid.appendChild(frag);
} else {
td.appendChild(document.createTextNode(dimensions_caption))
fluid.appendChild(frag);
fluid_images.push(fluid);
setTimeout(fluid_update, 0);
}
el.parentNode.replaceChild(fluid, el);
}
function fluid_update() {
for (i in fluid_images) {
var el = fluid_images[i];
var label = el.getElementsByTagName("td")[0].firstChild;
label.data = el.offsetWidth + "x" + el.offsetHeight;
}
}
function parse_flags(flags, options) {
var ret = {
theme: settings.themes.gray
}, render = false;
for (sl = flags.length, j = 0; j < sl; j++) {
var flag = flags[j];
if (app.flags.dimensions.match(flag)) {
render = true;
ret.dimensions = app.flags.dimensions.output(flag);
} else if (app.flags.fluid.match(flag)) {
render = true;
ret.dimensions = app.flags.fluid.output(flag);
ret.fluid = true;
} else if (app.flags.colors.match(flag)) {
ret.theme = app.flags.colors.output(flag);
} else if (options.themes[flag]) {
//If a theme is specified, it will override custom colors
ret.theme = options.themes[flag];
} else if (app.flags.text.match(flag)) {
ret.text = app.flags.text.output(flag);
}
}
return render ? ret : false;
};
if (!canvas.getContext) {
fallback = true;
} else {
if (canvas.toDataURL("image/png")
.indexOf("data:image/png") < 0) {
//Android doesn't support data URI
fallback = true;
} else {
var ctx = canvas.getContext("2d");
}
}
var fluid_images = [];
var settings = {
domain: "holder.js",
images: "img",
elements: ".holderjs",
themes: {
"gray": {
background: "#eee",
foreground: "#aaa",
size: 12
},
"social": {
background: "#3a5a97",
foreground: "#fff",
size: 12
},
"industrial": {
background: "#434A52",
foreground: "#C2F200",
size: 12
}
},
stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}"
};
app.flags = {
dimensions: {
regex: /(\d+)x(\d+)/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: +exec[1],
height: +exec[2]
}
}
},
fluid: {
regex: /([0-9%]+)x([0-9%]+)/,
output: function (val) {
var exec = this.regex.exec(val);
return {
width: exec[1],
height: exec[2]
}
}
},
colors: {
regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i,
output: function (val) {
var exec = this.regex.exec(val);
return {
size: settings.themes.gray.size,
foreground: "#" + exec[2],
background: "#" + exec[1]
}
}
},
text: {
regex: /text\:(.*)/,
output: function (val) {
return this.regex.exec(val)[1];
}
}
}
for (var flag in app.flags) {
app.flags[flag].match = function (val) {
return val.match(this.regex)
}
}
app.add_theme = function (name, theme) {
name != null && theme != null && (settings.themes[name] = theme);
return app;
};
app.add_image = function (src, el) {
var node = selector(el);
if (node.length) {
for (var i = 0, l = node.length; i < l; i++) {
var img = document.createElement("img")
img.setAttribute("data-src", src);
node[i].appendChild(img);
}
}
return app;
};
app.run = function (o) {
var options = extend(settings, o),
images_nodes = selector(options.images),
elements = selector(options.elements),
preempted = true,
images = [];
for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]);
var holdercss = document.createElement("style");
holdercss.type = "text/css";
holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet;
document.getElementsByTagName("head")[0].appendChild(holdercss);
var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)");
for (var l = elements.length, i = 0; i < l; i++) {
var src = window.getComputedStyle(elements[i], null)
.getPropertyValue("background-image");
var flags = src.match(cssregex);
if (flags) {
var holder = parse_flags(flags[1].split("/"), options);
if (holder) {
render("background", elements[i], holder, src);
}
}
}
for (var l = images.length, i = 0; i < l; i++) {
var src = images[i].getAttribute("src") || images[i].getAttribute("data-src");
if (src != null && src.indexOf(options.domain) >= 0) {
var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1)
.split("/"), options);
if (holder) {
if (holder.fluid) {
fluid(images[i], holder, src);
} else {
render("image", images[i], holder, src);
}
}
}
}
return app;
};
contentLoaded(win, function () {
if (window.addEventListener) {
window.addEventListener("resize", fluid_update, false);
window.addEventListener("orientationchange", fluid_update, false);
} else {
window.attachEvent("onresize", fluid_update)
}
preempted || app.run();
});
})(Holder, window);
|
069ka-ambition-cms
|
trunk/admin/assets/js/holder/holder.js
|
JavaScript
|
mit
| 10,517
|
.com { color: #93a1a1; }
.lit { color: #195f91; }
.pun, .opn, .clo { color: #93a1a1; }
.fun { color: #dc322f; }
.str, .atv { color: #D14; }
.kwd, .prettyprint .tag { color: #1e347b; }
.typ, .atn, .dec, .var { color: teal; }
.pln { color: #48484c; }
.prettyprint {
padding: 8px;
background-color: #f7f7f9;
border: 1px solid #e1e1e8;
}
.prettyprint.linenums {
-webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
-moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
}
/* Specify class=linenums on a pre to get line numbering */
ol.linenums {
margin: 0 0 0 33px; /* IE indents via margin-left */
}
ol.linenums li {
padding-left: 12px;
color: #bebec5;
line-height: 20px;
text-shadow: 0 1px 0 #fff;
}
|
069ka-ambition-cms
|
trunk/admin/assets/js/google-code-prettify/prettify.css
|
CSS
|
mit
| 817
|
/* Add additional stylesheets below
-------------------------------------------------- */
/*
Bootstrap's documentation styles
Special styles for presenting Bootstrap's documentation and examples
*/
/* Body and structure
-------------------------------------------------- */
body {
position: relative;
padding-top: 40px;
}
/* Code in headings */
h3 code {
font-size: 14px;
font-weight: normal;
}
/* Tweak navbar brand link to be super sleek
-------------------------------------------------- */
body > .navbar {
font-size: 13px;
}
/* Change the docs' brand */
body > .navbar .brand {
padding-right: 0;
padding-left: 0;
margin-left: 20px;
float: right;
font-weight: bold;
color: #000;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.125);
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
transition: all .2s linear;
}
body > .navbar .brand:hover {
text-decoration: none;
text-shadow: 0 1px 0 rgba(255,255,255,.1), 0 0 30px rgba(255,255,255,.4);
}
/* Sections
-------------------------------------------------- */
/* padding for in-page bookmarks and fixed navbar */
section {
padding-top: 30px;
}
section > .page-header,
section > .lead {
color: #5a5a5a;
}
section > ul li {
margin-bottom: 5px;
}
/* Separators (hr) */
.bs-docs-separator {
margin: 40px 0 39px;
}
/* Faded out hr */
hr.soften {
height: 1px;
margin: 70px 0;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,.1), rgba(0,0,0,0));
border: 0;
}
/* Jumbotrons
-------------------------------------------------- */
/* Base class
------------------------- */
.jumbotron {
position: relative;
padding: 40px 0;
color: #fff;
text-align: center;
text-shadow: 0 1px 3px rgba(0,0,0,.4), 0 0 30px rgba(0,0,0,.075);
background: #020031; /* Old browsers */
background: -moz-linear-gradient(45deg, #020031 0%, #6d3353 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left bottom, right top, color-stop(0%,#020031), color-stop(100%,#6d3353)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(45deg, #020031 0%,#6d3353 100%); /* IE10+ */
background: linear-gradient(45deg, #020031 0%,#6d3353 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#020031', endColorstr='#6d3353',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
-webkit-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
box-shadow: inset 0 3px 7px rgba(0,0,0,.2), inset 0 -3px 7px rgba(0,0,0,.2);
}
.jumbotron h1 {
font-size: 80px;
font-weight: bold;
letter-spacing: -1px;
line-height: 1;
}
.jumbotron p {
font-size: 24px;
font-weight: 300;
line-height: 1.25;
margin-bottom: 30px;
}
/* Link styles (used on .masthead-links as well) */
.jumbotron a {
color: #fff;
color: rgba(255,255,255,.5);
-webkit-transition: all .2s ease-in-out;
-moz-transition: all .2s ease-in-out;
transition: all .2s ease-in-out;
}
.jumbotron a:hover {
color: #fff;
text-shadow: 0 0 10px rgba(255,255,255,.25);
}
/* Download button */
.masthead .btn {
padding: 19px 24px;
font-size: 24px;
font-weight: 200;
color: #fff; /* redeclare to override the `.jumbotron a` */
border: 0;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.masthead .btn:hover {
-webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
-moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
box-shadow: inset 0 1px 0 rgba(255,255,255,.1), 0 1px 5px rgba(0,0,0,.25);
}
.masthead .btn:active {
-webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
-moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
box-shadow: inset 0 2px 4px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.1);
}
/* Pattern overlay
------------------------- */
.jumbotron .container {
position: relative;
z-index: 2;
}
.jumbotron:after {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(../img/bs-docs-masthead-pattern.png) repeat center center;
opacity: .4;
}
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1) {
.jumbotron:after {
background-size: 150px 150px;
}
}
/* Masthead (docs home)
------------------------- */
.masthead {
padding: 70px 0 80px;
margin-bottom: 0;
color: #fff;
}
.masthead h1 {
font-size: 120px;
line-height: 1;
letter-spacing: -2px;
}
.masthead p {
font-size: 40px;
font-weight: 200;
line-height: 1.25;
}
/* Textual links in masthead */
.masthead-links {
margin: 0;
list-style: none;
}
.masthead-links li {
display: inline;
padding: 0 10px;
color: rgba(255,255,255,.25);
}
/* Social proof buttons from GitHub & Twitter */
.bs-docs-social {
padding: 15px 0;
text-align: center;
background-color: #f5f5f5;
border-top: 1px solid #fff;
border-bottom: 1px solid #ddd;
}
/* Quick links on Home */
.bs-docs-social-buttons {
margin-left: 0;
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.bs-docs-social-buttons li {
display: inline-block;
padding: 5px 8px;
line-height: 1;
*display: inline;
*zoom: 1;
}
/* Subhead (other pages)
------------------------- */
.subhead {
text-align: left;
border-bottom: 1px solid #ddd;
}
.subhead h1 {
font-size: 60px;
}
.subhead p {
margin-bottom: 20px;
}
.subhead .navbar {
display: none;
}
/* Marketing section of Overview
-------------------------------------------------- */
.marketing {
text-align: center;
color: #5a5a5a;
}
.marketing h1 {
margin: 60px 0 10px;
font-size: 60px;
font-weight: 200;
line-height: 1;
letter-spacing: -1px;
}
.marketing h2 {
font-weight: 200;
margin-bottom: 5px;
}
.marketing p {
font-size: 16px;
line-height: 1.5;
}
.marketing .marketing-byline {
margin-bottom: 40px;
font-size: 20px;
font-weight: 300;
line-height: 1.25;
color: #999;
}
.marketing-img {
display: block;
margin: 0 auto 30px;
max-height: 145px;
}
/* Footer
-------------------------------------------------- */
.footer {
text-align: center;
padding: 30px 0;
margin-top: 70px;
border-top: 1px solid #e5e5e5;
background-color: #f5f5f5;
}
.footer p {
margin-bottom: 0;
color: #777;
}
.footer-links {
margin: 10px 0;
}
.footer-links li {
display: inline;
padding: 0 2px;
}
.footer-links li:first-child {
padding-left: 0;
}
/* Special grid styles
-------------------------------------------------- */
.show-grid {
margin-top: 10px;
margin-bottom: 20px;
}
.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
min-height: 40px;
line-height: 40px;
}
.show-grid:hover [class*="span"] {
background: #ddd;
}
.show-grid .show-grid {
margin-top: 0;
margin-bottom: 0;
}
.show-grid .show-grid [class*="span"] {
margin-top: 5px;
}
.show-grid [class*="span"] [class*="span"] {
background-color: #ccc;
}
.show-grid [class*="span"] [class*="span"] [class*="span"] {
background-color: #999;
}
/* Mini layout previews
-------------------------------------------------- */
.mini-layout {
border: 1px solid #ddd;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.075);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.075);
box-shadow: 0 1px 2px rgba(0,0,0,.075);
}
.mini-layout,
.mini-layout .mini-layout-body,
.mini-layout.fluid .mini-layout-sidebar {
height: 300px;
}
.mini-layout {
margin-bottom: 20px;
padding: 9px;
}
.mini-layout div {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.mini-layout .mini-layout-body {
background-color: #dceaf4;
margin: 0 auto;
width: 70%;
}
.mini-layout.fluid .mini-layout-sidebar,
.mini-layout.fluid .mini-layout-header,
.mini-layout.fluid .mini-layout-body {
float: left;
}
.mini-layout.fluid .mini-layout-sidebar {
background-color: #bbd8e9;
width: 20%;
}
.mini-layout.fluid .mini-layout-body {
width: 77.5%;
margin-left: 2.5%;
}
/* Download page
-------------------------------------------------- */
.download .page-header {
margin-top: 36px;
}
.page-header .toggle-all {
margin-top: 5px;
}
/* Space out h3s when following a section */
.download h3 {
margin-bottom: 5px;
}
.download-builder input + h3,
.download-builder .checkbox + h3 {
margin-top: 9px;
}
/* Fields for variables */
.download-builder input[type=text] {
margin-bottom: 9px;
font-family: Menlo, Monaco, "Courier New", monospace;
font-size: 12px;
color: #d14;
}
.download-builder input[type=text]:focus {
background-color: #fff;
}
/* Custom, larger checkbox labels */
.download .checkbox {
padding: 6px 10px 6px 25px;
font-size: 13px;
line-height: 18px;
color: #555;
background-color: #f9f9f9;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
}
.download .checkbox:hover {
color: #333;
background-color: #f5f5f5;
}
.download .checkbox small {
font-size: 12px;
color: #777;
}
/* Variables section */
#variables label {
margin-bottom: 0;
}
/* Giant download button */
.download-btn {
margin: 36px 0 108px;
}
#download p,
#download h4 {
max-width: 50%;
margin: 0 auto;
color: #999;
text-align: center;
}
#download h4 {
margin-bottom: 0;
}
#download p {
margin-bottom: 18px;
}
.download-btn .btn {
display: block;
width: auto;
padding: 19px 24px;
margin-bottom: 27px;
font-size: 30px;
line-height: 1;
text-align: center;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/* Misc
-------------------------------------------------- */
/* Make tables spaced out a bit more */
h2 + table,
h3 + table,
h4 + table,
h2 + .row {
margin-top: 5px;
}
/* Example sites showcase */
.example-sites {
xmargin-left: 20px;
}
.example-sites img {
max-width: 100%;
margin: 0 auto;
}
.scrollspy-example {
height: 200px;
overflow: auto;
position: relative;
}
/* Fake the :focus state to demo it */
.focused {
border-color: rgba(82,168,236,.8);
-webkit-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
-moz-box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
box-shadow: inset 0 1px 3px rgba(0,0,0,.1), 0 0 8px rgba(82,168,236,.6);
outline: 0;
}
/* For input sizes, make them display block */
.docs-input-sizes select,
.docs-input-sizes input[type=text] {
display: block;
margin-bottom: 9px;
}
/* Icons
------------------------- */
.the-icons {
margin-left: 0;
list-style: none;
}
.the-icons li {
float: left;
width: 25%;
line-height: 25px;
}
.the-icons i:hover {
background-color: rgba(255,0,0,.25);
}
/* Example page
------------------------- */
.bootstrap-examples p {
font-size: 13px;
line-height: 18px;
}
.bootstrap-examples .thumbnail {
margin-bottom: 9px;
background-color: #fff;
}
/* Bootstrap code examples
-------------------------------------------------- */
/* Base class */
.bs-docs-example {
position: relative;
margin: 15px 0;
padding: 39px 19px 14px;
*padding-top: 19px;
background-color: #fff;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
/* Echo out a label for the example */
.bs-docs-example:after {
content: "Example";
position: absolute;
top: -1px;
left: -1px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
background-color: #f5f5f5;
border: 1px solid #ddd;
color: #9da0a4;
-webkit-border-radius: 4px 0 4px 0;
-moz-border-radius: 4px 0 4px 0;
border-radius: 4px 0 4px 0;
}
/* Remove spacing between an example and it's code */
.bs-docs-example + .prettyprint {
margin-top: -20px;
padding-top: 15px;
}
/* Tweak examples
------------------------- */
.bs-docs-example > p:last-child {
margin-bottom: 0;
}
.bs-docs-example .table,
.bs-docs-example .progress,
.bs-docs-example .well,
.bs-docs-example .alert,
.bs-docs-example .hero-unit,
.bs-docs-example .pagination,
.bs-docs-example .navbar,
.bs-docs-example > .nav,
.bs-docs-example blockquote {
margin-bottom: 5px;
}
.bs-docs-example .pagination {
margin-top: 0;
}
.bs-navbar-top-example,
.bs-navbar-bottom-example {
z-index: 1;
padding: 0;
height: 90px;
overflow: hidden; /* cut the drop shadows off */
}
.bs-navbar-top-example .navbar-fixed-top,
.bs-navbar-bottom-example .navbar-fixed-bottom {
margin-left: 0;
margin-right: 0;
}
.bs-navbar-top-example {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
.bs-navbar-top-example:after {
top: auto;
bottom: -1px;
-webkit-border-radius: 0 4px 0 4px;
-moz-border-radius: 0 4px 0 4px;
border-radius: 0 4px 0 4px;
}
.bs-navbar-bottom-example {
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
border-radius: 4px 4px 0 0;
}
.bs-navbar-bottom-example .navbar {
margin-bottom: 0;
}
form.bs-docs-example {
padding-bottom: 19px;
}
/* Images */
.bs-docs-example-images img {
margin: 10px;
display: inline-block;
}
/* Tooltips */
.bs-docs-tooltip-examples {
text-align: center;
margin: 0 0 10px;
list-style: none;
}
.bs-docs-tooltip-examples li {
display: inline;
padding: 0 10px;
}
/* Popovers */
.bs-docs-example-popover {
padding-bottom: 24px;
background-color: #f9f9f9;
}
.bs-docs-example-popover .popover {
position: relative;
display: block;
float: left;
width: 260px;
margin: 20px;
}
/* Dropdowns */
.bs-docs-example-submenus {
min-height: 180px;
}
.bs-docs-example-submenus > .pull-left + .pull-left {
margin-left: 20px;
}
.bs-docs-example-submenus .dropup > .dropdown-menu,
.bs-docs-example-submenus .dropdown > .dropdown-menu {
display: block;
position: static;
margin-bottom: 5px;
*width: 180px;
}
/* Responsive docs
-------------------------------------------------- */
/* Utility classes table
------------------------- */
.responsive-utilities th small {
display: block;
font-weight: normal;
color: #999;
}
.responsive-utilities tbody th {
font-weight: normal;
}
.responsive-utilities td {
text-align: center;
}
.responsive-utilities td.is-visible {
color: #468847;
background-color: #dff0d8 !important;
}
.responsive-utilities td.is-hidden {
color: #ccc;
background-color: #f9f9f9 !important;
}
/* Responsive tests
------------------------- */
.responsive-utilities-test {
margin-top: 5px;
margin-left: 0;
list-style: none;
overflow: hidden; /* clear floats */
}
.responsive-utilities-test li {
position: relative;
float: left;
width: 25%;
height: 43px;
font-size: 14px;
font-weight: bold;
line-height: 43px;
color: #999;
text-align: center;
border: 1px solid #ddd;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test li + li {
margin-left: 10px;
}
.responsive-utilities-test span {
position: absolute;
top: -1px;
left: -1px;
right: -1px;
bottom: -1px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.responsive-utilities-test span {
color: #468847;
background-color: #dff0d8;
border: 1px solid #d6e9c6;
}
/* Sidenav for Docs
-------------------------------------------------- */
.bs-docs-sidenav {
width: 228px;
margin: 30px 0 0;
padding: 0;
background-color: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 1px 4px rgba(0,0,0,.065);
-moz-box-shadow: 0 1px 4px rgba(0,0,0,.065);
box-shadow: 0 1px 4px rgba(0,0,0,.065);
}
.bs-docs-sidenav > li > a {
display: block;
width: 190px \9;
margin: 0 0 -1px;
padding: 8px 14px;
border: 1px solid #e5e5e5;
}
.bs-docs-sidenav > li:first-child > a {
-webkit-border-radius: 6px 6px 0 0;
-moz-border-radius: 6px 6px 0 0;
border-radius: 6px 6px 0 0;
}
.bs-docs-sidenav > li:last-child > a {
-webkit-border-radius: 0 0 6px 6px;
-moz-border-radius: 0 0 6px 6px;
border-radius: 0 0 6px 6px;
}
.bs-docs-sidenav > .active > a {
position: relative;
z-index: 2;
padding: 9px 15px;
border: 0;
text-shadow: 0 1px 0 rgba(0,0,0,.15);
-webkit-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
-moz-box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
box-shadow: inset 1px 0 0 rgba(0,0,0,.1), inset -1px 0 0 rgba(0,0,0,.1);
}
/* Chevrons */
.bs-docs-sidenav .icon-chevron-right {
float: right;
margin-top: 2px;
margin-right: -6px;
opacity: .25;
}
.bs-docs-sidenav > li > a:hover {
background-color: #f5f5f5;
}
.bs-docs-sidenav a:hover .icon-chevron-right {
opacity: .5;
}
.bs-docs-sidenav .active .icon-chevron-right,
.bs-docs-sidenav .active a:hover .icon-chevron-right {
background-image: url(../img/glyphicons-halflings-white.png);
opacity: 1;
}
.bs-docs-sidenav.affix {
top: 40px;
}
.bs-docs-sidenav.affix-bottom {
position: absolute;
top: auto;
bottom: 270px;
}
/* Responsive
-------------------------------------------------- */
/* Desktop large
------------------------- */
@media (min-width: 1200px) {
.bs-docs-container {
max-width: 970px;
}
.bs-docs-sidenav {
width: 258px;
}
.bs-docs-sidenav > li > a {
width: 230px \9; /* Override the previous IE8-9 hack */
}
}
/* Desktop
------------------------- */
@media (max-width: 980px) {
/* Unfloat brand */
body > .navbar-fixed-top .brand {
float: left;
margin-left: 0;
padding-left: 10px;
padding-right: 10px;
}
/* Inline-block quick links for more spacing */
.quick-links li {
display: inline-block;
margin: 5px;
}
/* When affixed, space properly */
.bs-docs-sidenav {
top: 0;
width: 218px;
margin-top: 30px;
margin-right: 0;
}
}
/* Tablet to desktop
------------------------- */
@media (min-width: 768px) and (max-width: 979px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Widen masthead and social buttons to fill body padding */
.jumbotron {
margin-top: -20px; /* Offset bottom margin on .navbar */
}
/* Adjust sidenav width */
.bs-docs-sidenav {
width: 166px;
margin-top: 20px;
}
.bs-docs-sidenav.affix {
top: 0;
}
}
/* Tablet
------------------------- */
@media (max-width: 767px) {
/* Remove any padding from the body */
body {
padding-top: 0;
}
/* Widen masthead and social buttons to fill body padding */
.jumbotron {
padding: 40px 20px;
margin-top: -20px; /* Offset bottom margin on .navbar */
margin-right: -20px;
margin-left: -20px;
}
.masthead h1 {
font-size: 90px;
}
.masthead p,
.masthead .btn {
font-size: 24px;
}
.marketing .span4 {
margin-bottom: 40px;
}
.bs-docs-social {
margin: 0 -20px;
}
/* Space out the show-grid examples */
.show-grid [class*="span"] {
margin-bottom: 5px;
}
/* Sidenav */
.bs-docs-sidenav {
width: auto;
margin-bottom: 20px;
}
.bs-docs-sidenav.affix {
position: static;
width: auto;
top: 0;
}
/* Unfloat the back to top link in footer */
.footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
.footer p {
margin-bottom: 9px;
}
}
/* Landscape phones
------------------------- */
@media (max-width: 480px) {
/* Remove padding above jumbotron */
body {
padding-top: 0;
}
/* Change up some type stuff */
h2 small {
display: block;
}
/* Downsize the jumbotrons */
.jumbotron h1 {
font-size: 45px;
}
.jumbotron p,
.jumbotron .btn {
font-size: 18px;
}
.jumbotron .btn {
display: block;
margin: 0 auto;
}
/* center align subhead text like the masthead */
.subhead h1,
.subhead p {
text-align: center;
}
/* Marketing on home */
.marketing h1 {
font-size: 30px;
}
.marketing-byline {
font-size: 18px;
}
/* center example sites */
.example-sites {
margin-left: 0;
}
.example-sites > li {
float: none;
display: block;
max-width: 280px;
margin: 0 auto 18px;
text-align: center;
}
.example-sites .thumbnail > img {
max-width: 270px;
}
/* Do our best to make tables work in narrow viewports */
table code {
white-space: normal;
word-wrap: break-word;
word-break: break-all;
}
/* Examples: dropdowns */
.bs-docs-example-submenus > .pull-left {
float: none;
clear: both;
}
.bs-docs-example-submenus > .pull-left,
.bs-docs-example-submenus > .pull-left + .pull-left {
margin-left: 0;
}
.bs-docs-example-submenus p {
margin-bottom: 0;
}
.bs-docs-example-submenus .dropup > .dropdown-menu,
.bs-docs-example-submenus .dropdown > .dropdown-menu {
margin-bottom: 10px;
float: none;
max-width: 180px;
}
/* Examples: modal */
.modal-example .modal {
position: relative;
top: auto;
right: auto;
bottom: auto;
left: auto;
}
/* Tighten up footer */
.footer {
padding-top: 20px;
padding-bottom: 20px;
}
}
|
069ka-ambition-cms
|
trunk/admin/assets/css/docs.css
|
CSS
|
mit
| 22,431
|
<?php
$site_url = "http://localhost/ambition/class/";
$upload_url = "http://localhost/ambition/class/uploads/";
define('UPLOAD_PATH', 'http://localhost/ambition/class/uploads/' );
$con = mysql_connect("localhost", "root", "");
mysql_select_db("cms");
?>
|
069ka-ambition-cms
|
trunk/includes/common.php
|
PHP
|
mit
| 269
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Fresh Pick</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="Erwin Aligam - styleshout.com" />
<meta name="description" content="Site Description Here" />
<meta name="keywords" content="keywords, here" />
<meta name="robots" content="index, follow, noarchive" />
<meta name="googlebot" content="noarchive" />
<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><a href="index.html" title="">Freshpick</a></h1>
<p id="slogan">Just Another Styleshout CSS Template... </p>
<div id="nav">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li id="current"><a href="archives.html">Archives</a></li>
<li><a href="index.html">Support</a></li>
<li><a href="index.html">About</a></li>
</ul>
</div>
<div id="header-image"></div>
<!--header ends-->
</div>
<!-- content -->
<div id="content-outer" class="clear"><div id="content-wrap">
<div id="content">
<div id="left">
<h2><a href="index.html">Archives for 2009</a></h2>
<div class="page-navigation clear">
<div class="float-left"><a href="#">« Older Entries</a></div>
<div class="float-right"><a href="#">Newer Entries » </a></div>
</div>
<ul class="archive">
<li>
<div class="post-title"><strong><a href="index.html">Suspendisse bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">May 01, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Lorem ipsum dolor sit amet.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">May 01, 2009</a> | Filed under <a href="index.html">templates</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">In tristique orci porttitor ipsum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 30, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Donec libero. Suspendisse bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 30, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Suspendisse bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 28, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">internet</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Lorem ipsum dolor sit amet.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 27, 2009</a> | Filed under <a href="index.html">templates</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">In tristique orci porttitor ipsum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 25, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
<li>
<div class="post-title"><strong><a href="index.html">Donec mattis, purus nec placerat bibendum.</a></strong></div>
<div class="post-details">Posted on <a href="index.html">April 25, 2009</a> | Filed under <a href="index.html">templates</a>, <a href="index.html">design</a></div>
</li>
</ul>
<div class="page-navigation clear">
<div class="float-left"><a href="#">« Older Entries</a></div>
<div class="float-right"><a href="#">Newer Entries » </a></div>
</div>
</div>
<div id="right">
<div class="sidemenu">
<h3>Sidebar Menu</h3>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html#TemplateInfo">TemplateInfo</a></li>
<li><a href="style.html">Style Demo</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="http://www.dreamtemplate.com" title="Web Templates">Web Templates</a></li>
</ul>
</div>
<div class="sidemenu">
<h3>Sponsors</h3>
<ul>
<li><a href="http://www.dreamtemplate.com" title="Website Templates">DreamTemplate <br />
<span>Over 6,000+ Premium Web Templates</span></a>
</li>
<li><a href="http://www.themelayouts.com" title="WordPress Themes">ThemeLayouts <br />
<span>Premium WordPress & Joomla Themes</span></a>
</li>
<li><a href="http://www.imhosted.com" title="Website Hosting">ImHosted.com <br />
<span>Affordable Web Hosting Provider</span></a>
</li>
<li><a href="http://www.dreamstock.com" title="Stock Photos">DreamStock <br />
<span>Download Amazing Stock Photos</span></a>
</li>
<li><a href="http://www.evrsoft.com" title="Website Builder">Evrsoft <br />
<span>Website Builder Software & Tools</span></a>
</li>
<li><a href="http://www.webhostingwp.com" title="Web Hosting">Web Hosting <br />
<span>Top 10 Hosting Reviews</span></a>
</li>
</ul>
</div>
<h3>Search</h3>
<form id="quick-search" action="index.html" method="get" >
<p>
<label for="qsearch">Search:</label>
<input class="tbox" id="qsearch" type="text" name="qsearch" value="type and hit enter..." title="Start typing and hit ENTER" />
<input class="btn" alt="Search" type="image" name="searchsubmit" title="Search" src="images/search.gif" />
</p>
</form>
</div>
</div>
<!-- content end -->
</div></div>
<!-- footer starts here -->
<div id="footer-outer" class="clear"><div id="footer-wrap">
<div class="col-a">
<h3>Image Gallery </h3>
<p class="thumbs">
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
<a href="index.html"><img src="images/thumb.jpg" width="40" height="40" alt="thumbnail" /></a>
</p>
<h3>Lorem ipsum dolor</h3>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam. Cras fringilla magna.
</p>
</div>
<div class="col-a">
<h3>Lorem Ipsum</h3>
<p>
<strong>Lorem ipsum dolor</strong> <br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<div class="footer-list">
<ul>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">sem justo</a></li>
<li><a href="index.html">semper</a></li>
<li><a href="index.html">magna sed purus</a></li>
<li><a href="index.html">tincidunt</a></li>
<li><a href="index.html">consequat molestie</a></li>
<li><a href="index.html">magna sed purus</a></li>
</ul>
</div>
</div>
<div class="col-b">
<h3>About</h3>
<p>
<a href="index.html"><img src="images/gravatar.jpg" width="40" height="40" alt="firefox" class="float-left" /></a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu
posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum
odio, ac blandit ante orci ut diam.</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum.
Cras id urna. <a href="index.html">Learn more...</a></p>
</div>
<!-- footer ends -->
</div></div>
<!-- footer-bottom starts -->
<div id="footer-bottom">
<div class="bottom-left">
<p>
© 2010 <strong>Your Copyright Info Here</strong>
<a href="http://www.bluewebtemplates.com/" title="Website Templates">website templates</a> by <a href="http://www.styleshout.com/">styleshout</a>
</p>
</div>
<div class="bottom-right">
<p>
<a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a> |
<a href="http://validator.w3.org/check/referer">XHTML</a> |
<a href="index.html">Home</a> |
<a href="index.html">Sitemap</a> |
<a href="index.html">RSS Feed</a>
</p>
</div>
<!-- footer-bottom ends -->
</div>
<!-- wrap ends here -->
</div>
</body>
</html>
|
069ka-ambition-cms
|
trunk/archives.html
|
HTML
|
mit
| 10,677
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
$fruits = array ("apple","mango","orange","banana");
echo "<pre>";
print_r($fruits);
echo "</pre>";
echo "<br/>My favorite fruits : ";
for ($i=0; $i < count($fruits) ; $i++){
echo "<br/>" ;
echo $fruits [$i];
}
echo "<br/><br/><br/> foreach<br/>------------";
$fruits = array ("apple","mango","orange","banana");
foreach ($fruits as $fruit){
echo $fruit;
}
$fruits = array ("orange","apple","banana");
$users = array (
array (
"username" => "sanju",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "sanju@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "rudra",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "rudra@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "bimala",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "bimala@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
);
echo "<pre>";
print_r($users);
echo "</pre>";
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) {?>
<tr>
<td>1</td>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['email'];?></td>
<td><?php echo $user['address'];?></td>
<td><?php echo $user['phone'];?></td>
<td>
<?php if ($user['status'] == 1){
echo "Active";
}else {
echo "Inactive";
}
?>
</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//CSV - Comma Separated Values
$sports = "football, cricket, basketball";
$sports_array = explode ("," , $sports );
echo "<pre>"; print_r($sports_array); echo "</pre>";
echo $string = implode ("," , $sports_array );
$filename = "sample.exe";
$e = substr($filename,-3);
$allowed_ext = array ("jpg","bmp","gif","png");
if (in_array($e, $allowed_ext)) {
echo "<br/><strong>File allowed to upload</strong>";
}else {
echo "<br/><strong>Not supported file format</strong>";
}
echo "<br/>Array Push/Pop";
$allowed_ext = array ("jpg","bmp","gif","png");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"psd");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"doc");
array_push($allowed_ext,"txt");
array_push($allowed_ext,"bmp");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
$unique = array_unique ($allowed_ext);
echo "<pre>"; print_r($unique); echo "</pre>";
echo array_pop($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
asort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
arsort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
ksort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
$merged = array_merge($sports_array, $unique);
echo "<pre>"; print_r($merged); echo "</pre>";
$rand_key = array_rand($merged);
echo $merged[$rand_key];
?>
<br>
<br>
<br>
<br>
<br>
<br>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/array.php
|
PHP
|
mit
| 7,144
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
function add($a,$b){
return $a + $b;
}
echo "Sum is ".add(2,10);
//echo "Sum is ".add($_GET['a'],$_GET['b']);
//string functions
echo strlen("bhupal")."<br/>";
echo "<pre>";
//print_r( count_chars ("hello world"));
echo "</pre>";
echo strtoupper('hello world')."<br/>";
echo strtolower('Hello World')."<br/>";
echo ucfirst("ambition college")."<br/>";
echo ucwords("ambition college")."<br/>";
$str = "Hi it's 9 o'Clock";
echo addslashes ($str)."<br/>";
echo stripslashes (addslashes ($str))."<br/>";
echo $data = 5/3;
echo "<br/>";
echo number_format($data,2);
$str = "filename.jpeg";
echo "<br/>";
echo substr($str, -3, 3);
echo "<br/>";
echo substr($str, 0, 4);
echo "<br/>";
echo $dot_position = strpos($str,".");
echo "<br/>";
echo substr( $str, $dot_position+1);
echo "<br/>";
echo sha1("password");
echo "<br/>";
echo md5("password");
echo "<br/>";
echo sin(deg2rad(30));
echo "<br/>";
echo cos(30);
$value = 5.8;
echo "<br/>";
echo ceil($value);
echo "<br/>";
echo floor($value);
echo "<br/>";
echo rand();
echo "<br/>";
echo rand(1,10);
echo "<br/>";
echo abs(-10);
echo abs(+10);
echo sqrt(25);
echo pow(5,2);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/functions.php
|
PHP
|
mit
| 4,785
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
<form class="form-search" class="">
<input type="text" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
</form>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/pv.php
|
Hack
|
mit
| 3,577
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Calculator</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Calculator</h1>
<p>Simple calculator</p>
<br/>
<br/>
<form class="form-inline" method="GET" action="calculator.php">
<input type="text" class="input-small" name="num1" placeholder="1st number">
<select name="operator" class="input-small">
<option value="+">Add</option>
<option value="-">Substract</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<input type="text" class="input-small" name ="num2" placeholder="2nd Number">
<button name="submit" value="submit" type="submit" class="btn">Calculate</button>
</form>
<?php
if ($_GET['submit'] != ""){
$num1 = $_GET['num1'];$num2 = $_GET['num2'];
if ($num1 == "" || $num2 == "") {
echo "Please enter both numbers.";
}else {
//echo "<pre>"; print_r($_GET); echo "</pre>";
$op = $_GET['operator'];
if ($op == "+"){ $result = $num1+$num2; }
else if ($op== "-"){ $result = $num1 - $num2;}
else if ($op== "*"){ $result = $num1 * $num2;}
else if ($op== "/"){ $result = $num1 / $num2;}
else { $result = 0; }
echo "Output of $num1 $op $num2 is : $result ";
}
}
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/calculator.php
|
PHP
|
mit
| 4,382
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
$fruits = array ("apple","mango","orange","banana");
echo "<pre>";
print_r($fruits);
echo "</pre>";
echo "<br/>My favorite fruits : ";
for ($i=0; $i < count($fruits) ; $i++){
echo "<br/>" ;
echo $fruits [$i];
}
echo "<br/><br/><br/> foreach<br/>------------";
$fruits = array ("apple","mango","orange","banana");
foreach ($fruits as $fruit){
echo $fruit;
}
$fruits = array ("orange","apple","banana");
$users = array (
array (
"username" => "sanju",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "sanju@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "rudra",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "rudra@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
array (
"username" => "bimala",
"password" => "ihg987656gggyfhvhg9876456",
"email" => "bimala@gmail.com",
"address" =>"baneshwor",
"phone" => "9841",
"status" => 1
),
);
echo "<pre>";
print_r($users);
echo "</pre>";
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) {?>
<tr>
<td>1</td>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['email'];?></td>
<td><?php echo $user['address'];?></td>
<td><?php echo $user['phone'];?></td>
<td>
<?php if ($user['status'] == 1){
echo "Active";
}else {
echo "Inactive";
}
?>
</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//CSV - Comma Separated Values
$sports = "football, cricket, basketball";
$sports_array = explode ("," , $sports );
echo "<pre>"; print_r($sports_array); echo "</pre>";
echo $string = implode ("," , $sports_array );
$filename = "sample.exe";
$e = substr($filename,-3);
$allowed_ext = array ("jpg","bmp","gif","png");
if (in_array($e, $allowed_ext)) {
echo "<br/><strong>File allowed to upload</strong>";
}else {
echo "<br/><strong>Not supported file format</strong>";
}
echo "<br/>Array Push/Pop";
$allowed_ext = array ("jpg","bmp","gif","png");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"psd");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
array_push($allowed_ext,"doc");
array_push($allowed_ext,"txt");
array_push($allowed_ext,"bmp");
echo "<pre>"; print_r($allowed_ext); echo "</pre>";
$unique = array_unique ($allowed_ext);
echo "<pre>"; print_r($unique); echo "</pre>";
echo array_pop($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
asort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
arsort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
ksort($unique);
echo "<pre>"; print_r($unique); echo "</pre>";
$merged = array_merge($sports_array, $unique);
echo "<pre>"; print_r($merged); echo "</pre>";
$rand_key = array_rand($merged);
echo $merged[$rand_key];
?>
<br>
<br>
<br>
<br>
<br>
<br>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/array.php
|
PHP
|
mit
| 7,144
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to Database</h1>
<?php
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/base.php
|
PHP
|
mit
| 3,282
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<?php
function add($a,$b){
return $a + $b;
}
echo "Sum is ".add(2,10);
//echo "Sum is ".add($_GET['a'],$_GET['b']);
//string functions
echo strlen("bhupal")."<br/>";
echo "<pre>";
//print_r( count_chars ("hello world"));
echo "</pre>";
echo strtoupper('hello world')."<br/>";
echo strtolower('Hello World')."<br/>";
echo ucfirst("ambition college")."<br/>";
echo ucwords("ambition college")."<br/>";
$str = "Hi it's 9 o'Clock";
echo addslashes ($str)."<br/>";
echo stripslashes (addslashes ($str))."<br/>";
echo $data = 5/3;
echo "<br/>";
echo number_format($data,2);
$str = "filename.jpeg";
echo "<br/>";
echo substr($str, -3, 3);
echo "<br/>";
echo substr($str, 0, 4);
echo "<br/>";
echo $dot_position = strpos($str,".");
echo "<br/>";
echo substr( $str, $dot_position+1);
echo "<br/>";
echo sha1("password");
echo "<br/>";
echo md5("password");
echo "<br/>";
echo sin(deg2rad(30));
echo "<br/>";
echo cos(30);
$value = 5.8;
echo "<br/>";
echo ceil($value);
echo "<br/>";
echo floor($value);
echo "<br/>";
echo rand();
echo "<br/>";
echo rand(1,10);
echo "<br/>";
echo abs(-10);
echo abs(+10);
echo sqrt(25);
echo pow(5,2);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/functions.php
|
PHP
|
mit
| 4,785
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: login.php");
include "dbactions/user_add.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
<script type="text/javascript">
function sure(){
if (confirm("Are you sure delete this user ?")){
return true;
}else {
return false;
}
}
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
<li><a href="logout.php">Logout - <?php echo $_SESSION['username']; ?></a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>PHP / MySql</h1>
<p>Basic CRUD oparations on Database</p>
<br/>
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users`";
$result = mysql_query($sql);
?>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
//Step - 4 (Grab / Process result of query)
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$i++;
//echo "<pre>";print_r($row);echo "</pre>";
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row['username'];?></td>
<td><?php echo $row['email'];?></td>
<td>
<a href="">View</a> |
<a href="dbactions/user_edit.php?id=<?php echo $row['id']; ?>">Edit</a> |
<a onclick="return sure()" href="dbactions/user_delete.php?id=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php }?>
</tbody>
</table>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
<h3>Add New Users</h3>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php if (isset($username)) echo $username; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php if (isset($email)) echo $email; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Add User" type="submit" class="btn" />
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/database.php
|
PHP
|
mit
| 6,625
|
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$sql = "";
//Step - 4 (Grab / Process / Execute query)
$sql = "delete from `users` where `id` = $id";
mysql_query($sql);
//Step - 5 (Close connection)
mysql_close($con);
//redirect to main page
header ("location: ../database.php");
?>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/dbactions/steps.php
|
PHP
|
mit
| 465
|
<?php
session_start();
if (!$_SESSION['login']) header ("location: ../login.php");
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
$id= $_GET['id'];
//Step - 3 (SQL / Get result)
$sql = "SELECT * from `users` where `id` = $id";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
$password = md5($password);
$sql_update = "UPDATE `users` SET `username` = '$username', `password` = '$password', `email` = '$email' WHERE `id` = $id";
mysql_query($sql_update);
header ("location: ../database.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Course</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PHP Course</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>PHP / MySql</h1>
<p>Basic CRUD oparations on Database</p>
<br/>
<h3>Update User '<?php echo $row['username']; ?>' </h3>
<br/><br/>
<form class="form-horizontal" action="" method="POST">
<div class="control-group <?php if ($username_error) { echo 'error'; } ?> ">
<label class="control-label" for="first_name">Username</label>
<div class="controls">
<input type="text" name="username" value="<?php echo $row['username']; ?>">
<?php if ($username_error) { ?>
<span class="help-inline"><?php echo $username_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($password_error) { echo 'error'; } ?>">
<label class="control-label" for="username">Password</label>
<div class="controls">
<input type="password" id="password" name="password" value="<?php echo $row['password']; ?>" >
<?php if ($password_error) { ?>
<span class="help-inline"><?php echo $password_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group <?php if ($email_error) { echo 'error'; } ?>">
<label class="control-label" for="last_name">Email</label>
<div class="controls">
<input type="text" id="email" name="email" value="<?php echo $row['email']; ?>">
<?php if ($email_error) { ?>
<span class="help-inline"><?php echo $email_error; ?></span>
<?php } ?>
</div>
</div>
<div class="control-group">
<div class="controls">
<input name="submit" value="Update User" type="submit" class="btn" />
</div>
</div>
</form>
<?php
//Step - 5 (Close connection)
mysql_close($con);
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/dbactions/user_edit.php
|
PHP
|
mit
| 5,762
|
<?php
//Step - 1 (Connection)
$con = mysql_connect("localhost", "root", "");
//Step - 2 (Database)
mysql_select_db("test");
//Step - 3 (SQL / Get result)
$id = $_GET['id'];
$sql = "delete from `users` where `id` = $id";
mysql_query($sql);
//echo "user id ". $_GET['id'] . " deleted";
header ("location: ../database.php");
?>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/dbactions/user_delete.php
|
PHP
|
mit
| 392
|
<?php
if (isset($_POST['submit'])) {
$error = false;
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$email = trim($_POST['email']);
if($username == '') {
$error = true;
$username_error = "Please provide username";
}
if($password == '') {
$error = true;
$password_error = "Please provide password";
}else {
$password = md5($_POST['password']);
}
if($email == '') {
$error = true;
$email_error = "Please provide email";
}
//if ($username != "" && $password !="" && $email !="" ) {
if(!$error) {
$con = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, '$username','$password','$email');";
mysql_query($sql);
header ("location: database.php");
}
}
?>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/dbactions/user_add.php
|
PHP
|
mit
| 908
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
<form class="form-search" class="">
<input type="text" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
</form>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/pv.php
|
Hack
|
mit
| 3,577
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Calculator</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Calculator</h1>
<p>Simple calculator</p>
<br/>
<br/>
<form class="form-inline" method="GET" action="calculator.php">
<input type="text" class="input-small" name="num1" placeholder="1st number">
<select name="operator" class="input-small">
<option value="+">Add</option>
<option value="-">Substract</option>
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select>
<input type="text" class="input-small" name ="num2" placeholder="2nd Number">
<button name="submit" value="submit" type="submit" class="btn">Calculate</button>
</form>
<?php
if ($_GET['submit'] != ""){
$num1 = $_GET['num1'];$num2 = $_GET['num2'];
if ($num1 == "" || $num2 == "") {
echo "Please enter both numbers.";
}else {
//echo "<pre>"; print_r($_GET); echo "</pre>";
$op = $_GET['operator'];
if ($op == "+"){ $result = $num1+$num2; }
else if ($op== "-"){ $result = $num1 - $num2;}
else if ($op== "*"){ $result = $num1 * $num2;}
else if ($op== "/"){ $result = $num1 / $num2;}
else { $result = 0; }
echo "Output of $num1 $op $num2 is : $result ";
}
}
?>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/calculator.php
|
PHP
|
mit
| 4,382
|
<?php
session_start();
//unset session
$_SESSION['login'] = 0;
$_SESSION['username'] = "";
//or
//unset($_SESSION['login']);
//unset($_SESSION['username']);
session_destroy();
//redirect to login page
header ("location: login.php");
?>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/logout.php
|
PHP
|
mit
| 274
|
<?php
session_start();
$username = $_POST['username']; $password = $_POST['password'];
if ($_POST['submit'] && ($username !="" && $password !="" )) {
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "");
mysql_select_db("test");
$sql = "select * from `users` where `username` = '$username' and `password` = '$password'";
$result = mysql_query($sql);
$count_result = mysql_num_rows($result);
if ($count_result == 1 ) {
//echo "Login Success!";
//set session
$_SESSION['login'] = 1;
$_SESSION['username'] = $username;
//redirect to database
header ("location: database.php");
}else {
echo "Login failed!";
}
} else {
echo "Please provide username & password!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sign in · Twitter Bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin input[type="text"],
.form-signin input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="../assets/ico/favicon.png">
</head>
<body>
<div class="container">
<form class="form-signin" action="" method="POST" >
<h2 class="form-signin-heading">Login</h2>
Username: <input name="username" value="" type="text" class="input-block-level" >
Password: <input name="password" value="" type="password" class="input-block-level" >
<button name="submit" value="Sign In" class="btn btn-large btn-primary" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-transition.js"></script>
<script src="../assets/js/bootstrap-alert.js"></script>
<script src="../assets/js/bootstrap-modal.js"></script>
<script src="../assets/js/bootstrap-dropdown.js"></script>
<script src="../assets/js/bootstrap-scrollspy.js"></script>
<script src="../assets/js/bootstrap-tab.js"></script>
<script src="../assets/js/bootstrap-tooltip.js"></script>
<script src="../assets/js/bootstrap-popover.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/bootstrap-carousel.js"></script>
<script src="../assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/login.php
|
PHP
|
mit
| 4,427
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap, from Twitter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">USers</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<h3>Add New User</h3>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/user_add.php
|
Hack
|
mit
| 3,406
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to PV Gallery</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">PV Gallery</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">Users</a></li>
<li><a href="#contact">Photos</a></li>
<li><a href="#contact">Videos</a></li>
<li><a href="#contact">Feedback</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container">
<h1>Welcome to PV Gallery</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<h3>Latest Users</h3>
<a href="user_add.html">+ Add New User</a>
<br/><br/>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
<tr>
<td>3</td>
<td>Larry the Bird</td>
<td>@twitter</td>
<td>@twitter</td>
<td><a href="">View</a> | <a href="">Edit</a> | <a href="">Delete</a></td>
</tr>
</tbody>
</table>
<h3>Add New Users</h3>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="first_name">First Name</label>
<div class="controls">
<input type="text" id="first_name" name="first_name" placeholder="first name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="last_name">Last Name</label>
<div class="controls">
<input type="text" id="last_name" name="last_name" placeholder="last name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Add User</button>
</div>
</div>
</form>
</div> <!-- /container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap-transition.js"></script>
<script src="assets/js/bootstrap-alert.js"></script>
<script src="assets/js/bootstrap-modal.js"></script>
<script src="assets/js/bootstrap-dropdown.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
<script src="assets/js/bootstrap-tab.js"></script>
<script src="assets/js/bootstrap-tooltip.js"></script>
<script src="assets/js/bootstrap-popover.js"></script>
<script src="assets/js/bootstrap-button.js"></script>
<script src="assets/js/bootstrap-collapse.js"></script>
<script src="assets/js/bootstrap-carousel.js"></script>
<script src="assets/js/bootstrap-typeahead.js"></script>
</body>
</html>
|
069ka-ambition-cms
|
trunk/bkp/ambition_before_session/users.php
|
Hack
|
mit
| 5,535
|