code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/bin/env python
import os
import re
import sys
ws = re.compile(r'-')
f = open("list.txt")
names = f.readlines()
f.close()
for name in names:
name = name[0:-1]
newname = ""
for token in ws.split(name):
newname += token[0].upper()
newname += token[1:]
cmd = "cp %s %s" % (name,newname)
print cmd
os.system(cmd)
| Python |
import types as t
import os, imp
import inspect
def scan_folder_recurse(folder, excl_names=['__']):
""" Recurse search for PY files in given folder """
all_files = []
for root, d, files in os.walk(folder): #@UnusedVariable
filelist = [os.path.join(root, fi) for fi in files if fi.endswith('.py')
and not any(fi.startswith(prefix) for prefix in excl_names)]
all_files += filelist
return all_files
def scan_package(p):
for x in dir(p):
if not x.startswith("_"):
o = getattr(p, x)
if inspect.isclass(o) and o.__module__.startswith(p.__name__) and getattr(o, "METAROUTE_CONTROLLER_PATH", None) is not None:
yield o
def attach_controllers(app, pkg):
pkg_path = pkg.__path__[0]
pkg_name = pkg.__name__
all_files = scan_folder_recurse(pkg_path)
for f in all_files:
pkg = f[len(pkg_path):]
pkg = pkg.strip("/")[:-3]
if len(pkg):
pkg = pkg_name + "." + pkg
attach_controller(app, imp.load_source(pkg, f))
def attach_controller(app, mdl):
for cls in scan_package(mdl):
if cls.__module__.startswith(mdl.__name__):
cpath = getattr(cls, "METAROUTE_CONTROLLER_PATH", None)
if cpath is not None:
ctrl = cls()
methods = dir(ctrl)
for meth in methods:
m = getattr(cls, meth, None)
for path, args, opts in getattr(m, "METAROUTE_ACTION_PATHS", []):
xf = cls.__dict__[m.__name__].__get__(ctrl, cls)
opts['endpoint'] = cls.__module__ + "." + cls.__name__ + "." + xf.__name__
app.route(cpath + path, **opts)(cls.__dict__[m.__name__].__get__(ctrl, cls))
for ex in getattr(m, "METAROUTE_ERROR_EXCEPTIONS", []):
app._register_error_handler(None, ex, cls.__dict__[m.__name__].__get__(ctrl, cls))
| Python |
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack #@UnusedImport
from flask_metaroute.func import attach_controllers
import importlib
class MetaRoute(object):
def __init__(self, app = None, ctrl_pkg = None):
if app is not None:
self.app = app
self.init_app(self.app, ctrl_pkg)
else:
self.app = None
def init_app(self, app, ctrl_pkg = None):
pkg = ctrl_pkg or app.config['METAROUTE_CONTROLLERS_PKG']
if isinstance(pkg, str):
pkg = importlib.import_module(pkg)
attach_controllers(app, pkg)
| Python |
import inspect
def enhance_ctrl_class(cls, path, args, kwargs):
cls.METAROUTE_CONTROLLER_PATH = path
cls.METAROUTE_CONTROLLER_ARGS = args
cls.METAROUTE_CONTROLLER_KWARGS = kwargs
return cls
def Controller(*args, **kwargs):
if not inspect.isclass(args[0]):
def d(cls):
return enhance_ctrl_class(cls, args[0], args[1:], kwargs)
return d
else:
return enhance_ctrl_class(args[0], "", [], {})
def Route(path = "", *args, **kwargs):
def d(f):
f.METAROUTE_ACTION_PATHS = getattr(f, "METAROUTE_ACTION_PATHS", []) + [(path, args, kwargs)]
return f
return d
def Error(ex = ""):
def d(f):
f.METAROUTE_ERROR_EXCEPTIONS = getattr(f, "METAROUTE_ERROR_EXCEPTIONS", []) + [ex]
return f
return d
| Python |
from flask_metaroute.decorators import Controller, Error, Route
from flask_metaroute.metaroute import MetaRoute
__all__ = ["Controller", "Error", "Route", "MetaRoute"] | Python |
"""
Flask-MetaRoute
-------------
Flask-MetaRoute adds some useful decorators for routing
"""
from setuptools import setup
setup(
name='Flask-MetaRoute',
version='1.2',
url='http://code.google.com/p/flask-metaroute/',
license='BSD',
author='Orca',
author_email='deep.orca@gmail.com',
description='Extra routing capabilities for Flask',
long_description=__doc__,
packages=['flask_metaroute'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
) | Python |
import string
class Message:
player_id = None
action = None
parameters = []
fieldSeparator = ':'
address = None
# actions
PLAYER_JOIN = 'join'
PLAYER_LEAVE = 'leave'
PLAYER_MOVE = 'move'
PLAYER_PLANT_BOMB = 'plant_bomb'
PLAYER_STOP_BOMB = 'stop_bomb'
PLAYER_PAUSE_GAME = 'pause_game'
PLAYER_START_GAME = 'start_game'
def __init__(self):
pass
def __init__(self, message, address):
self.address = address
self.parse(message)
def parse(self, message):
print "Parsing: " + message;
splitData = message.split(':')
print splitData
self.player_id = splitData[0]
self.action = splitData[1]
self.parameters = splitData[2:]
def __str__(self):
return "Message <" + self.player_id + self.fieldSeparator + self.action + self.fieldSeparator + string.join(self.parameters, self.fieldSeparator) + "> from address: " + str(self.address)
| Python |
class Game:
GAME_NOT_STARTED_YET = 0
GAME_STARTED = 1
players = []
server = None
currentArena = None
def __init__(self, server):
self.server = server
def addPlayer(self, player):
self.players.append(player)
def handleMessage(self, message):
for p in self.players:
print p
player = self.getPlayerById(message.player_id)
if not player:
player = self.getPlayerByAddress(message.address)
print "Message object: " + str(message)
print "Player object: " + str(player)
print "Player id: " + player.id
if message.action == message.PLAYER_JOIN:
self.playerJoins(player, message)
elif message.action == message.PLAYER_LEAVE:
self.playerLeaves(player, message)
elif message.action == message.PLAYER_MOVE:
self.playerMoves(player, message)
elif message.action == message.PLAYER_PLANT_BOMB:
self.playerPlantsBomb(player, message)
# finally send the received message to all players
# (except original sender)
self.server.sendMessageToAllPlayers(message)
def playerStartsGame(self, player, message):
print "Player <" + player.id + "> starts the game."
def playerPlantsBomb(self, player, message):
print "Player <" + player.id + "> plants a bomb at (" + message.parameters[0] + ", " + message.parameters[1] + ")."
def playerMoves(self, player, message):
print "Player <" + player.id + "> moves to (" + message.parameters[0] + ", " + message.parameters[1] + ")."
player.position == (message.parameters[0], message.parameters[1])
def playerPausesGame(self, player, message):
print "Player <" + player.id + "> pauses the game."
def playerJoins(self, player, message):
if player:
player.id = message.player_id
print "Player <" + player.id + "> joins the game."
def playerLeaves(self, player, message):
print "Player <" + player.id + "> leaves the game."
players.remove(player)
player = None
def getPlayerByAddress(self, addr):
for p in self.players:
if p.address == addr:
return p
return None
def getPlayerById(self, id):
for p in self.players:
if p.id == id:
return p
return None
| Python |
import socket
class Player:
id = ""
connection = None
address = None
position = (0, 0)
extraBombs = 0
extraFlames = 0
def __init__(self, conn, addr):
self.connection = conn
self.address = addr
def sendMessage(self, message):
try:
self.connection.send(message)
except socket.error, msg:
self.connection = None
print "ERROR WHILE SENDING TO:", self.address
raise E('Player connection failed!')
def __del__(self):
if self.connection:
self.connection.close()
def __str__(self):
if self.id:
return "Player <" + self.id + "> from address " + str(self.address)
else:
return "Player <unknown> from address " + str(self.address)
| Python |
#server-test.py
from server import Server
import unittest
class SomeTest(unittest.TestCase):
def someFunctionality(self):
self.assertEqual(1, 1)
| Python |
#!/usr/bin/env python
import socket
HOST = 'localhost' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# Test player join
#s.send("player_2:join:pos_x:pos_y");
# Test player location change
s.send("player_2:move:pos_x:pos_y");
# Test player location change
#s.send("player_2:bomb:pos_x:pos_y");
#
# Main loop
#
while 1:
data = s.recv(1024)
print 'Received from server:', repr(data)
s.close()
| Python |
#!/usr/bin/env python
import sys
from server import Server
print """
===== FlashBomber 2008 Server =====
Software written by Mikko Saarela, 2008.
(Press Ctrl-Break to stop the server.)
Copyright, GNU General Public Licence version 3.
Server started ...
"""
server = Server();
server.start();
| Python |
#!/usr/bin/env python
import socket
HOST = 'localhost' # The remote host
PORT = 50007 # The remote port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# Test player join
s.send("player_1:join");
# Test player location change
#s.send("player_1:move:pos_x:pos_y");
# Test player location change
#s.send("player_1:bomb:pos_x:pos_y");
#
# Main loop
#
while 1:
data = s.recv(1024)
if not data:
continue
else:
print 'Received from server:', repr(data)
s.close()
| Python |
import socket, sys, time
from player import Player
from message import Message
from game import Game
class Server:
SERVERNAME = 'Java-teamserver'
HOST = 'localhost'
PORT = 50007
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#players = []
game = None
def __init__(self):
self.socket.bind((self.HOST, self.PORT))
self.socket.listen(1)
self.socket.setblocking(0)
self.game = Game(self)
def start(self):
print "Listening to connections at " + self.HOST + ":" + str(self.PORT)
self.mainLoop()
def stop(self):
print "Server shutdown ..."
self.socket.close()
sys.exit(0);
#def addPlayer(self, player):
# self.players.append(player)
def sendMessageToAllPlayers(self, message):
for p in self.game.players:
try:
p.sendMessage(message)
except Exception, e:
self.game.players.remove(p)
def mainLoop(self):
while 1:
time.sleep(1) # wait a sec
print "."
updateMessage = "1 sec"
#updateMessage = updateGameArena()
# wait for players to join/connect
conn = None
try:
conn, addr = self.socket.accept()
#conn.setblocking(0)
if conn:
p = Player(conn, addr)
self.game.addPlayer(p) # add unidentified player
except Exception, e:
pass
# wait for player messages
if conn:
data = conn.recv(1024)
if not data:
print "no data"
else:
# parse msg
m = Message(data, addr)
self.game.handleMessage(m)
self.sendMessageToAllPlayers(updateMessage)
def __del__(self):
self.stop()
| Python |
#!/usr/bin/env python
import socket
HOST = 'localhost' # The remote host
PORT = 50007 # The remote port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# Test player join
s.send("player_1:join");
# Test player location change
#s.send("player_1:move:pos_x:pos_y");
# Test player location change
#s.send("player_1:bomb:pos_x:pos_y");
#
# Main loop
#
while 1:
data = s.recv(1024)
if not data:
continue
else:
print 'Received from server:', repr(data)
s.close()
| Python |
#!/usr/bin/env python
import sys
from server import Server
print """
===== FlashBomber 2008 Server =====
Software written by Mikko Saarela, 2008.
(Press Ctrl-Break to stop the server.)
Copyright, GNU General Public Licence version 3.
Server started ...
"""
server = Server();
server.start();
| Python |
class Arena:
players = []
map = [
[W,W,W,W,W,W,W,W,W,W,W,W,W],
[W,B,B,B,B,_,_,_,_,_,_,_,W],
[W,_,W,_,W,_,W,_,W,_,W,_,W],
[W,_,_,_,_,_,_,_,_,_,_,_,W],
[W,_,W,_,W,_,W,_,W,_,W,_,W],
[W,_,_,B,B,B,B,B,_,_,_,_,W],
[W,_,W,_,W,B,W,B,W,_,W,_,W],
[W,_,_,B,_,B,_,B,B,B,_,_,W],
[W,_,W,_,W,_,W,_,W,_,W,_,W],
[W,_,_,_,_,B,_,_,_,_,_,_,W],
[W,_,W,_,W,_,W,_,W,B,W,_,W],
[W,_,_,_,B,B,B,B,_,_,_,_,W],
[W,W,W,W,W,W,W,W,W,W,W,W,W]
];
def __init__(self):
randomizeMapContents()
def randomizeMapContents(self):
# breakable blocks
# items within blocks
pass
def checkStatus(self):
# players have been moved
# events has been done
# check what has happened
# create events
# create messages
# send messages to players
| Python |
#!/usr/bin/env python
import socket
HOST = 'localhost' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# Test player join
#s.send("player_2:join:pos_x:pos_y");
# Test player location change
s.send("player_2:move:pos_x:pos_y");
# Test player location change
#s.send("player_2:bomb:pos_x:pos_y");
#
# Main loop
#
while 1:
data = s.recv(1024)
print 'Received from server:', repr(data)
s.close()
| Python |
class Match:
matchOn = False
arena = None
def __init__(self):
pass
| Python |
import sys
print
| Python |
import pygame, random
# ----------------------------------------------------------------------
# Bonus Item
# ----------------------------------------------------------------------
class BonusItem(pygame.sprite.Sprite):
EXTRA_BOMB = 1;
EXTRA_FLAME = 2;
KICK = 3;
TRIPLE_BOMB = 4;
position = (0, 0)
type = EXTRA_BOMB
def __init__(self, image, position):
pygame.sprite.Sprite.__init__(self)
self.src_image = pygame.image.load(image)
self.position = position
def update(self, deltat):
pass
# ----------------------------------------------------------------------
# Magic Mushroom
# ----------------------------------------------------------------------
class MagicMushroom(pygame.sprite.Sprite):
NO_EFFECT = 0
SLOW_MOVEMENT = 1 # first effect
FAST_MOVEMENT = 2
SLOW_BOMBS = 3
FAST_BOMBS = 4
TELEPORT = 5
REVERSE_MOVEMENT = 6
FORCED_BOMB_PLANTING = 7
NO_BOMB_PLANTING = 8 # last effect
position = (0, 0)
type = 0
def __init__(self, image, position):
pygame.sprite.Sprite.__init__(self)
self.src_image = pygame.image.load(image)
self.position = position
self.type = random.randint(1, 8) # first and last effect
def update(self, deltat):
pass
# ----------------------------------------------------------------------
# Exploding Bomb
# ----------------------------------------------------------------------
class Bomb(pygame.sprite.Sprite):
position = (0, 0)
owner = None # player
secondsToGo = 5;
exploding = False;
def __init__(self, image, position, player):
pygame.sprite.Sprite.__init__(self)
self.src_image = pygame.image.load(image)
self.position = position
self.owner = player
def update(self, deltat):
pass
def burnFuse():
self.secondsToGo -= 1
if self.secondsToGo == 0:
self.explode();
def explode():
pass
| Python |
import pygame
class Player(pygame.sprite.Sprite):
RED = 1
BLUE = 2
WHITE = 3
BLACK = 4
GREEN = 5
NORMAL_STATE = 1
MAGIC_STATE = 2
state = NORMAL_STATE
playerName = "unnamedPlayer"
color = 0
startPosition = (0, 0)
currentPosition = (0, 0)
amountOfBombs = 1
lenghtOfFlames = 2
hasKick = False
hasMulti = False
victories = 0
movingLeft = False
movingRight = False
movingUp = False
movingDown = False
def moveLeft(self):
self.movingLeft = True
def moveRight(self):
self.movingRight = True
def moveUp(self):
self.movingUp = True
def moveDown(self):
self.movingDown = True
def clearMovement(self):
self.movingLeft = False
self.movingRight = False
self.movingUp = False
self.movingDown = False
def dropBomb(self):
pass
def stopBomb(self):
pass
def __init__(self, color, image, position):
pygame.sprite.Sprite.__init__(self)
self.color = color
self.image = pygame.image.load(image) # src_image?
self.position = position
self.rect = pygame.Rect(self.image.get_rect())
self.rect.center = position
def update(self, deltat):
x, y = self.position
if self.movingLeft:
x += -4
elif self.movingRight:
x += 4
elif self.movingUp:
y += -4
elif self.movingDown:
y += 4
self.position = (x, y)
self.rect = self.image.get_rect()
self.rect.center = self.position
| Python |
#!/usr/bin/env python
import pygame
import os, sys
import gc
import lounge_screen
from ctypes import *
from pygame.locals import *
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = None
screenW = 800
screenH = 600
tileSize = 32
screen = None
sinewave = [
100,97,95,92,90,87,85,82,80,78,75,73,70,68,66,63,
61,59,57,54,52,50,48,46,44,42,40,38,36,34,32,30,
29,27,25,24,22,20,19,18,16,15,14,12,11,10,9,8,
7,6,5,4,4,3,2,2,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,1,1,2,2,3,3,4,5,6,6,
7,8,9,11,12,13,14,15,17,18,20,21,23,24,26,28,
29,31,33,35,37,39,41,43,45,47,49,51,53,55,58,60,
62,65,67,69,72,74,76,79,81,84,86,88,91,93,96,98,
101,103,106,108,111,113,115,118,120,123,125,127,130,132,134,137,
139,141,144,146,148,150,152,154,156,158,160,162,164,166,168,170,
171,173,175,176,178,179,181,182,184,185,186,187,188,190,191,192,
193,193,194,195,196,196,197,197,198,198,199,199,199,199,199,199,
199,199,199,199,199,198,198,198,197,197,196,195,195,194,193,192,
191,190,189,188,187,185,184,183,181,180,179,177,175,174,172,170,
169,167,165,163,161,159,157,155,153,151,149,147,145,142,140,138,
136,133,131,129,126,124,121,119,117,114,112,109,107,104,102,100
]
scrollText = " *GBOMBER 2008* CODING BY THE G-MEN PRESS ANYKEY TO CONTINUE POWERED BY PYTHON AND THE AMAZING ... PYGAME LIB "
sineScrollerIndex = 0
sineScrollerX = 0
textIndex = 0
def waveScroller():
global sineScrollerX, sineScrollerIndex, screen, sineScrollerSurface, screenH, screenW, textIndex, scrollTextSurface
step = 4 #px
sineIndex = sineScrollerIndex
for index in range (0, screenW/step):
subsurface = sineScrollerSurface.subsurface((index * step, 0, step, 120))
screen.blit(subsurface, (0 + (index * step), 200 + (int(sinewave[sineIndex] * 1.2) ) ))
sineIndex += 1
if sineIndex >= 255:
sineIndex = 0
sineScrollerIndex += 3
if sineScrollerIndex >= 255:
sineScrollerIndex = 0
#
# make better system here with modulo offsets (width/step)
#
sineScrollerX -= 5
if sineScrollerX < -55: # width of one character (guessed)
textIndex += 1
if textIndex > (len(scrollText) - 1):
textIndex = 0
sineScrollerX = 0
scrollTextSurface.fill((0,0,0))
scrollTextSurface = font.render(scrollText[textIndex:], 0, (200,200,200))
sineScrollerSurface.fill((0,0,0))
sineScrollerSurface.blit(scrollTextSurface, (sineScrollerX, 0))
beam = []
def setupBeam():
global beam
for i in range(0, 16):
beam.append((0, i*16, 0))
for i in range(15, 0, -1):
beam.append((0, i*16, 0))
beamCenter = 270
def drawBeam(sinepos):
global screen
y = beamCenter + sinewave[sinepos]
for color in beam:
pygame.draw.line(screen, color, (0, y), (screenW-1, y), 1)
y += 1
# increase thread priority for this thread
hthread = windll.kernel32.GetCurrentThread()
windll.kernel32.SetThreadPriority(hthread,1)
pygame.init()
pygame.mouse.set_visible(0)
#pygame.display.set_icon(pygame.image.load(data.filepath("icon.gif")))
pygame.display.set_caption("PyBomber 2008")
clock = pygame.time.Clock()
FRAMES_PER_SECOND = 150
direction = False
#start positions in sine index < 255
beams = [0, 15, 30, 45, 60, 75, 90]
beamColors = [(255, 0, 255), (255, 255, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0)]
def updateBeams():
i = 0
for beam in beams:
if beam >= 254:
beams[i] = 0
else:
beams[i] = beam + 2
i += 1
index = 0
for beam in beams:
drawBeam(beam)
index += 1
font = pygame.font.Font('c:/Windows/Fonts/DejaVuMonoSansBold.ttf', 100)
scrollTextSpecific = None
scrollColors = [140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 250, 245, 240, 235, 230, 225, 220, 215, 210, 205, 200, 195, 190, 185, 180, 175, 170, 165, 160, 155, 150, 145, 140]
currentScrollColor = 0
scrollX = screenW
sineScrollerSurface = pygame.Surface((screenW, 120))
sineScrollerSurface.set_colorkey((0,0,0))
scrollTextSurface = font.render(scrollText, 0, (200,200,200))
def scroller():
global screen, scrollX, scrollTextSpecific, currentScrollColor
color = scrollColors[currentScrollColor]
scrollTextSpecific = font.render("=== PYTHON/BOMBER 2008 GAME ===", 0, (color,color,color))
currentScrollColor += 1
if currentScrollColor >= len(scrollColors):
currentScrollColor = 0
screen.blit(scrollTextSpecific, (scrollX,400))
scrollX -= 5
if scrollX <= 0:
scrollX = screenW
logoIndex = 0
def drawLogo():
global screen, logoIndex
#logo = pygame.image.load('images/gbomber_logo.png')
logo = pygame.image.load('images/gbomber_logo_green.png')
xPos = (screenW - logo.get_width() - 600)/2
xPos += int(sinewave[logoIndex] * 3)
logoIndex += 4
if logoIndex >= 255:
logoIndex = 0
screen.blit(logo, (xPos, 50))
def makeWater():
global screen
subsurface = screen.subsurface((0, 400, 800, 100))
water = pygame.transform.flip(subsurface, False, True)
pxarray = pygame.PixelArray(water)
water = pxarray.make_surface()
del(pxarray)
water.set_alpha(100)
water.set_colorkey((0,0,0))
screen.blit(water, (0, 500))
def main():
global screen
try:
screen = pygame.display.set_mode((screenW, screenH), pygame.DOUBLEBUF | pygame.HWSURFACE, 16) #| pygame.FULLSCREEN
setupBeam()
gc.disable()
looping = True
while 1:
pygame.display.flip()
deltat = clock.tick(FRAMES_PER_SECOND)
#print deltat
# clear screen
screen.fill((0,0,0))
drawLogo()
updateBeams()
waveScroller()
screen.fill((0,0,50), (0, 500, 800, 100))
makeWater()
# draw screen
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN # key down or up?
if down:
if event.key == K_ESCAPE:
sys.exit(0) # quit the game
else:
looping = False
break
# after breaking from the while loop, go to lounge screen
lounge_screen.main()
finally:
gc.enable()
pygame.quit() # Keep this IDLE friendly
| Python |
import pygame
class Tile(pygame.sprite.Sprite):
SOLID = 1
BREAKABLE = 2
EMPTY = 3
type = 1 # default type = SOLID
item = None
image = None
size = 0
def __init__(self, type):
self.type = type
if type == self.SOLID:
self.image = pygame.image.load('images/tile_desert_solid.png')
elif type == self.BREAKABLE:
self.image = pygame.image.load('images/tile_desert_breakable.png')
elif type == self.EMPTY:
self.image = pygame.image.load('images/tile_desert_empty.png')
self.size = self.image.get_width()
def update(self, collisions):
pass
| Python |
import sys
print
| Python |
import sys
print
| Python |
#!/usr/bin/env python
import pygame
import os, sys
import gc
import lounge_screen
from ctypes import *
from pygame.locals import *
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = None
screenW = 800
screenH = 600
tileSize = 32
screen = None
sinewave = [
100,97,95,92,90,87,85,82,80,78,75,73,70,68,66,63,
61,59,57,54,52,50,48,46,44,42,40,38,36,34,32,30,
29,27,25,24,22,20,19,18,16,15,14,12,11,10,9,8,
7,6,5,4,4,3,2,2,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,1,1,2,2,3,3,4,5,6,6,
7,8,9,11,12,13,14,15,17,18,20,21,23,24,26,28,
29,31,33,35,37,39,41,43,45,47,49,51,53,55,58,60,
62,65,67,69,72,74,76,79,81,84,86,88,91,93,96,98,
101,103,106,108,111,113,115,118,120,123,125,127,130,132,134,137,
139,141,144,146,148,150,152,154,156,158,160,162,164,166,168,170,
171,173,175,176,178,179,181,182,184,185,186,187,188,190,191,192,
193,193,194,195,196,196,197,197,198,198,199,199,199,199,199,199,
199,199,199,199,199,198,198,198,197,197,196,195,195,194,193,192,
191,190,189,188,187,185,184,183,181,180,179,177,175,174,172,170,
169,167,165,163,161,159,157,155,153,151,149,147,145,142,140,138,
136,133,131,129,126,124,121,119,117,114,112,109,107,104,102,100
]
scrollText = " *GBOMBER 2008* CODING BY THE G-MEN PRESS ANYKEY TO CONTINUE POWERED BY PYTHON AND THE AMAZING ... PYGAME LIB "
sineScrollerIndex = 0
sineScrollerX = 0
textIndex = 0
def waveScroller():
global sineScrollerX, sineScrollerIndex, screen, sineScrollerSurface, screenH, screenW, textIndex, scrollTextSurface
step = 4 #px
sineIndex = sineScrollerIndex
for index in range (0, screenW/step):
subsurface = sineScrollerSurface.subsurface((index * step, 0, step, 120))
screen.blit(subsurface, (0 + (index * step), 200 + (int(sinewave[sineIndex] * 1.2) ) ))
sineIndex += 1
if sineIndex >= 255:
sineIndex = 0
sineScrollerIndex += 3
if sineScrollerIndex >= 255:
sineScrollerIndex = 0
#
# make better system here with modulo offsets (width/step)
#
sineScrollerX -= 5
if sineScrollerX < -55: # width of one character (guessed)
textIndex += 1
if textIndex > (len(scrollText) - 1):
textIndex = 0
sineScrollerX = 0
scrollTextSurface.fill((0,0,0))
scrollTextSurface = font.render(scrollText[textIndex:], 0, (200,200,200))
sineScrollerSurface.fill((0,0,0))
sineScrollerSurface.blit(scrollTextSurface, (sineScrollerX, 0))
beam = []
def setupBeam():
global beam
for i in range(0, 16):
beam.append((0, i*16, 0))
for i in range(15, 0, -1):
beam.append((0, i*16, 0))
beamCenter = 270
def drawBeam(sinepos):
global screen
y = beamCenter + sinewave[sinepos]
for color in beam:
pygame.draw.line(screen, color, (0, y), (screenW-1, y), 1)
y += 1
# increase thread priority for this thread
hthread = windll.kernel32.GetCurrentThread()
windll.kernel32.SetThreadPriority(hthread,1)
pygame.init()
pygame.mouse.set_visible(0)
#pygame.display.set_icon(pygame.image.load(data.filepath("icon.gif")))
pygame.display.set_caption("PyBomber 2008")
clock = pygame.time.Clock()
FRAMES_PER_SECOND = 150
direction = False
#start positions in sine index < 255
beams = [0, 15, 30, 45, 60, 75, 90]
beamColors = [(255, 0, 255), (255, 255, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0)]
def updateBeams():
i = 0
for beam in beams:
if beam >= 254:
beams[i] = 0
else:
beams[i] = beam + 2
i += 1
index = 0
for beam in beams:
drawBeam(beam)
index += 1
font = pygame.font.Font('c:/Windows/Fonts/DejaVuMonoSansBold.ttf', 100)
scrollTextSpecific = None
scrollColors = [140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 250, 245, 240, 235, 230, 225, 220, 215, 210, 205, 200, 195, 190, 185, 180, 175, 170, 165, 160, 155, 150, 145, 140]
currentScrollColor = 0
scrollX = screenW
sineScrollerSurface = pygame.Surface((screenW, 120))
sineScrollerSurface.set_colorkey((0,0,0))
scrollTextSurface = font.render(scrollText, 0, (200,200,200))
def scroller():
global screen, scrollX, scrollTextSpecific, currentScrollColor
color = scrollColors[currentScrollColor]
scrollTextSpecific = font.render("=== PYTHON/BOMBER 2008 GAME ===", 0, (color,color,color))
currentScrollColor += 1
if currentScrollColor >= len(scrollColors):
currentScrollColor = 0
screen.blit(scrollTextSpecific, (scrollX,400))
scrollX -= 5
if scrollX <= 0:
scrollX = screenW
logoIndex = 0
def drawLogo():
global screen, logoIndex
#logo = pygame.image.load('images/gbomber_logo.png')
logo = pygame.image.load('images/gbomber_logo_green.png')
xPos = (screenW - logo.get_width() - 600)/2
xPos += int(sinewave[logoIndex] * 3)
logoIndex += 4
if logoIndex >= 255:
logoIndex = 0
screen.blit(logo, (xPos, 50))
def makeWater():
global screen
subsurface = screen.subsurface((0, 400, 800, 100))
water = pygame.transform.flip(subsurface, False, True)
pxarray = pygame.PixelArray(water)
water = pxarray.make_surface()
del(pxarray)
water.set_alpha(100)
water.set_colorkey((0,0,0))
screen.blit(water, (0, 500))
def main():
global screen
try:
screen = pygame.display.set_mode((screenW, screenH), pygame.DOUBLEBUF | pygame.HWSURFACE, 16) #| pygame.FULLSCREEN
setupBeam()
gc.disable()
looping = True
while 1:
pygame.display.flip()
deltat = clock.tick(FRAMES_PER_SECOND)
#print deltat
# clear screen
screen.fill((0,0,0))
drawLogo()
updateBeams()
waveScroller()
screen.fill((0,0,50), (0, 500, 800, 100))
makeWater()
# draw screen
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN # key down or up?
if down:
if event.key == K_ESCAPE:
sys.exit(0) # quit the game
else:
looping = False
break
# after breaking from the while loop, go to lounge screen
lounge_screen.main()
finally:
gc.enable()
pygame.quit() # Keep this IDLE friendly
| Python |
#!/usr/bin/env python
import pygame
import os, sys
from pygame.locals import *
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = None
screenW = 800
screenH = 600
tileSize = 32
k_up = k_down = k_left = k_right = 0
map = [
['W','W','W','W','W','W','W','W','W','W','W','W','W'],
['W','B','B','B','B','_','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','_','_','_','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','B','B','B','B','B','_','_','_','_','W'],
['W','_','W','_','W','B','W','B','W','_','W','_','W'],
['W','_','_','B','_','B','_','B','B','B','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','_','_','B','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','B','W','_','W'],
['W','_','_','_','B','B','B','B','_','_','_','_','W'],
['W','W','W','W','W','W','W','W','W','W','W','W','W']
];
def drawArena():
tile_solid = pygame.image.load('images/tile_desert_solid.png')
tile_empty = pygame.image.load('images/tile_desert_empty.png')
tile_breakable = pygame.image.load('images/tile_desert_breakable.png')
x = 0
y = 0
for row in map:
for tile in row:
if tile == 'W':
screen.blit(tile_solid, (x, y))
elif tile == 'B':
screen.blit(tile_breakable, (x, y))
elif tile == '_':
screen.blit(tile_empty, (x, y))
x += tileSize
x = 0
y += tileSize
pygame.display.flip()
playerX = 100
playerY = 100
playerMovingUp = False
playerMovingDown = False
playerMovingLeft = False
playerMovingRight = False
def clearMovement():
global playerMovingUp, playerMovingDown, playerMovingLeft, playerMovingRight
playerMovingUp = False
playerMovingDown = False
playerMovingLeft = False
playerMovingRight = False
def drawPlayer():
global screen, playerX, playerY
player = pygame.image.load('images/player_temp.png')
screen.blit(player, (playerX, playerY))
def main():
global playerX, playerY, playerMovingUp, playerMovingDown, playerMovingLeft, playerMovingRight
if playerMovingUp:
playerY -= 2
elif playerMovingDown:
playerY += 2
elif playerMovingLeft:
playerX -= 2
elif playerMovingRight:
playerX += 2
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN # key down or up?
print down
if down:
if event.key == K_RIGHT:
playerMovingRight = True
elif event.key == K_LEFT:
playerMovingLeft = True
elif event.key == K_UP:
playerMovingUp = True
elif event.key == K_DOWN:
playerMovingDown = True
elif event.key == K_ESCAPE: sys.exit(0) # quit the game
else:
clearMovement()
drawPlayer()
def main():
global screen
pygame.init()
pygame.mouse.set_visible(0)
#pygame.display.set_icon(pygame.image.load(data.filepath("icon.gif")))
pygame.display.set_caption("PyBomber 2008")
clock = pygame.time.Clock()
FRAMES_PER_SECOND = 100
try:
screen = pygame.display.set_mode((screenW, screenH))
# This should show a blank 200 by 200 window centered on the screen
drawArena()
looping = True
while looping:
deltat = clock.tick(FRAMES_PER_SECOND)
pygame.display.flip()
evt = pygame.event.wait()
if evt.type == pygame.QUIT:
looping = False
break
finally:
pygame.quit() # Keep this IDLE friendly
| Python |
#!/usr/bin/env python
import pygame
import os, sys
from pygame.locals import *
from player import Player
import inter_results_screen
import final_results_screen
from arena import Arena
from match import Match
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = None
screenW = 800
screenH = 600
tileSize = 32
arenaSurface = pygame.Surface((screenW, screenH))
def drawArena():
global arena, arenaSurface
x = y = 0
for row in arena.map:
for tile in row:
arenaSurface.blit(tile.image, (x, y))
x += tileSize
x = 0
y += tileSize
def checkKeyboard():
global player
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
#print event.type
if event.type == KEYDOWN:
if event.key == K_ESCAPE: sys.exit(0) # quit the game
elif event.type == KEYUP:
player.clearMovement()
if (pygame.key.get_pressed()[K_RIGHT]) and (not pygame.key.get_pressed()[K_LEFT]):
player.moveRight()
elif (pygame.key.get_pressed()[K_LEFT]) and (not pygame.key.get_pressed()[K_RIGHT]):
player.moveLeft()
elif (pygame.key.get_pressed()[K_UP]) and (not pygame.key.get_pressed()[K_DOWN]):
player.moveUp()
elif (pygame.key.get_pressed()[K_DOWN]) and (not pygame.key.get_pressed()[K_UP]):
player.moveDown()
#
# move this stuff into main method
#
pygame.init()
pygame.mouse.set_visible(0)
#pygame.display.set_icon(pygame.image.load(data.filepath("icon.gif")))
pygame.display.set_caption("PyBomber 2008")
clock = pygame.time.Clock()
FRAMES_PER_SECOND = 40
try:
screen = pygame.display.set_mode((screenW, screenH))
rect = screen.get_rect()
player = Player(Player.RED, 'images/player_temp.png', rect.center)
player_group = pygame.sprite.RenderPlain(player)
match = Match()
arena = Arena()
screen.fill((0,0,0))
drawArena()
looping = True
while looping:
deltat = clock.tick(FRAMES_PER_SECOND)
player_group.clear(screen, arenaSurface)
checkKeyboard()
screen.blit(arenaSurface, (0, 0))
player_group.update(deltat)
player_group.draw(screen)
pygame.display.flip()
#if match.roundIsOver():
# inter_results_screen.main()
# break
if match.isOver():
break
#evt = pygame.event.wait()
#if evt.type == pygame.QUIT:
# break
final_results_screen.main()
finally:
pygame.quit() # Keep this IDLE friendly
| Python |
#!/usr/bin/env python
import os, sys
import title_screen
print("GBomber")
title_screen.main()
| Python |
#!/usr/bin/env python
import os, sys
import title_screen
print("GBomber")
title_screen.main()
| Python |
#!/usr/bin/env python
import pygame
import os, sys
from pygame.locals import *
from player import Player
import inter_results_screen
import final_results_screen
from arena import Arena
from match import Match
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = None
screenW = 800
screenH = 600
tileSize = 32
arenaSurface = pygame.Surface((screenW, screenH))
def drawArena():
global arena, arenaSurface
x = y = 0
for row in arena.map:
for tile in row:
arenaSurface.blit(tile.image, (x, y))
x += tileSize
x = 0
y += tileSize
def checkKeyboard():
global player
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
#print event.type
if event.type == KEYDOWN:
if event.key == K_ESCAPE: sys.exit(0) # quit the game
elif event.type == KEYUP:
player.clearMovement()
if (pygame.key.get_pressed()[K_RIGHT]) and (not pygame.key.get_pressed()[K_LEFT]):
player.moveRight()
elif (pygame.key.get_pressed()[K_LEFT]) and (not pygame.key.get_pressed()[K_RIGHT]):
player.moveLeft()
elif (pygame.key.get_pressed()[K_UP]) and (not pygame.key.get_pressed()[K_DOWN]):
player.moveUp()
elif (pygame.key.get_pressed()[K_DOWN]) and (not pygame.key.get_pressed()[K_UP]):
player.moveDown()
#
# move this stuff into main method
#
pygame.init()
pygame.mouse.set_visible(0)
#pygame.display.set_icon(pygame.image.load(data.filepath("icon.gif")))
pygame.display.set_caption("PyBomber 2008")
clock = pygame.time.Clock()
FRAMES_PER_SECOND = 40
try:
screen = pygame.display.set_mode((screenW, screenH))
rect = screen.get_rect()
player = Player(Player.RED, 'images/player_temp.png', rect.center)
player_group = pygame.sprite.RenderPlain(player)
match = Match()
arena = Arena()
screen.fill((0,0,0))
drawArena()
looping = True
while looping:
deltat = clock.tick(FRAMES_PER_SECOND)
player_group.clear(screen, arenaSurface)
checkKeyboard()
screen.blit(arenaSurface, (0, 0))
player_group.update(deltat)
player_group.draw(screen)
pygame.display.flip()
#if match.roundIsOver():
# inter_results_screen.main()
# break
if match.isOver():
break
#evt = pygame.event.wait()
#if evt.type == pygame.QUIT:
# break
final_results_screen.main()
finally:
pygame.quit() # Keep this IDLE friendly
| Python |
import sys
print
| Python |
#!/usr/bin/env python
import pygame
import os, sys
from pygame.locals import *
os.environ['SDL_VIDEO_CENTERED'] = '1'
screen = None
screenW = 800
screenH = 600
tileSize = 32
k_up = k_down = k_left = k_right = 0
map = [
['W','W','W','W','W','W','W','W','W','W','W','W','W'],
['W','B','B','B','B','_','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','_','_','_','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','B','B','B','B','B','_','_','_','_','W'],
['W','_','W','_','W','B','W','B','W','_','W','_','W'],
['W','_','_','B','_','B','_','B','B','B','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','_','_','B','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','B','W','_','W'],
['W','_','_','_','B','B','B','B','_','_','_','_','W'],
['W','W','W','W','W','W','W','W','W','W','W','W','W']
];
def drawArena():
tile_solid = pygame.image.load('images/tile_desert_solid.png')
tile_empty = pygame.image.load('images/tile_desert_empty.png')
tile_breakable = pygame.image.load('images/tile_desert_breakable.png')
x = 0
y = 0
for row in map:
for tile in row:
if tile == 'W':
screen.blit(tile_solid, (x, y))
elif tile == 'B':
screen.blit(tile_breakable, (x, y))
elif tile == '_':
screen.blit(tile_empty, (x, y))
x += tileSize
x = 0
y += tileSize
pygame.display.flip()
playerX = 100
playerY = 100
playerMovingUp = False
playerMovingDown = False
playerMovingLeft = False
playerMovingRight = False
def clearMovement():
global playerMovingUp, playerMovingDown, playerMovingLeft, playerMovingRight
playerMovingUp = False
playerMovingDown = False
playerMovingLeft = False
playerMovingRight = False
def drawPlayer():
global screen, playerX, playerY
player = pygame.image.load('images/player_temp.png')
screen.blit(player, (playerX, playerY))
def main():
global playerX, playerY, playerMovingUp, playerMovingDown, playerMovingLeft, playerMovingRight
if playerMovingUp:
playerY -= 2
elif playerMovingDown:
playerY += 2
elif playerMovingLeft:
playerX -= 2
elif playerMovingRight:
playerX += 2
for event in pygame.event.get():
if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN # key down or up?
print down
if down:
if event.key == K_RIGHT:
playerMovingRight = True
elif event.key == K_LEFT:
playerMovingLeft = True
elif event.key == K_UP:
playerMovingUp = True
elif event.key == K_DOWN:
playerMovingDown = True
elif event.key == K_ESCAPE: sys.exit(0) # quit the game
else:
clearMovement()
drawPlayer()
def main():
global screen
pygame.init()
pygame.mouse.set_visible(0)
#pygame.display.set_icon(pygame.image.load(data.filepath("icon.gif")))
pygame.display.set_caption("PyBomber 2008")
clock = pygame.time.Clock()
FRAMES_PER_SECOND = 100
try:
screen = pygame.display.set_mode((screenW, screenH))
# This should show a blank 200 by 200 window centered on the screen
drawArena()
looping = True
while looping:
deltat = clock.tick(FRAMES_PER_SECOND)
pygame.display.flip()
evt = pygame.event.wait()
if evt.type == pygame.QUIT:
looping = False
break
finally:
pygame.quit() # Keep this IDLE friendly
| Python |
from tile import Tile
class Arena:
name = "The Name Of Arena"
dimensions = (30, 20)
players = []
amountOfExtraBombs = 15
amountOfExtraFlames = 15
amountOFKicks = 4
#
# this should be just initial character map, but there needs to be also
# object map.
#
initMap = [
['W','W','W','W','W','W','W','W','W','W','W','W','W'],
['W','B','B','B','B','_','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','_','_','_','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','B','B','B','B','B','_','_','_','_','W'],
['W','_','W','_','W','B','W','B','W','_','W','_','W'],
['W','_','_','B','_','B','_','B','B','B','_','_','W'],
['W','_','W','_','W','_','W','_','W','_','W','_','W'],
['W','_','_','_','_','B','_','_','_','_','_','_','W'],
['W','_','W','_','W','_','W','_','W','B','W','_','W'],
['W','_','_','_','B','B','B','B','_','_','_','_','W'],
['W','W','W','W','W','W','W','W','W','W','W','W','W']
];
map = []
def __init__(self):
for row in self.initMap:
list = []
for tile in row:
if tile == 'W':
list.append(Tile(Tile.SOLID))
elif tile == 'B':
list.append(Tile(Tile.BREAKABLE))
elif tile == '_':
list.append(Tile(Tile.EMPTY))
self.map.append(list)
def randomizeMapContents(self):
x = y = 0
for y in range(0, self.dimensions[0]):
for x in range(0, self.dimensions[1]):
break
#tile = map[y][x];
#if tile.type == Tile.BREAKABLE:
# pass
def checkStatus(self):
# players have been moved
# events has been done
# check what has happened
# create events
# create messages
# send messages to players
pass
def draw():
pass
| Python |
class Match:
date = None
matchOn = False
arena = None
neededVictories = 4
durationSeconds = 120
players = []
winner = None # player
over = False
def __init__(self):
pass
def addPlayer(self, player):
self.players.append(player)
def isOver(self):
for p in self.players:
if p.victories >= self.neededVictories:
self.over = True
return self.over;
| Python |
__author__ = 'Brad'
| Python |
import this
| Python |
__author__ = 'Ian'
def clinic():
"""Function gives operator two options, and then prints results to screen"""
print "You've just entered the clinic!"
print "Do you take the door on the left or the right?"
answer = raw_input("Type left or right and hit 'Enter'.").lower()
if answer == "left" or answer == "l":
print "This is the Verbal Abuse Room, you heap of parrot droppings!"
elif answer == "right" or answer == "r":
print "Of course this is the Argument Room, I've told you that already!"
else:
print "You didn't pick left or right! Try again."
clinic()
| Python |
__author__ = 'Ian'
def PygLatin():
"""A function used for turing any english word into its Piglatin equavelent"""
print "Welcome to the English to Pig Latin Translator!"
word = raw_input("Please provide a word to be translated:")
pyg = "ay"
newword = word.lower()
firstletter= newword[0]
vowelArray = ["A", "E", "I", "O", "U", "Y"]
if len(word) > 0 and word.isalpha():
if firstletter in vowelArray:
new_word = word + pyg
print new_word
else:
new_word = newword[1:] + firstletter + pyg
print new_word
elif word.isalpha() is False:
print "You have entered a number, please enter a word!"
else:
print "You have failed to enter in an alphanumerical, please try again!"
| Python |
__author__ = 'Ian'
import translator,clinic
translator.PygLatin()
| Python |
import sys
__author__ = 'Ian'
loginDict={"Ian":"Bouldin", "Brad":"Zylstra"}
print ("Welcome to Inferno v1.0")
while True:
prompt1 = "Please Provide Your User Name: "
username = raw_input(prompt1)
try:
passwordLogin=loginDict[username]
print "Welcome %s!" % username
break
except:
print "username not in database"
for x in range (2, -1, -1):
prompt2 = "Please Provide Your Password: "
password = raw_input(prompt2)
if password==passwordLogin:
print "You have successfully logged in!"
break
else:
print"Password incorrect, you have "+str(x)+" login attempt(s) remaining!"
if x==0:
print "You are kicked off the system, your ip address has been recorded"
sys.exit() | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#pylint: disable=C0103
"Fake answers for testing Control the monochromator CM-110"
print "%c" % chr(27) #CM.echo()
print "%c" % chr(27) #CM.echo()
print "%c" % chr(27) #CM.echo()
print "%c\n%c" % (chr(1), chr(24)) #CM.select(1)
print "%c\n%c" % (chr(1), chr(24)) #CM.select(2)
print "%c\n%c" % (chr(0), chr(24)) #CM.units(0)
print "%c\n%c" % (chr(1), chr(24)) #CM.units("nm")
print "%c\n%c" % (chr(2), chr(24)) #CM.units(2)
print "%c\n%c" % (chr(2), chr(24)) #CM.goto(800)
print "%c\n%c" % (chr(2), chr(24)) #CM.goto(0)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(0)
print "%c\n%c\n%c\n%c" % (chr(0), chr(0), chr(2), chr(24)) #CM.query(1)
print "%c\n%c\n%c\n%c" % (chr(4), chr(0xB0), chr(2), chr(24)) #CM.query(2)
print "%c\n%c\n%c\n%c" % (chr(2), chr(0x58), chr(2), chr(24)) #CM.query(3)
print "%c\n%c\n%c\n%c" % (chr(0), chr(1), chr(2), chr(24)) #CM.query(4)
print "%c\n%c\n%c\n%c" % (chr(0), chr(250), chr(2), chr(24)) #CM.query(5)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(6)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(13)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(14)
print "%c\n%c\n%c\n%c" % (chr(01), chr(123), chr(2), chr(24)) #CM.query(19)
#CM.query_all() :
print "%c\n%c\n%c\n%c" % (chr(2), chr(0x58), chr(2), chr(24)) #CM.query(3)
print "%c\n%c\n%c\n%c" % (chr(0), chr(1), chr(2), chr(24)) #CM.query(4)
print "%c\n%c\n%c\n%c" % (chr(4), chr(0xB0), chr(2), chr(24)) #CM.query(2)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(13)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(0)
print "%c\n%c\n%c\n%c" % (chr(01), chr(123), chr(2), chr(24)) #CM.query(19)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(6)
print "%c\n%c\n%c\n%c" % (chr(0), chr(250), chr(2), chr(24)) #CM.query(5)
print "%c\n%c\n%c\n%c" % (chr(0), chr(0), chr(2), chr(24)) #CM.query(1)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(14)
for i in range(66): #CM.query_all()
print i
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"Control the monochromator CM-110"
import logging
import inspect
from serial import Serial
def show_frame():
"Show info about the program place where called"
stack = inspect.stack()
for record in stack[1:]:
print "Module %s, file %s, line %s, function %s." % (
inspect.getmodule(record[0]), record[1], record[2], record[3])
if record[5]:
print "%d:" % record[5]
for line in record[4]:
print line,
PORT = "/dev/cuaU0"
LOG = logging.INFO # WARN INFO DEBUG
CONFIGDIR = "~/.flash-photolysis"
SAVEFILE = CONFIGDIR + "/NOVRAM"
REPRES = {
ord("\r"): r"\r", #CR
ord("\n"): r"\n", #LF
ord("\t"): r"\t", #TAB
ord("\0"): r"\0", #NUL
27: r"\e", #ESC
}
def repr_(byte):
"Representing a byte for text"
byte = ord(byte)
if byte in REPRES:
return REPRES[byte]
if not (32 <= byte < 127):
return "\\0%(byte)o" % ({"byte": byte})
return chr(byte)
class CM110_Logs(object): # pylint: disable=C0103
"Logging for Monochromator CM110/CM112 from CVI Laser Corp."
def __init__(self, stream=None, port=PORT):
self.port = Serial(port)
self.port.setTimeout(30) # some operations need long time...
self.logger = self.set_log(stream)
def set_log(self, stream): # pylint: disable=R0201
"Change the logger"
logger = logging.getLogger('simple')
logger.addHandler(logging.StreamHandler(stream))
logger.setLevel(LOG)
return logger
def log_send(self, byte):
"Write to a journal what will be sent, in few formats"
self.logger.debug("Sending: int:%(byte)d hex:%(byte)x "
"oct:%(byte)o str:%(repr)s",
{"byte" : ord(byte), "repr": repr_(byte)})
def log_received(self, byte):
"Write to a journal what was received, in few formats"
self.logger.debug("Received: int:%(byte)d hex:%(byte)x "
"oct:%(byte)o str:%(repr)s"
% {"byte" : ord(byte), "repr": repr_(byte)})
def log_status(self, byte):
"Write to a journal what is received status"
byte = ord(byte)
units = byte & 7
if units == 0:
units = "Microns (10nm)"
elif units == 1:
units = "nm"
elif units == 2:
units = "Å"
else:
units = " Wrong units!"
result = "Status: " + " ".join((
"Not accepted" if (byte & 128) else "Accepted",
"No action" if (byte & 64) else "Action",
"Too small" if (byte & 32) else "Too large",
"" if (byte & 128) else "(irrelevant)",
"Negative going" if (byte & 16) else "Positive going",
"" if (byte & 128) else "(irrelevant)",
"Negative orders" if (byte & 8) else "Positive orders",
units,
"(For SCAN:",
"Lambda1 not acceptable" if (byte & 64) else "Lambda 1 OK",
"Lambda2 not acceptable" if (byte & 32) else "Lambda 2 OK",
")",
))
self.logger.info(result)
def log_state(self, state):
"Write to a journal the state of monochromator"
self.logger.info("State of the monochromator CM110/CM112:")
self.logger.info("\tWavelength: %d", state["position"])
self.logger.info("\tType byte: %d", state["type"])
self.logger.info("\tGrooves/mm: %d", state["grooves"])
self.logger.info("\tBlaze, nm: %d", state["blaze"])
self.logger.info("\tCurrent grating: %d", state["grating"])
self.logger.info("\tSpeed, Å/s: %d", state["speed"])
self.logger.info("\tSize: %d", state["size"])
self.logger.info("\tNumber of gratings: %d", state["num_of_gratings"])
self.logger.info("\tUnits (0=10nm 1=nm 2=Å): %d", state["units"])
self.logger.info("\tSerial number: %d", state["serial_num"])
def send(self, byte):
"Log and send a byte"
self.log_send(byte)
self.port.write(byte) # send to monochromator
self.logger.debug("Send OK: %s" % repr_(byte))
def receive(self, byte):
"Receive, log, and check a byte. byte=None means any value is OK."
resp = self.port.read(1) # read 1 byte from monochromator
if resp == "":
self.logger.critical("Timeout!")
exit(1)
self.log_received(resp)
if byte is not None and resp != byte:
self.logger.warn("ERROR: wrong reply, expected: %s, got: %s." % (
repr_(byte), repr_(resp)))
else:
self.logger.debug("Receive OK: %s" % repr_(resp))
return resp
class CM110_Commands(CM110_Logs): # pylint: disable=C0103
"Command for Monochromator CM110/CM112 from CVI Laser Corp."
subq_table = {
"position": 0,
"type": 1,
"grooves": 2,
"blaze": 3,
"grating": 4,
"speed": 5,
"size": 6,
"num_of_gratings": 13,
"units": 14,
"serial_num": 19,
}
state_limits = {
"position": {"type": "special"},
"type": {"type": "list", "list": (0, 1, 254)},
"grooves": {"type": "list", "list": (3600, 2400, 1800, 1200,
600, 300, 150, 75)},
"blaze": {"type": "limits", "limits": (0, 24000)},
"grating": {"type": "list", "list": (1, 2)}, #<=num_of_gratings
"speed": {"type": "special"},
"size": {"type": "special"},
"num_of_gratings": {"type": "list", "list": (1, 2)},
"units": {"type": "list", "list": (0, 1, 2)}, # centimicron, nm, Å
"serial_num": {"type": "None"},
}
def state_is_sane(self, state):
"Check that some of the state values are legal"
for subq, limits in self.state_limits.iteritems():
if limits["type"] in ("None", "special"):
continue
elif ((limits["type"] == "list" and
state[subq] not in limits["list"]) or
(limits["type"] == "limits" and not
(limits["limits"][0] <= state[subq] <= limits["limits"][1]))):
self.logger.warn("state[%s] = %s not in %s!" %
(subq, state[subq], limits["list"]))
return False
if not (0 < state["grating"] <= state["num_of_gratings"]):
self.logger.warn("Selected grating %s not in %s!" %
(state["grating"], [0, state["num_of_gratings"]]))
return False
return True
def echo(self):
"Verify communication"
self.send(chr(27))
result = self.receive(chr(27))
return result == chr(27)
def goto(self, wavelength):
"Set wavelength"
self.send(chr(16))
self.send(chr(wavelength>>8)) # high byte
self.send(chr(wavelength%256)) # low byte
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
return status
def query(self, subq):
"Read current state of monochromater"
assert (subq in self.subq_table or subq in self.subq_table.values()), \
"Wrong subquery!"
if subq in self.subq_table:
subq = self.subq_table[subq]
self.send(chr(56))
self.send(chr(subq))
high = ord(self.receive(None))
low = ord(self.receive(None))
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
return high * 256 + low
def query_all(self):
"Read full current state of monochromater, return it as dict"
result = {}
for subq in self.subq_table.keys():
result[subq] = self.query(subq)
self.log_state(result)
self.state_is_sane(result)
return result
def select(self, grating):
"Select grating 1 or 2"
if grating in ("1", "2"):
grating = int(grating)
assert grating in (1, 2), "Wrong grating number: %s." % grating
self.send(chr(26))
self.send(chr(grating))
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
def units(self, unit):
"Select units for commands goto, scan, size, calibrate"
unit_table = {"10nm": 0, "nm": 1, "Å": 2}
assert (unit in unit_table or unit in unit_table.values()), \
"Wrong units!"
if unit in unit_table:
unit = unit_table[unit]
self.send(chr(50))
self.send(chr(unit))
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
def readNOVRAM(self, address): # pylint: disable=C0103
"Read a byte from NOVRAM in monochromator"
assert (0 <= address <= 127), "Wrong NOVRAM address!"
self.send(chr(156))
self.send(chr(address))
result = self.receive(None)
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
return result
def readNOVRAM_all(self): # pylint: disable=C0103
"Read all 128 bytes from monochromator NOVRAM"
result = ""
for addr in xrange(128):
result += self.readNOVRAM(addr)
return result
def save_NOVRAM(self, fname=SAVEFILE): # pylint: disable=C0103
"Save the contents of memory in a binary file"
novram = self.readNOVRAM_all()
with open(fname, "wb") as fil:
fil.write(novram)
class CM110(CM110_Commands):
"Class with the state of a CM100 monochromator"
def __init__(self, stream=None, port=PORT):
CM110_Commands.__init__(self, stream, port)
self.state = self.query_all()
def get_state(self):
"Re-read the device state"
self.state = self.query_all()
if __name__ == '__main__':
CM = CM110_Commands()
CM.logger.info("sendBreak")
CM.port.sendBreak()
CM.logger.info("flushInput")
CM.port.flushInput()
CM.logger.info("echo")
CM.echo()
CM.logger.info("echo")
CM.echo()
CM.logger.info("echo")
CM.echo()
CM.logger.info("select 2")
CM.select(2)
CM.logger.info("select 1")
CM.select(1)
CM.logger.info("units 0")
CM.units(0)
CM.logger.info("units nm")
CM.units("nm")
CM.logger.info("units 2")
CM.units(2)
CM.logger.info("goto 800")
CM.goto(800)
CM.logger.info("goto 0")
CM.goto(0)
CM.logger.info("query_all")
CM.query_all()
CM.logger.info("select 2")
CM.select(2)
CM.logger.info("goto 800")
CM.goto(800)
CM.logger.info("query_all")
CM.query_all()
CM.logger.info("readNOVRAM_all")
CM.save_NOVRAM("NOVRAM")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"Test PyGTK"
import pygtk
pygtk.require('2.0')
import gtk
from CM110 import CM110
class StreamLike(object): # pylint: disable=R0903
"A stream-like class to show logs in a window"
def __init__(self, textview):
self.textview = textview
def write(self, message):
"Add a message into the widget buffer"
buff = self.textview.get_buffer()
buff.insert(buff.get_end_iter(), message)
self.textview.scroll_mark_onscreen(buff.get_insert())
## def flush(self):
## "Required by API"
## pass
class PyApp(gtk.Window): # pylint: disable=R0904,R0924
"Try to make a window"
def __init__(self):
gtk.Window.__init__(self)
self.set_title("CM110 Control")
self.cm110 = CM110()
self.vbox1 = gtk.VBox()
# Prepare First two lines of widgets
self.vbox1.hbox1 = self.setup_hbox1()
self.vbox1.scrolledwindow1 = self.setup_scrolledwindow1()
self.cm110.set_log(StreamLike(self.vbox1.scrolledwindow1.textview1))
self.vbox1.pack_start(self.vbox1.hbox1, expand=False, fill=False)
self.vbox1.pack_start(self.vbox1.scrolledwindow1, expand=True,
fill=True)
self.add(self.vbox1)
self.connect("destroy", gtk.main_quit)
self.show_all()
def setup_hbox1(self):
"Create hbox1 and its internals"
hbox1 = gtk.HBox()
hbox1.label1 = gtk.Label(" Wavelength:")
adjustment = gtk.Adjustment(self.cm110.state["position"], 0, 99000)
hbox1.spinbutton1 = gtk.SpinButton(adjustment, 0, 0)
hbox1.spinbutton1.set_numeric(True)
hbox1.spinbutton1.update()
adjustment.connect("value_changed", self.wavelength, hbox1.spinbutton1)
hbox1.combobox1 = gtk.combo_box_new_text()
for txt in ("10nm", "nm", "Å"):
hbox1.combobox1.append_text(txt)
hbox1.combobox1.set_active(self.cm110.state["units"])
hbox1.combobox1.connect("changed", self.units)
hbox1.button3 = gtk.Button("State")
hbox1.button3.connect("clicked", self.get_state)
hbox1.button4 = gtk.Button("Save NOVRAM")
hbox1.button4.connect("clicked", self.save_NOVRAM)
hbox1.label2 = gtk.Label("Grating:")
hbox1.combobox2 = gtk.combo_box_new_text()
hbox1.combobox2.append_text("1")
if self.cm110.state["num_of_gratings"] == 2:
hbox1.combobox2.append_text("2")
hbox1.combobox2.set_active(int(self.cm110.state["grating"])-1)
hbox1.combobox2.connect("changed", self.set_grating)
grating = "%d gr/mm, blaze %d nm." % (self.cm110.state["grooves"],
self.cm110.state["blaze"])
hbox1.label3 = gtk.Label(grating)
hbox1.button5 = gtk.Button("Close")
hbox1.button5.connect("clicked", gtk.main_quit)
hbox1.pack_start(hbox1.label2, expand=False, fill=False)
hbox1.pack_start(hbox1.combobox2, expand=False, fill=False)
hbox1.pack_start(hbox1.label3, expand=False, fill=False)
hbox1.pack_start(hbox1.label1, expand=False, fill=False)
hbox1.pack_start(hbox1.spinbutton1, expand=False, fill=False)
hbox1.pack_start(hbox1.combobox1, expand=False, fill=False)
hbox1.pack_start(hbox1.button3, expand=False, fill=False)
hbox1.pack_end(hbox1.button5, expand=False, fill=False)
hbox1.pack_end(hbox1.button4, expand=False, fill=False)
return hbox1
def setup_scrolledwindow1(self): # pylint: disable=R0201
"Create scrolled text window"
scrolledwindow1 = gtk.ScrolledWindow()
scrolledwindow1.textview1 = gtk.TextView()
scrolledwindow1.textview1.set_cursor_visible(False)
scrolledwindow1.textview1.set_editable(False)
scrolledwindow1.add(scrolledwindow1.textview1)
return scrolledwindow1
def get_state(self, _widget=None):
"Add some text to a buffer"
self.cm110.get_state()
self.vbox1.hbox1.spinbutton1.set_value(self.cm110.state["position"])
self.vbox1.hbox1.combobox1.set_active(self.cm110.state["units"])
grating = "%d gr/mm, blaze %d nm." % (self.cm110.state["grooves"],
self.cm110.state["blaze"])
self.vbox1.hbox1.label3.set_text(grating)
def units(self, widget):
"A call-back for units change"
self.cm110.units(widget.get_active_text())
self.vbox1.hbox1.spinbutton1.set_value(0) # It also resets wavelength
def wavelength(self, _widget, spin):
"A call-back for units change"
self.cm110.goto(spin.get_value_as_int())
def save_NOVRAM(self, _widget): # pylint: disable=C0103
"A call-back saving memory to a file"
self.cm110.save_NOVRAM()
def set_grating(self, widget):
"A call-back to select a grating"
self.cm110.select(widget.get_active_text())
self.get_state() # reflect the state change by re-reading the state
PYAPP = PyApp()
gtk.main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#pylint: disable=C0103
"Fake answers for testing Control the monochromator CM-110"
print "%c" % chr(27) #CM.echo()
print "%c" % chr(27) #CM.echo()
print "%c" % chr(27) #CM.echo()
print "%c\n%c" % (chr(1), chr(24)) #CM.select(1)
print "%c\n%c" % (chr(1), chr(24)) #CM.select(2)
print "%c\n%c" % (chr(0), chr(24)) #CM.units(0)
print "%c\n%c" % (chr(1), chr(24)) #CM.units("nm")
print "%c\n%c" % (chr(2), chr(24)) #CM.units(2)
print "%c\n%c" % (chr(2), chr(24)) #CM.goto(800)
print "%c\n%c" % (chr(2), chr(24)) #CM.goto(0)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(0)
print "%c\n%c\n%c\n%c" % (chr(0), chr(0), chr(2), chr(24)) #CM.query(1)
print "%c\n%c\n%c\n%c" % (chr(4), chr(0xB0), chr(2), chr(24)) #CM.query(2)
print "%c\n%c\n%c\n%c" % (chr(2), chr(0x58), chr(2), chr(24)) #CM.query(3)
print "%c\n%c\n%c\n%c" % (chr(0), chr(1), chr(2), chr(24)) #CM.query(4)
print "%c\n%c\n%c\n%c" % (chr(0), chr(250), chr(2), chr(24)) #CM.query(5)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(6)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(13)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(14)
print "%c\n%c\n%c\n%c" % (chr(01), chr(123), chr(2), chr(24)) #CM.query(19)
#CM.query_all() :
print "%c\n%c\n%c\n%c" % (chr(2), chr(0x58), chr(2), chr(24)) #CM.query(3)
print "%c\n%c\n%c\n%c" % (chr(0), chr(1), chr(2), chr(24)) #CM.query(4)
print "%c\n%c\n%c\n%c" % (chr(4), chr(0xB0), chr(2), chr(24)) #CM.query(2)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(13)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(0)
print "%c\n%c\n%c\n%c" % (chr(01), chr(123), chr(2), chr(24)) #CM.query(19)
print "%c\n%c\n%c\n%c" % (chr(0), chr(25), chr(2), chr(24)) #CM.query(6)
print "%c\n%c\n%c\n%c" % (chr(0), chr(250), chr(2), chr(24)) #CM.query(5)
print "%c\n%c\n%c\n%c" % (chr(0), chr(0), chr(2), chr(24)) #CM.query(1)
print "%c\n%c\n%c\n%c" % (chr(0), chr(2), chr(2), chr(24)) #CM.query(14)
for i in range(66): #CM.query_all()
print i
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"Control the monochromator CM-110"
import logging
import inspect
from serial import Serial
def show_frame():
"Show info about the program place where called"
stack = inspect.stack()
for record in stack[1:]:
print "Module %s, file %s, line %s, function %s." % (
inspect.getmodule(record[0]), record[1], record[2], record[3])
if record[5]:
print "%d:" % record[5]
for line in record[4]:
print line,
PORT = "/dev/cuaU0"
LOG = logging.INFO # WARN INFO DEBUG
CONFIGDIR = "~/.flash-photolysis"
SAVEFILE = CONFIGDIR + "/NOVRAM"
REPRES = {
ord("\r"): r"\r", #CR
ord("\n"): r"\n", #LF
ord("\t"): r"\t", #TAB
ord("\0"): r"\0", #NUL
27: r"\e", #ESC
}
def repr_(byte):
"Representing a byte for text"
byte = ord(byte)
if byte in REPRES:
return REPRES[byte]
if not (32 <= byte < 127):
return "\\0%(byte)o" % ({"byte": byte})
return chr(byte)
class CM110_Logs(object): # pylint: disable=C0103
"Logging for Monochromator CM110/CM112 from CVI Laser Corp."
def __init__(self, stream=None, port=PORT):
self.port = Serial(port)
self.port.setTimeout(30) # some operations need long time...
self.logger = self.set_log(stream)
def set_log(self, stream): # pylint: disable=R0201
"Change the logger"
logger = logging.getLogger('simple')
logger.addHandler(logging.StreamHandler(stream))
logger.setLevel(LOG)
return logger
def log_send(self, byte):
"Write to a journal what will be sent, in few formats"
self.logger.debug("Sending: int:%(byte)d hex:%(byte)x "
"oct:%(byte)o str:%(repr)s",
{"byte" : ord(byte), "repr": repr_(byte)})
def log_received(self, byte):
"Write to a journal what was received, in few formats"
self.logger.debug("Received: int:%(byte)d hex:%(byte)x "
"oct:%(byte)o str:%(repr)s"
% {"byte" : ord(byte), "repr": repr_(byte)})
def log_status(self, byte):
"Write to a journal what is received status"
byte = ord(byte)
units = byte & 7
if units == 0:
units = "Microns (10nm)"
elif units == 1:
units = "nm"
elif units == 2:
units = "Å"
else:
units = " Wrong units!"
result = "Status: " + " ".join((
"Not accepted" if (byte & 128) else "Accepted",
"No action" if (byte & 64) else "Action",
"Too small" if (byte & 32) else "Too large",
"" if (byte & 128) else "(irrelevant)",
"Negative going" if (byte & 16) else "Positive going",
"" if (byte & 128) else "(irrelevant)",
"Negative orders" if (byte & 8) else "Positive orders",
units,
"(For SCAN:",
"Lambda1 not acceptable" if (byte & 64) else "Lambda 1 OK",
"Lambda2 not acceptable" if (byte & 32) else "Lambda 2 OK",
")",
))
self.logger.info(result)
def log_state(self, state):
"Write to a journal the state of monochromator"
self.logger.info("State of the monochromator CM110/CM112:")
self.logger.info("\tWavelength: %d", state["position"])
self.logger.info("\tType byte: %d", state["type"])
self.logger.info("\tGrooves/mm: %d", state["grooves"])
self.logger.info("\tBlaze, nm: %d", state["blaze"])
self.logger.info("\tCurrent grating: %d", state["grating"])
self.logger.info("\tSpeed, Å/s: %d", state["speed"])
self.logger.info("\tSize: %d", state["size"])
self.logger.info("\tNumber of gratings: %d", state["num_of_gratings"])
self.logger.info("\tUnits (0=10nm 1=nm 2=Å): %d", state["units"])
self.logger.info("\tSerial number: %d", state["serial_num"])
def send(self, byte):
"Log and send a byte"
self.log_send(byte)
self.port.write(byte) # send to monochromator
self.logger.debug("Send OK: %s" % repr_(byte))
def receive(self, byte):
"Receive, log, and check a byte. byte=None means any value is OK."
resp = self.port.read(1) # read 1 byte from monochromator
if resp == "":
self.logger.critical("Timeout!")
exit(1)
self.log_received(resp)
if byte is not None and resp != byte:
self.logger.warn("ERROR: wrong reply, expected: %s, got: %s." % (
repr_(byte), repr_(resp)))
else:
self.logger.debug("Receive OK: %s" % repr_(resp))
return resp
class CM110_Commands(CM110_Logs): # pylint: disable=C0103
"Command for Monochromator CM110/CM112 from CVI Laser Corp."
subq_table = {
"position": 0,
"type": 1,
"grooves": 2,
"blaze": 3,
"grating": 4,
"speed": 5,
"size": 6,
"num_of_gratings": 13,
"units": 14,
"serial_num": 19,
}
state_limits = {
"position": {"type": "special"},
"type": {"type": "list", "list": (0, 1, 254)},
"grooves": {"type": "list", "list": (3600, 2400, 1800, 1200,
600, 300, 150, 75)},
"blaze": {"type": "limits", "limits": (0, 24000)},
"grating": {"type": "list", "list": (1, 2)}, #<=num_of_gratings
"speed": {"type": "special"},
"size": {"type": "special"},
"num_of_gratings": {"type": "list", "list": (1, 2)},
"units": {"type": "list", "list": (0, 1, 2)}, # centimicron, nm, Å
"serial_num": {"type": "None"},
}
def state_is_sane(self, state):
"Check that some of the state values are legal"
for subq, limits in self.state_limits.iteritems():
if limits["type"] in ("None", "special"):
continue
elif ((limits["type"] == "list" and
state[subq] not in limits["list"]) or
(limits["type"] == "limits" and not
(limits["limits"][0] <= state[subq] <= limits["limits"][1]))):
self.logger.warn("state[%s] = %s not in %s!" %
(subq, state[subq], limits["list"]))
return False
if not (0 < state["grating"] <= state["num_of_gratings"]):
self.logger.warn("Selected grating %s not in %s!" %
(state["grating"], [0, state["num_of_gratings"]]))
return False
return True
def echo(self):
"Verify communication"
self.send(chr(27))
result = self.receive(chr(27))
return result == chr(27)
def goto(self, wavelength):
"Set wavelength"
self.send(chr(16))
self.send(chr(wavelength>>8)) # high byte
self.send(chr(wavelength%256)) # low byte
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
return status
def query(self, subq):
"Read current state of monochromater"
assert (subq in self.subq_table or subq in self.subq_table.values()), \
"Wrong subquery!"
if subq in self.subq_table:
subq = self.subq_table[subq]
self.send(chr(56))
self.send(chr(subq))
high = ord(self.receive(None))
low = ord(self.receive(None))
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
return high * 256 + low
def query_all(self):
"Read full current state of monochromater, return it as dict"
result = {}
for subq in self.subq_table.keys():
result[subq] = self.query(subq)
self.log_state(result)
self.state_is_sane(result)
return result
def select(self, grating):
"Select grating 1 or 2"
if grating in ("1", "2"):
grating = int(grating)
assert grating in (1, 2), "Wrong grating number: %s." % grating
self.send(chr(26))
self.send(chr(grating))
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
def units(self, unit):
"Select units for commands goto, scan, size, calibrate"
unit_table = {"10nm": 0, "nm": 1, "Å": 2}
assert (unit in unit_table or unit in unit_table.values()), \
"Wrong units!"
if unit in unit_table:
unit = unit_table[unit]
self.send(chr(50))
self.send(chr(unit))
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
def readNOVRAM(self, address): # pylint: disable=C0103
"Read a byte from NOVRAM in monochromator"
assert (0 <= address <= 127), "Wrong NOVRAM address!"
self.send(chr(156))
self.send(chr(address))
result = self.receive(None)
status = self.receive(None)
self.log_status(status)
self.receive(chr(24))
return result
def readNOVRAM_all(self): # pylint: disable=C0103
"Read all 128 bytes from monochromator NOVRAM"
result = ""
for addr in xrange(128):
result += self.readNOVRAM(addr)
return result
def save_NOVRAM(self, fname=SAVEFILE): # pylint: disable=C0103
"Save the contents of memory in a binary file"
novram = self.readNOVRAM_all()
with open(fname, "wb") as fil:
fil.write(novram)
class CM110(CM110_Commands):
"Class with the state of a CM100 monochromator"
def __init__(self, stream=None, port=PORT):
CM110_Commands.__init__(self, stream, port)
self.state = self.query_all()
def get_state(self):
"Re-read the device state"
self.state = self.query_all()
if __name__ == '__main__':
CM = CM110_Commands()
CM.logger.info("sendBreak")
CM.port.sendBreak()
CM.logger.info("flushInput")
CM.port.flushInput()
CM.logger.info("echo")
CM.echo()
CM.logger.info("echo")
CM.echo()
CM.logger.info("echo")
CM.echo()
CM.logger.info("select 2")
CM.select(2)
CM.logger.info("select 1")
CM.select(1)
CM.logger.info("units 0")
CM.units(0)
CM.logger.info("units nm")
CM.units("nm")
CM.logger.info("units 2")
CM.units(2)
CM.logger.info("goto 800")
CM.goto(800)
CM.logger.info("goto 0")
CM.goto(0)
CM.logger.info("query_all")
CM.query_all()
CM.logger.info("select 2")
CM.select(2)
CM.logger.info("goto 800")
CM.goto(800)
CM.logger.info("query_all")
CM.query_all()
CM.logger.info("readNOVRAM_all")
CM.save_NOVRAM("NOVRAM")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"Test PyGTK"
import pygtk
pygtk.require('2.0')
import gtk
from CM110 import CM110
class StreamLike(object): # pylint: disable=R0903
"A stream-like class to show logs in a window"
def __init__(self, textview):
self.textview = textview
def write(self, message):
"Add a message into the widget buffer"
buff = self.textview.get_buffer()
buff.insert(buff.get_end_iter(), message)
self.textview.scroll_mark_onscreen(buff.get_insert())
## def flush(self):
## "Required by API"
## pass
class PyApp(gtk.Window): # pylint: disable=R0904,R0924
"Try to make a window"
def __init__(self):
gtk.Window.__init__(self)
self.set_title("CM110 Control")
self.cm110 = CM110()
self.vbox1 = gtk.VBox()
# Prepare First two lines of widgets
self.vbox1.hbox1 = self.setup_hbox1()
self.vbox1.scrolledwindow1 = self.setup_scrolledwindow1()
self.cm110.set_log(StreamLike(self.vbox1.scrolledwindow1.textview1))
self.vbox1.pack_start(self.vbox1.hbox1, expand=False, fill=False)
self.vbox1.pack_start(self.vbox1.scrolledwindow1, expand=True,
fill=True)
self.add(self.vbox1)
self.connect("destroy", gtk.main_quit)
self.show_all()
def setup_hbox1(self):
"Create hbox1 and its internals"
hbox1 = gtk.HBox()
hbox1.label1 = gtk.Label(" Wavelength:")
adjustment = gtk.Adjustment(self.cm110.state["position"], 0, 99000)
hbox1.spinbutton1 = gtk.SpinButton(adjustment, 0, 0)
hbox1.spinbutton1.set_numeric(True)
hbox1.spinbutton1.update()
adjustment.connect("value_changed", self.wavelength, hbox1.spinbutton1)
hbox1.combobox1 = gtk.combo_box_new_text()
for txt in ("10nm", "nm", "Å"):
hbox1.combobox1.append_text(txt)
hbox1.combobox1.set_active(self.cm110.state["units"])
hbox1.combobox1.connect("changed", self.units)
hbox1.button3 = gtk.Button("State")
hbox1.button3.connect("clicked", self.get_state)
hbox1.button4 = gtk.Button("Save NOVRAM")
hbox1.button4.connect("clicked", self.save_NOVRAM)
hbox1.label2 = gtk.Label("Grating:")
hbox1.combobox2 = gtk.combo_box_new_text()
hbox1.combobox2.append_text("1")
if self.cm110.state["num_of_gratings"] == 2:
hbox1.combobox2.append_text("2")
hbox1.combobox2.set_active(int(self.cm110.state["grating"])-1)
hbox1.combobox2.connect("changed", self.set_grating)
grating = "%d gr/mm, blaze %d nm." % (self.cm110.state["grooves"],
self.cm110.state["blaze"])
hbox1.label3 = gtk.Label(grating)
hbox1.button5 = gtk.Button("Close")
hbox1.button5.connect("clicked", gtk.main_quit)
hbox1.pack_start(hbox1.label2, expand=False, fill=False)
hbox1.pack_start(hbox1.combobox2, expand=False, fill=False)
hbox1.pack_start(hbox1.label3, expand=False, fill=False)
hbox1.pack_start(hbox1.label1, expand=False, fill=False)
hbox1.pack_start(hbox1.spinbutton1, expand=False, fill=False)
hbox1.pack_start(hbox1.combobox1, expand=False, fill=False)
hbox1.pack_start(hbox1.button3, expand=False, fill=False)
hbox1.pack_end(hbox1.button5, expand=False, fill=False)
hbox1.pack_end(hbox1.button4, expand=False, fill=False)
return hbox1
def setup_scrolledwindow1(self): # pylint: disable=R0201
"Create scrolled text window"
scrolledwindow1 = gtk.ScrolledWindow()
scrolledwindow1.textview1 = gtk.TextView()
scrolledwindow1.textview1.set_cursor_visible(False)
scrolledwindow1.textview1.set_editable(False)
scrolledwindow1.add(scrolledwindow1.textview1)
return scrolledwindow1
def get_state(self, _widget=None):
"Add some text to a buffer"
self.cm110.get_state()
self.vbox1.hbox1.spinbutton1.set_value(self.cm110.state["position"])
self.vbox1.hbox1.combobox1.set_active(self.cm110.state["units"])
grating = "%d gr/mm, blaze %d nm." % (self.cm110.state["grooves"],
self.cm110.state["blaze"])
self.vbox1.hbox1.label3.set_text(grating)
def units(self, widget):
"A call-back for units change"
self.cm110.units(widget.get_active_text())
self.vbox1.hbox1.spinbutton1.set_value(0) # It also resets wavelength
def wavelength(self, _widget, spin):
"A call-back for units change"
self.cm110.goto(spin.get_value_as_int())
def save_NOVRAM(self, _widget): # pylint: disable=C0103
"A call-back saving memory to a file"
self.cm110.save_NOVRAM()
def set_grating(self, widget):
"A call-back to select a grating"
self.cm110.select(widget.get_active_text())
self.get_state() # reflect the state change by re-reading the state
PYAPP = PyApp()
gtk.main()
| Python |
'''
Created on Aug 15, 2012
@author: Chung Leong
'''
from flaczki.abc.structures import *
from struct import Struct
class ABCParser(object):
def __init__(self):
self.u8 = Struct('<B')
self.u16 = Struct('<H')
self.f64 = Struct('d')
def parse(self, byte_codes):
self.byte_codes = byte_codes
self.byte_code_index = 0;
abc_file = ABCFile()
# AVM version info--should be 16.46
abc_file.major_version = self.readU16()
abc_file.minor_version = self.readU16()
# signed integer constants (zeroth item is default value)
int_count = self.readU32()
abc_file.int_table = [0] + [self.readS32() for _ in range(int_count)]
# unsigned integer constants
uint_count = self.readU32()
abc_file.uint_table = [0] + [self.readU32() for _ in range(uint_count)]
# double constants
double_count = self.readU32()
abc_file.double_table = [0.0] + [self.readD64() for _ in range(double_count)]
# string constants
string_count = self.readU32()
abc_file.string_table = [''] + [self.readString() for _ in range(string_count)]
# namespace constants
namespace_count = self.readU32()
default_namespace = ABCNamespace()
abc_file.namespace_table = [default_namespace] + [self.readNamespace() for _ in range(namespace_count)]
# namespace-set constants
namespace_set_count = self.readU32()
default_namespace_set = ABCNamespaceSet()
abc_file.namespace_set_table = [default_namespace_set] + [self.readNamespaceSet() for _ in range(namespace_set_count)]
# multiname (i.e. variable name) constants
multiname_count = self.readU32()
default_multiname = ABCMultiname()
abc_file.multiname_table = [default_multiname] + [self.readMultiname() for _ in range(multiname_count)]
# methods
method_count = self.readU32()
abc_file.method_table = [self.readMethod() for _ in range(method_count)]
# metadata
metadata_count = self.readU32()
abc_file.metadata_table = [self.readMetadata() for _ in range(metadata_count)]
# class instances
class_count = self.readU32()
abc_file.instance_table = [self.readInstance() for _ in range(class_count)]
abc_file.class_table = [self.readClass() for _ in range(class_count)]
# scripts
script_count = self.readU32()
abc_file.script_table = [self.readScript() for _ in range(script_count)]
# method bodies
method_body_count = self.readU32()
abc_file.method_body_table = [self.readMethodBody() for _ in range(method_body_count)]
self.input = None
return abc_file
def readNamespace(self):
namespace = ABCNamespace()
namespace.kind = self.readU8()
namespace.string_index = self.readU32()
return namespace
def readNamespaceSet(self):
namespace_set = ABCNamespaceSet()
namespace_count = self.readU32()
namespace_set.namespace_indices = [self.readU32() for _ in range(namespace_count)]
return namespace_set
def readMultiname(self):
multiname = ABCMultiname()
multiname.name_type = name_type = self.readU8()
if name_type in (0x07, 0x0D): # CONSTANT_QName, CONSTANT_QNameA
multiname.namespace_index = self.readU32()
multiname.string_index = self.readU32()
elif name_type in (0x0F, 0x10): # CONSTANT_RTQNamem, CONSTANT_RTQNameA
multiname.namespace_index = self.readU32()
elif name_type in (0x11, 0x12): # CONSTANT_RTQNameL, CONSTANT_RTQNameLA
pass
elif name_type in (0x09, 0x0E): # CONSTANT_Multiname, CONSTANT_MultinameA
multiname.string_index = self.readU32()
multiname.namespace_set_index = self.readU32()
elif name_type in (0x1B, 0x1C): # CONSTANT_MultinameL, CONSTANT_MultinameLA
multiname.namespace_set_index = self.readU32()
elif name_type == 0x1D: # CONSTANT_GENERIC
multiname.name_index = self.readU32()
type_count = self.readU32()
multiname.type_indices = [self.readU32() for _ in range(type_count)]
return multiname
def readMethod(self):
method = ABCMethod()
method.param_count = self.readU32()
method.return_type = self.readU32()
method.param_types = [self.readU32() for _ in range(method.param_count)]
method.name_index = self.readU32()
method.flags = self.readU8()
if method.flags & 0x08: # HAS_OPTIONAL
opt_param_count = self.readU32()
method.optional_params = [self.readMethodOptionalParameter() for _ in range(opt_param_count)]
if method.flags & 0x80: # HAS_PARAM_NAMES
method.paramName_indices = [self.readU32() for _ in range(method.param_count)]
return method
def readMethodOptionalParameter(self):
parameter = ABCMethodOptionalParameter()
parameter.index = self.readU32()
parameter.flags = self.readU8()
return parameter
def readMetadata(self):
metadata = ABCMetadata()
metadata.name_index = self.readU32()
pair_count = self.readU32()
indices = [self.readU32() for _ in range(pair_count * 2)]
metadata.key_indices = indices[0: :2]
metadata.value_indices = indices[1: :2]
return metadata
def readInstance(self):
instance = ABCInstance()
instance.name_index = self.readU32()
instance.super_name_index = self.readU32()
instance.flags = self.readU8()
if instance.flags & 0x08: # CONSTANT_ClassProtectedNs
instance.protectedNamespace_index = self.readU32()
interface_count = self.readU32()
instance.interface_indices = [self.readU32() for _ in range(interface_count)]
instance.constructor_index = self.readU32()
trait_count = self.readU32()
instance.traits = [self.readTrait() for _ in range(trait_count)]
return instance
def readClass(self):
class_object = ABCClass()
class_object.constructor_index = self.readU32()
trait_count = self.readU32()
class_object.traits = [self.readTrait() for _ in range(trait_count)]
return class_object
def readScript(self):
script = ABCScript()
script.initializer_index = self.readU32()
trait_count = self.readU32()
script.traits = [self.readTrait() for _ in range(trait_count)]
return script
def readMethodBody(self):
method_body = ABCMethodBody()
method_body.method_index = self.readU32()
method_body.max_stack = self.readU32()
method_body.local_count = self.readU32()
method_body.init_scope_depth = self.readU32()
method_body.max_scope_depth = self.readU32()
codeLength = self.readU32()
method_body.byte_codes = self.readBytes(codeLength)
exception_count = self.readU32()
method_body.exceptions = [self.readException for _ in range(exception_count)]
trait_count = self.readU32()
method_body.traits = [self.readTrait() for _ in range(trait_count)]
# link it with the method object so we can quickly find the body with a method index
# method = abc_file.method_table[method_body.method_index]
# method.body = method_body
return method_body
def readException(self):
exception = ABCException()
exception.from_offset = self.readU32()
exception.to_offset = self.readU32()
exception.target_offset = self.readU32()
exception.type_index = self.readU32()
exception.variable_index = self.readU32()
return exception
def readTrait(self):
trait = ABCTrait()
trait.name_index = self.readU32()
trait.flags = self.readU8()
trait.slotId = self.readU32()
trait_type = trait.flags & 0x0F
if trait_type in (0, 6): # Trait_Slot, Trait_Constant
data = ABCTraitSlot()
data.typeName_index = self.readU32()
data.value_index = self.readU32()
if data.value_index:
data.value_type = self.readU8()
trait.data = data
elif trait_type in (1, 2, 3): # Trait_Method, Trait_Getter, Trait_Setter
data = ABCTraitMethod()
data.method_index = self.readU32()
trait.data = data
elif trait_type == 4: # Trait_Class
data = ABCTraitClass()
data.class_index = self.readU32()
trait.data = data
elif trait_type == 5: # Trait_Function
data = ABCTraitFunction()
data.method_index = self.readU32()
trait.data = data
if trait.flags & 0x40: # ATTR_Metadata
metadata_count = self.readU32()
trait.metadata_indices = [self.readU32() for _ in range(metadata_count)]
return trait
def readU8(self):
data = self.readBytes(1)
if len(data) == 1:
result = self.ui8.unpack(data)
return result[0]
else:
return 0
def readU16(self):
data = self.readBytes(2)
if len(data) == 2:
result = self.u16.unpack(data)
return result[0]
else:
return 0
def readU32(self):
result = 0
shift = 0
while shift < 32:
u8 = self.readU8()
result |= (u8 & 0x7F) << shift
shift += 7
if not (u8 & 0x80):
break
return result
def readS32(self):
result = 0
shift = 0
while shift < 32:
u8 = self.readU8()
result |= (u8 & 0x7F) << shift
shift += 7
if not (u8 & 0x80):
break
if u8 & 0x40:
result |= -1 << shift;
return result
def readD64(self):
data = self.readBytes(8)
if len(data) == 8:
result = self.d64.unpack(data)
return result[0]
else:
return 0.0
def readBytes(self, count):
start = self.byte_code_index;
end = start + count;
self.byte_code_index = end;
return self.byte_codes[start:end]
| Python |
'''
Created on Aug 15, 2012
@author: Chung Leong
'''
class ABCFile(object):
major_version = None
minor_version = None
int_table = None
uint_table = None
double_table = None
string_table = None
namespace_table = None
namespace_set_table = None
multiname_table = None
method_table = None
metadata_table = None
instance_table = None
class_table = None
script_table = None
method_body_table = None
class ABCNamespace(object):
kind = None
string_index = None
class ABCNamespaceSet(object):
namespace_indices = None
class ABCMultiname(object):
name_type = None
string_index = None
namespace_index = None
namespace_set_index = None
name_index = None
type_indices = None
class ABCMethod(object):
param_count = None
return_type = None
param_types = None
name_index = None
flags = None
optional_params = None
param_name_indices = None
body = None
class ABCMethodOptionalParameter(object):
flags = None
index = None
class ABCMetadata(object):
name_index = None
key_indices = None
value_indices = None
class ABCInstance(object):
name_index = None
superName_index = None
flags = None
protectedNamespace_index = None
interface_indices = None
constructor_index = None
traits = None
class ABCClass(object):
constructor_index = None
traits = None
class ABCScript(object):
initializer_index = None
traits = None
class ABCMethodBody(object):
method_index = None
max_stack = None
local_count = None
init_scope_depth = None
max_scope_depth = None
byte_codes = None
exceptions = None
traits = None
class ABCTrait(object):
name_index = None
flags = None
data = None
slotId = None
metadata_indices = None
class ABCTraitSlot(object):
type_name_index = None
value_index = None
value_type = None
class ABCTraitClass(object):
class_index = None
class ABCTraitFunction(object):
method_index = None
class ABCTraitMethod(object):
method_index = None
class ABCException(object):
from_offset = None
to_offset = None
target_offset = None
type_index = None
variable_index = None
| Python |
'''
Created on Jul 21, 2012
@author: Chung Leong
'''
from zlib import decompressobj
from struct import Struct
from flaczki.swf.tags import *
class SWFFile(object):
'''
classdocs
'''
version = None
compressed = False
frame_size = None
tags = []
class SWFParser(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.ui8 = Struct('<B')
self.si16 = Struct('<h')
self.ui16 = Struct('<H')
self.si32 = Struct('<i')
self.ui32 = Struct('<I')
self.f32 = Struct('f')
self.f64 = Struct('d')
self.tag_class_and_handlers = {
74: (CSMTextSettings, self.readCSMTextSettingsTag),
78: (DefineScalingGrid, self.readDefineScalingGridTag),
87: (DefineBinaryData, self.readDefineBinaryDataTag),
6: (DefineBits, self.readDefineBitsTag),
21: (DefineBitsJPEG2, self.readDefineBitsJPEG2Tag),
35: (DefineBitsJPEG3, self.readDefineBitsJPEG3Tag),
90: (DefineBitsJPEG4, self.readDefineBitsJPEG4Tag),
20: (DefineBitsLossless, self.readDefineBitsLosslessTag),
36: (DefineBitsLossless2, self.readDefineBitsLossless2Tag),
7: (DefineButton, self.readDefineButtonTag),
34: (DefineButton2, self.readDefineButton2Tag),
23: (DefineButtonCxform, self.readDefineButtonCxformTag),
17: (DefineButtonSound, self.readDefineButtonSoundTag),
37: (DefineEditText, self.readDefineEditTextTag),
10: (DefineFont, self.readDefineFontTag),
48: (DefineFont2, self.readDefineFont2Tag),
75: (DefineFont3, self.readDefineFont3Tag),
91: (DefineFont4, self.readDefineFont4Tag),
73: (DefineFontAlignZones, self.readDefineFontAlignZonesTag),
13: (DefineFontInfo, self.readDefineFontInfoTag),
62: (DefineFontInfo2, self.readDefineFontInfo2Tag),
88: (DefineFontName, self.readDefineFontNameTag),
46: (DefineMorphShape, self.readDefineMorphShapeTag),
84: (DefineMorphShape2, self.readDefineMorphShape2Tag),
86: (DefineSceneAndFrameLabelData, self.readDefineSceneAndFrameLabelDataTag),
2: (DefineShape, self.readDefineShapeTag),
22: (DefineShape2, self.readDefineShape2Tag),
32: (DefineShape3, self.readDefineShape3Tag),
83: (DefineShape4, self.readDefineShape4Tag),
39: (DefineSprite, self.readDefineSpriteTag),
11: (DefineText, self.readDefineTextTag),
33: (DefineText2, self.readDefineText2Tag),
14: (DefineSound, self.readDefineSoundTag),
60: (DefineVideoStream, self.readDefineVideoStreamTag),
59: (DoInitAction, self.readDoInitActionTag),
82: (DoABC, self.readDoABCTag),
12: (DoAction, self.readDoActionTag),
58: (EnableDebugger, self.readEnableDebuggerTag),
64: (EnableDebugger2, self.readEnableDebugger2Tag),
0: (End, self.readEndTag),
56: (ExportAssets, self.readExportAssetsTag),
69: (FileAttributes, self.readFileAttributesTag),
43: (FrameLabel, self.readFrameLabelTag),
57: (ImportAssets, self.readImportAssetsTag),
71: (ImportAssets2, self.readImportAssets2Tag),
8: (JPEGTables, self.readJPEGTablesTag),
77: (Metadata, self.readMetadataTag),
24: (Protect, self.readProtectTag),
4: (PlaceObject, self.readPlaceObjectTag),
26: (PlaceObject2, self.readPlaceObject2Tag),
70: (PlaceObject3, self.readPlaceObject3Tag),
5: (RemoveObject, self.readRemoveObjectTag),
28: (RemoveObject2, self.readRemoveObject2Tag),
65: (ScriptLimits, self.readScriptLimitsTag),
9: (SetBackgroundColor, self.readSetBackgroundColorTag),
66: (SetTabIndex, self.readSetTabIndexTag),
1: (ShowFrame, self.readShowFrameTag),
15: (StartSound, self.readStartSoundTag),
89: (StartSound2, self.readStartSound2Tag),
18: (SoundStreamHead, self.readSoundStreamHeadTag),
45: (SoundStreamHead2, self.readSoundStreamHead2Tag),
19: (SoundStreamBlock, self.readSoundStreamBlockTag),
76: (SymbolClass, self.readSymbolClassTag),
61: (VideoFrame, self.readVideoFrameTag)
}
def parse(self, source):
swf_file = SWFFile()
self.source = source
self.byte_buffer = bytearray()
self.bytes_remaining = 8
self.bit_buffer = 0
self.bits_remaining = 0
self.highest_character_id = 0
self.decompressor = None
# signature
signature = self.readUI32()
swf_file.version = self.swf_version = (signature >> 24) & 0xFF
signature = signature & 0xFFFFFF
# should be SWF or SWC
if signature != 0x535746 and signature != 0x535743:
return False
# file length
file_length = self.readUI32()
self.bytes_remaining = file_length
if signature == 0x535743:
# start decompressing incoming data
swf_file.compressed = True
self.startDecompression()
swf_file.frame_size = self.readRect()
# frame rate and count
swf_file.frame_rate = self.readUI16()
swf_file.frame_count = self.readUI16()
while True:
tag = self.readTag()
swf_file.tags.append(tag)
if isinstance(tag, End):
break
swf_file.highest_character_id = self.highest_character_id
self.source = None
return swf_file
def readTag(self):
self.bytes_remaining = 6
tag_code_and_length = self.readUI16()
tag_code = (tag_code_and_length & 0xFFC0) >> 6
tag_length = tag_code_and_length & 0x003F
if tag_length == 0x003F:
# long format
tag_length = self.readUI32()
header_length = 6
else:
header_length = 2
self.bytes_remaining = tag_length
tag_class, handler = self.tag_class_and_handlers[tag_code]
if handler:
tag = handler()
if self.bytes_remaining > 0:
extra = self.readBytes(self.bytes_remaining)
print(str(len(extra)) + ' bytes left after ' + str(tag))
if tag is Character:
if tag.character_id > self.highest_character_id:
self.highest_character_id = tag.character_id
else:
tag = Generic()
tag.data = self.readBytes(tag_length)
tag.code = tag_code
tag.header_length = header_length
tag.length = tag_length
if tag_class is Character:
character_id = self.ui16.unpack_from(tag.data)
if character_id > self.highest_character_id:
self.highest_character_id = character_id
return tag
def readCSMTextSettingsTag(self):
tag = CSMTextSettings()
tag.character_id = self.readUI16()
tag.renderer = self.readUB(2)
tag.gridFit = self.readUB(3)
tag.reserved1 = self.readUB(3)
tag.thickness = self.readF32()
tag.sharpness = self.readF32()
tag.reserved2 = self.readUI8()
return tag
def readDefineBinaryDataTag(self):
tag = DefineBinaryData()
tag.character_id = self.readUI16()
tag.reserved = self.readUI32()
tag.data = self.readBytes(self.bytes_remaining)
return tag
def readDefineBitsTag(self):
tag = DefineBits()
tag.character_id = self.readUI16()
tag.image_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineBitsLosslessTag(self):
tag = DefineBitsLossless()
tag.character_id = self.readUI16()
tag.format = self.readUI8()
tag.width = self.readUI16()
tag.height = self.readUI16()
if tag.format == 3:
tag.color_table_size = self.readUI8()
tag.image_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineBitsLossless2Tag(self):
tag = DefineBitsLossless2()
tag.character_id = self.readUI16()
tag.format = self.readUI8()
tag.width = self.readUI16()
tag.height = self.readUI16()
if tag.format == 3:
tag.colorTableSize = self.readUI8()
tag.image_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineBitsJPEG2Tag(self):
tag = DefineBitsJPEG2()
tag.character_id = self.readUI16()
tag.image_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineBitsJPEG3Tag(self):
tag = DefineBitsJPEG3()
tag.character_id = self.readUI16()
alpha_offset = self.readUI32()
tag.image_data = self.readBytes(alpha_offset)
tag.alpha_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineBitsJPEG4Tag(self):
tag = DefineBitsJPEG4()
tag.character_id = self.readUI16()
alpha_offset = self.readUI32()
tag.deblockingParam = self.readUI16()
tag.image_data = self.readBytes(alpha_offset)
tag.alpha_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineButtonTag(self):
tag = DefineButton()
tag.character_id = self.readUI16()
tag.characters = self.readButtonRecords(1)
tag.actions = self.readBytes(self.bytes_remaining)
return tag
def readDefineButton2Tag(self):
tag = DefineButton2()
tag.character_id = self.readUI16()
tag.flags = self.readUI8()
_action_offset = self.readUI16()
tag.characters = self.readButtonRecords(2)
tag.actions = self.readBytes(self.bytes_remaining)
return tag
def readDefineButtonCxformTag(self):
tag = DefineButtonCxform()
tag.character_id = self.readUI16()
tag.color_transform = self.readColorTransform()
return tag
def readDefineButtonSoundTag(self):
tag = DefineButtonSound()
tag.character_id = self.readUI16()
tag.over_up_to_idle_id = self.readUI16()
if tag.over_up_to_idle_id != 0:
tag.over_up_to_idle_info = self.readSoundInfo()
tag.idle_to_over_up_id = self.readUI16()
if tag.idle_to_over_up_id != 0:
tag.idle_to_over_up_info = self.readSoundInfo()
tag.over_up_to_over_down_id = self.readUI16()
if tag.over_up_to_over_down_id != 0:
tag.over_up_to_over_down_info = self.readSoundInfo()
tag.over_down_to_over_up_id = self.readUI16()
if tag.over_down_to_over_up_id != 0:
tag.over_down_to_over_up_info = self.readSoundInfo()
return tag
def readDefineEditTextTag(self):
tag = DefineEditText()
tag.character_id = self.readUI16()
tag.bounds = self.readRect()
tag.flags = self.readUI16()
if tag.flags & 0x0001: # HasFont
tag.font_id = self.readUI16()
tag.font_height = self.readUI16()
if tag.flags & 0x8000: # HasFontClass
tag.font_class = self.readString()
if tag.flags & 0x0004: # HasTextColor
tag.text_color = self.readRGBA()
if tag.flags & 0x0002: # HasMaxLength
tag.maxLength = self.readUI16()
if tag.flags & 0x2000: # HasLayout
tag.align = self.readUI8()
tag.leftMargin = self.readUI16()
tag.rightMargin = self.readUI16()
tag.indent = self.readUI16()
tag.leading = self.readUI16()
tag.variable_name = self.readString()
if tag.flags & 0x0080: # HasText
tag.initialText = self.readString()
return tag
def readDefineFontTag(self):
tag = DefineFont()
tag.character_id = self.readUI16()
first_offset = self.readUI16()
glyph_count = first_offset >> 1
_offset_table = [first_offset] + [self.readUI16() for _ in range(1, glyph_count)]
tag.glyph_table = [self.readShape() for _ in range(glyph_count)]
return tag
def readDefineFont2Tag(self):
tag = DefineFont2()
tag.character_id = self.readUI16()
tag.flags = self.readUI8()
tag.language_code = self.readUI8()
name_length = self.readUI8()
tag.name = self.readBytes(name_length)
glyph_count = self.readUI16()
bytes_remaining_before = self.bytes_remaining
glyph_range = range(0, glyph_count)
if tag.flags & 0x08: # WideOffsets
_offset_table = [self.readUI32() for _ in glyph_range]
_code_table_offset = self.readUI32()
else:
_offset_table = [self.readUI16() for _ in glyph_range]
_code_table_offset = self.readUI16()
tag.glyph_table = [self.readShape() for _ in glyph_range]
_offset = bytes_remaining_before - self.bytes_remaining
if tag.flags & 0x04: # WideCodes
tag.code_table = [self.readUI16() for _ in glyph_range]
else:
tag.code_table = [self.readUI8() for _ in glyph_range]
if tag.flags & 0x80 or self.bytes_remaining > 0: # HasLayout
tag.ascent = self.readSI16()
tag.descent = self.readSI16()
tag.leading = self.readSI16()
tag.advance_table = [self.readUI16() for _ in glyph_range]
tag.bound_table = [self.readRect() for _ in glyph_range]
if tag.flags & 0x04: # WideCodes
tag.kerning_table = self.readWideKerningRecords()
else:
tag.kerning_table = self.readKerningRecords()
return tag
def readDefineFont3Tag(self):
tag = DefineFont3()
tag2 = self.readDefineFont2Tag()
tag.__dict__ = tag2.__dict__
return tag
def readDefineFont4Tag(self):
tag = DefineFont4()
tag.character_id = self.readUI16()
tag.flags = self.readUI8()
tag.name = self.readString()
tag.cff_data = self.readBytes(self.bytes_remaining)
return tag
def readDefineFontAlignZonesTag(self):
tag = DefineFontAlignZones()
tag.character_id = self.readUI16()
tag.table_hint = self.readUB(2)
tag.zone_table = self.readZoneRecords()
return tag
def readDefineFontInfoTag(self):
tag = DefineFontInfo()
tag.character_id = self.readUI16()
nameLength = self.readUI8()
tag.name = self.readBytes(nameLength)
tag.flags = self.readUI8()
if tag.flags & 0x01: # WideCodes
while self.bytes_remaining > 0:
tag.code_table.append(self.readUI16())
else:
while self.bytes_remaining > 0:
tag.code_table.append(self.readU8())
return tag
def readDefineFontInfo2Tag(self):
tag = DefineFontInfo2()
tag.character_id = self.readUI16()
nameLength = self.readUI8()
tag.name = self.readBytes(nameLength)
tag.flags = self.readUI8()
tag.languageCode = self.readUI8()
tag.code_table = []
if tag.flags & 0x01: # WideCodes
while self.bytes_remaining > 0:
tag.code_table.append(self.readUI16())
else:
while self.bytes_remaining > 0:
tag.code_table.append(self.readU8())
return tag
def readDefineFontNameTag(self):
tag = DefineFontName()
tag.character_id = self.readUI16()
tag.name = self.readString()
tag.copyright = self.readString()
return tag
def readDefineMorphShapeTag(self):
tag = DefineMorphShape()
tag.character_id = self.readUI16()
tag.start_bounds = self.readRect()
tag.end_bounds = self.readRect()
tag.morph_shape = self.readMorphShapeWithStyle(3) # use structures of DefineShape3
return tag
def readDefineMorphShape2Tag(self):
tag = DefineMorphShape2()
tag.character_id = self.readUI16()
tag.start_bounds = self.readRect()
tag.end_bounds = self.readRect()
tag.start_edge_bounds = self.readRect()
tag.end_edge_bounds = self.readRect()
tag.flags = self.readUI8()
tag.morph_shape = self.readMorphShapeWithStyle(4) # use structures of DefineShape4
return tag
def readDefineScalingGridTag(self):
tag = DefineScalingGrid()
tag.character_id = self.readUI16()
tag.splitter = self.readRect()
return tag
def readDefineSceneAndFrameLabelDataTag(self):
tag = DefineSceneAndFrameLabelData()
tag.scene_names = self.readEncUI32StringTable()
tag.frame_labels = self.readEncUI32StringTable()
return tag
def readDefineShapeTag(self):
tag = DefineShape()
tag.character_id = self.readUI16()
tag.shape_bounds = self.readRect()
tag.shape = self.readShapeWithStyle(1)
return tag
def readDefineShape2Tag(self):
tag = DefineShape2()
tag.character_id = self.readUI16()
tag.shape_bounds = self.readRect()
tag.shape = self.readShapeWithStyle(2)
return tag
def readDefineShape3Tag(self):
tag = DefineShape3()
tag.character_id = self.readUI16()
tag.shape_bounds = self.readRect()
tag.shape = self.readShapeWithStyle(3)
return tag
def readDefineShape4Tag(self):
tag = DefineShape4()
tag.character_id = self.readUI16()
tag.shape_bounds = self.readRect()
tag.edge_bounds = self.readRect()
tag.flags = self.readUI8()
tag.shape = self.readShapeWithStyle(4)
return tag
def readDefineSoundTag(self):
tag = DefineSound()
tag.format = self.readUB(4)
tag.sampleRate = self.readUB(2)
tag.sampleSize = self.readUB(1)
tag.type = self.readUB(1)
tag.sample_count = self.readUI32()
tag.data = self.readBytes(self.bytes_remaining)
return tag
def readDefineSpriteTag(self):
tag = DefineSprite()
tag.character_id = self.readUI16()
tag.frame_count = self.readUI16()
tag.tags = []
while True:
child = self.readTag()
tag.tags.append(child)
if isinstance(child, End):
break
return tag
def readDefineTextTag(self):
tag = DefineText()
tag.character_id = self.readUI16()
tag.bounds = self.readRect()
tag.matrix = self.readMatrix()
tag.glyph_bits = self.readUI8()
tag.advance_bits = self.readUI8()
tag.text_records = self.readTextRecords(tag.glyph_bits, tag.advance_bits, 1)
return tag
def readDefineText2Tag(self):
tag = DefineText2()
tag.character_id = self.readUI16()
tag.bounds = self.readRect()
tag.matrix = self.readMatrix()
tag.glyph_bits = self.readUI8()
tag.advance_bits = self.readUI8()
tag.text_records = self.readTextRecords(tag.glyph_bits, tag.advance_bits, 2)
return tag
def readDefineVideoStreamTag(self):
tag = DefineVideoStream()
tag.character_id = self.readUI16()
tag.frame_count = self.readUI16()
tag.width = self.readUI16()
tag.height = self.readUI16()
tag.flags = self.readUI8()
tag.codecId = self.readUI8()
return tag
def readDoABCTag(self):
tag = DoABC()
tag.flags = self.readUI32()
tag.byte_code_name = self.readString()
tag.byte_codes = self.readBytes(self.bytes_remaining)
return tag
def readDoActionTag(self):
tag = DoAction()
tag.actions = self.readBytes()
return tag
def readDoInitActionTag(self):
tag = DoInitAction()
tag.character_id = self.readUI16()
tag.actions = self.readBytes()
return tag
def readEndTag(self):
tag = End()
return tag
def readEnableDebuggerTag(self):
tag = EnableDebugger()
tag.password = self.readString()
return tag
def readEnableDebugger2Tag(self):
tag = EnableDebugger2()
tag.reserved = self.readUI16()
tag.password = self.readString()
return tag
def readExportAssetsTag(self):
tag = ExportAssets()
tag.names = self.readStringTable()
return tag
def readFileAttributesTag(self):
tag = FileAttributes()
tag.flags = self.readUI32()
return tag
def readFrameLabelTag(self):
tag = FrameLabel()
tag.name = self.readString()
if self.bytes_remaining > 0:
tag.anchor = tag.readString()
return tag
def readImportAssetsTag(self):
tag = ImportAssets()
tag.url = self.readString()
tag.names = self.readStringTable()
return tag
def readImportAssets2Tag(self):
tag = ImportAssets2()
tag.url = self.readString()
tag.reserved1 = self.readUI8()
tag.reserved2 = self.readUI8()
tag.names = self.readStringTable()
return tag
def readJPEGTablesTag(self):
tag = JPEGTables()
tag.jpeg_data = self.readBytes(self.bytes_remaining)
return tag
def readMetadataTag(self):
tag = Metadata()
tag.metadata = self.readString()
return tag
def readPlaceObjectTag(self):
tag = PlaceObject()
tag.character_id = self.readUI16()
tag.depth = self.readUI16()
tag.matrix = self.readMatrix()
if self.bytes_remaining > 0:
tag.color_transform = self.readColorTransform()
return tag
def readPlaceObject2Tag(self):
tag = PlaceObject2()
tag.flags = self.readUI8()
tag.depth = self.readUI16()
if tag.flags & 0x02: # HasCharacter
tag.character_id = self.readUI16()
if tag.flags & 0x04: # HasMatrix
tag.matrix = self.readMatrix()
if tag.flags & 0x08: # HasColorTransform
tag.color_transform = self.readColorTransformAlpha()
if tag.flags & 0x10: # HasRatio
tag.ratio = self.readUI16()
if tag.flags & 0x20: # HasName
tag.name = self.readString()
if tag.flags & 0x40: # HasClipDepth
tag.clipDepth = self.readUI16()
if tag.flags & 0x80: # HasClipActions
_reserved = self.readUI16()
tag.allEventFlags = self.readUI32() if self.swf_version >= 6 else self.readUI16()
tag.clip_actions = self.readClipActions()
return tag
def readPlaceObject3Tag(self):
tag = PlaceObject3()
tag.flags = self.readUI16()
tag.depth = self.readUI16()
if tag.flags & 0x0800: # HasClassName
tag.class_name = self.readString()
if tag.flags & 0x0002: # HasCharacter
tag.character_id = self.readUI16()
if tag.flags & 0x0004: # HasMatrix
tag.matrix = self.readMatrix()
if tag.flags & 0x0008: # HasColorTransform
tag.color_transform = self.readColorTransformAlpha()
if tag.flags & 0x0010: # HasRatio
tag.ratio = self.readUI16()
if tag.flags & 0x0020: # HasName
tag.name = self.readString()
if tag.flags & 0x0040: # HasClipDepth
tag.clipDepth = self.readUI16()
if tag.flags & 0x0100: # HasFilterList
tag.filters = self.readFilters()
if tag.flags & 0x0200: # HasBlendMode
tag.blend_mode = self.readUI8()
if tag.flags & 0x0400: # HasCacheAsBitmap
tag.bitmapCache = self.readUI8()
if tag.flags & 0x0080: # HasClipActions
tag.clip_actions = self.readClipActions()
if tag.flags & 0x2000: # HasVisibility
tag.visibility = self.readUI8()
if tag.flags & 0x4000: # HasBackgroundColor
tag.bitmap_cache_background_color = self.readRGBA()
if tag.flags & 0x0080: # HasClipActions
_reserved = self.readUI16()
tag.allEventFlags = self.readUI32() if self.swf_version >= 6 else self.readUI16()
tag.clip_actions = self.readClipActions()
return tag
def readProtectTag(self):
tag = Protect()
tag.password = self.readString()
return tag
def readRemoveObjectTag(self):
tag = RemoveObject()
tag.character_id = self.readUI16()
tag.depth = self.readUI16()
return tag
def readRemoveObject2Tag(self):
tag = RemoveObject2()
tag.depth = self.readUI16()
return tag
def readScriptLimitsTag(self):
tag = ScriptLimits()
tag.max_recursion_depth = self.readUI16()
tag.script_timeout_seconds = self.readUI16()
return tag
def readSetBackgroundColorTag(self):
tag = SetBackgroundColor()
tag.color = self.readRGB()
return tag
def readSetTabIndexTag(self):
tag = SetTabIndex()
tag.depth = self.readUI16()
tag.tab_index = self.readUI16()
return tag
def readShowFrameTag(self):
tag = ShowFrame()
return tag
def readSoundStreamBlockTag(self):
tag = SoundStreamBlock()
tag.data = self.readBytes(self.bytes_remaining)
return tag
def readSoundStreamHeadTag(self):
tag = SoundStreamHead()
tag.flags = self.readUI16()
tag.sample_count = self.readUI16()
if tag.flags & 0xF000 == 0x2000:
tag.latency_seek = self.readS16()
return tag
def readSoundStreamHead2Tag(self):
tag = SoundStreamHead2()
_reserved = self.readUB(4)
tag.playback_sample_rate = self.readUB(2)
tag.playback_sample_size = self.readUB(1)
tag.playback_type = self.readUB(1)
tag.format = self.readUB(4)
tag.sample_rate = self.readUB(2)
tag.sample_size = self.readUB(1)
tag.type = self.readUB(1)
tag.sample_count = self.readUI16()
if tag.format == 2:
tag.latency_seek = self.readS16()
return tag
def readStartSoundTag(self):
tag = StartSound()
tag.character_id = self.readUI16()
tag.info = self.readSoundInfo()
return tag
def readStartSound2Tag(self):
tag = StartSound2()
tag.class_name = self.readString()
tag.info = self.readSoundInfo()
return tag
def readSymbolClassTag(self):
tag = SymbolClass()
tag.names = self.readStringTable()
return tag
def readVideoFrameTag(self):
tag = VideoFrame()
tag.stream_id = self.readUI16()
tag.frame_number = self.readUI16()
tag.data = self.readBytes(self.bytes_remaining)
return tag
def readZoneRecords(self):
records = []
while self.bytes_remaining > 0:
record = ZoneRecord()
_num_zone_data = self.readUI8() # always 1
record.zone_data1 = self.readUI16()
record.zone_data2 = self.readUI16()
record.flags = self.readUI8()
record.alignment_coordinate = self.readUI16()
record.range = self.readUI16()
records.append(record)
return records
def readKerningRecords(self):
kerns = []
count = self.readUI16()
for _ in range(count):
kern = KerningRecord()
kern.code1 = self.readUI8()
kern.code2 = self.readUI8()
kern.adjustment = self.readUI16()
kerns.append(kern)
return kerns
def readWideKerningRecords(self):
kerns = []
count = self.readUI16()
for _ in range(count):
kern = KerningRecord()
kern.code1 = self.readUI16()
kern.code2 = self.readUI16()
kern.adjustment = self.readUI16()
kerns.append(kern)
return kerns
def readClipActions(self):
clip_actions = []
while True:
eventFlags = self.readUI32() if self.swf_version >= 6 else self.readUI16()
if eventFlags == 0:
break
else:
clip_action = ClipAction()
clip_action.eventFlags = eventFlags
actionLength = self.readUI32()
if clip_action.eventFlags & 0x00020000: # KeyPress
clip_action.keyCode = self.readUI8()
clip_action.actions = self.readBytes(actionLength)
clip_actions.append(clip_action)
return clip_actions
def readFilters(self):
filters = []
count = self.readUI8()
for _ in range(count):
filter_id = self.readUI8()
if filter_id == 0:
drop_shadow = DropShadowFilter()
drop_shadow.shadowColor = self.readRGBA()
drop_shadow.blur_x = self.readSI32()
drop_shadow.blur_y = self.readSI32()
drop_shadow.angle = self.readSI32()
drop_shadow.distance = self.readSI32()
drop_shadow.strength = self.readSI16()
drop_shadow.flags = self.readUB(3)
drop_shadow.passes = self.readUB(5)
filters.append(drop_shadow)
elif filter_id == 1:
blur = BlurFilter()
blur.blur_x = self.readSI32()
blur.blur_y = self.readSI32()
blur.passes = self.readUB(5)
filters.append(blur)
elif filter_id == 2:
glow = GlowFilter()
glow.color = self.readRGBA()
glow.blur_x = self.readSI32()
glow.blur_y = self.readSI32()
glow.strength = self.readSI16()
glow.flags = self.readUB(3)
glow.passes = self.readUB(5)
filters.append(glow)
elif filter_id == 3:
bevel = BevelFilter()
# the spec incorrectly states that shadowColor comes first
bevel.highlight_color = self.readRGBA()
bevel.shadow_color = self.readRGBA()
bevel.blur_x = self.readSI32()
bevel.blur_y = self.readSI32()
bevel.angle = self.readSI32()
bevel.distance = self.readSI32()
bevel.strength = self.readSI16()
bevel.flags = self.readUB(4)
bevel.passes = self.readUB(4)
filters.append(bevel)
elif filter_id == 4:
gradient_glow = GradientGlowFilter()
color_count = self.readUI8()
gradient_glow.colors = [self.readRGBA() for _ in range(color_count)]
gradient_glow.ratios = [self.readUI8() for _ in range(color_count)]
gradient_glow.blur_x = self.readSI32()
gradient_glow.blur_y = self.readSI32()
gradient_glow.angle = self.readSI32()
gradient_glow.distance = self.readSI32()
gradient_glow.strength = self.readSI16()
gradient_glow.flags = self.readUB(4)
gradient_glow.passes = self.readUB(4)
filters.append(gradient_glow)
elif filter_id == 5:
convolution = ConvolutionFilter()
convolution.matrix_x = self.readUI8()
convolution.matrix_y = self.readUI8()
convolution.divisor = self.readFloat()
convolution.bias = self.readFloat()
convolution.matrix = [self.readFloat() for _ in range(convolution.matrix_x * convolution.matrix_y)]
convolution.default_color = self.readRGBA()
convolution.flags = self.readUI8()
filters.append(convolution)
elif filter_id == 6:
color_matrix = ColorMatrixFilter()
color_matrix.matrix = [self.readFloat() for _ in range(20)]
filters.append(color_matrix)
elif filter_id == 7:
gradient_bevel = GradientBevelFilter()
color_count = self.readUI8()
gradient_bevel.colors = [self.readRGBA() for _ in range(color_count)]
gradient_bevel.ratios = [self.readUI8() for _ in range(color_count)]
gradient_bevel.blur_x = self.readSI32()
gradient_bevel.blur_y = self.readSI32()
gradient_bevel.angle = self.readSI32()
gradient_bevel.distance = self.readSI32()
gradient_bevel.strength = self.readSI16()
gradient_bevel.flags = self.readUB(4)
gradient_bevel.passes = self.readUB(4)
filters.append(gradient_bevel)
return filters
def readTextRecords(self, glyph_bits, advance_bits, version):
records = []
while True:
flags = self.readUI8()
if flags == 0:
break
else:
record = TextRecord()
record.flags = flags
if record.flags & 0x08: # HasFont
record.font_id = self.readUI16()
if record.flags & 0x04: # HasColor
record.textColor = self.readRGBA() if version >= 2 else self.readRGB()
if record.flags & 0x02: # HasXOffset
record.x_offset = self.readSI16()
if record.flags & 0x01: # HasYOffset
record.y_offset = self.readSI16()
if record.flags & 0x08: # HasFont
record.text_height = self.readUI16()
record.glyphs = self.readGlyphEntries(glyph_bits, advance_bits)
records.append(record)
return records
def readGlyphEntries(self, glyph_bits, advance_bits):
glyphs = []
count = self.readUI8()
for _ in range(count):
glyph = GlyphEntry()
glyph.index = self.readUB(glyph_bits)
glyph.advance = self.readUB(advance_bits)
glyphs.append(glyph)
return glyphs
def readSoundInfo(self):
info = SoundInfo()
info.flags = self.readUI8()
if info.flags & 0x01: # HasInPoint
info.in_point = self.readUI32()
if info.flags & 0x02: # HasOutPoint
info.out_point = self.readUI32()
if info.flags & 0x04: # HasLoops
info.loop_count = self.readUI32()
if info.flags & 0x08: # HasEnvelope
info.envelopes = self.readSoundEnvelopes()
return info
def readSoundEnvelopes(self):
envelopes = []
count = self.readUI8()
for _ in range(count):
envelope = SoundEnvelope()
envelope.position_44 = self.readUI32()
envelope.left_level = self.readUI16()
envelope.right_level = self.readUI16()
envelopes.append(envelope)
return envelopes
def readButtonRecords(self, version):
records = []
while True:
flags = self.readUI8()
if flags == 0:
break
else:
record = ButtonRecord()
record.flags = flags
record.character_id = self.readUI16()
record.place_depth = self.readUI16()
record.matrix = self.readMatrix()
if version == 2:
record.color_transform = self.readColorTransformAlpha()
if version == 2 and record.flags & 0x10: # HasFilterList
record.filters = self.readFilters()
if version == 2 and record.flags & 0x20: # HasBlendMode
record.blend_mode = self.readUI8()
records.append(record)
return records
def readShape(self):
shape = Shape()
shape.num_fill_bits = self.readUB(4)
shape.num_line_bits = self.readUB(4)
shape.edges = self.readShapeRecords(shape.num_fill_bits, shape.num_line_bits, 1)
return shape
def readShapeWithStyle(self, version):
shape = ShapeWithStyle()
shape.fill_styles = self.readFillStyles(version)
shape.line_styles = self.readLineStyles(version)
shape.num_fill_bits = self.readUB(4)
shape.num_line_bits = self.readUB(4)
shape.edges = self.readShapeRecords(shape.num_fill_bits, shape.num_line_bits, version)
return shape
def readMorphShapeWithStyle(self, version):
shape = MorphShapeWithStyle()
_offset = self.readUI32()
shape.fill_styles = self.readMorphFillStyles()
shape.line_styles = self.readMorphLineStyles(version)
shape.start_num_fill_bits = self.readUB(4)
shape.start_num_line_bits = self.readUB(4)
shape.startEdges = self.readShapeRecords(shape.start_num_fill_bits, shape.start_num_line_bits, version)
shape.end_num_fill_bits = self.readUB(4)
shape.end_num_line_bits = self.readUB(4)
shape.endEdges = self.readShapeRecords(shape.end_num_fill_bits, shape.end_num_line_bits, version)
return shape
def readShapeRecords(self, num_fill_bits, num_line_bits, version):
records = []
while self.bytes_remaining > 0:
if self.readUB(1):
# edge
if self.readUB(1):
# straight
line = StraightEdge()
line.num_bits = self.readUB(4) + 2
if self.readUB(1):
# general line
line.delta_x = self.readSB(line.num_bits)
line.delta_y = self.readSB(line.num_bits)
else:
if self.readUB(1):
# vertical
line.delta_x = 0
line.delta_y = self.readSB(line.num_bits)
else:
# horizontal
line.delta_x = self.readSB(line.num_bits)
line.delta_y = 0
records.append(line)
else:
# curve
curve = QuadraticCurve()
curve.num_bits = self.readUB(4) + 2
curve.control_delta_x = self.readSB(curve.num_bits)
curve.control_delta_y = self.readSB(curve.num_bits)
curve.anchor_delta_x = self.readSB(curve.num_bits)
curve.anchor_delta_y = self.readSB(curve.num_bits)
records.append(curve)
else:
flags = self.readUB(5)
if flags == 0:
break
else:
# style change
change = StyleChange()
if flags & 0x01: # HasMove
change.num_move_bits = self.readSB(5)
change.move_delta_x = self.readSB(change.num_move_bits)
change.move_delta_y = self.readSB(change.num_move_bits)
if flags & 0x02: # HasFillStyle0
change.fill_style0 = self.readUB(num_fill_bits)
if flags & 0x04: # HasFillStyle1
change.fill_style1 = self.readUB(num_fill_bits)
if flags & 0x08: # HasLineStyle
change.line_style = self.readUB(num_line_bits)
if flags & 0x10: # HasNewStyles
change.new_fill_styles = self.readFillStyles(version)
change.new_line_styles = self.readLineStyles(version)
change.num_fill_bits = num_fill_bits = self.readUB(4)
change.num_line_bits = num_line_bits = self.readUB(4)
records.append(change)
self.alignToByte()
return records
def readFillStyles(self, version):
count = self.readUI8()
if count == 0xFF and version > 1:
count = self.readUI16()
return [self.readFillStyle(version) for _ in range(count)]
def readFillStyle(self, version):
style = FillStyle()
style.type = self.readUI8()
if style.type == 0x00:
style.color = self.readRGBA() if version >= 3 else self.readRGB()
elif style.type in (0x10, 0x12, 0x13):
style.gradient_matrix = self.readMatrix()
if style.type == 0x13:
style.gradient = self.readFocalGradient(version)
else:
style.gradient = self.readGradient(version)
elif style.type in (0x40, 0x41, 0x42, 0x43):
style.bitmap_id = self.readUI16()
style.bitmap_matrix = self.readMatrix()
return style
def readMorphFillStyles(self):
count = self.readUI8()
if count == 0xFF:
count = self.readUI16()
styles = [self.readMorphFillStyle() for _ in range(count)]
return styles
def readMorphFillStyle(self):
style = MorphFillStyle()
style.type = self.readUI8()
if style.type == 0x00:
style.start_color = self.readRGBA()
style.end_color = self.readRGBA()
elif style.type in (0x10, 0x12):
style.start_gradient_matrix = self.readMatrix()
style.end_gradient_matrix = self.readMatrix()
style.gradient = self.readMorphGradient()
elif style.type in (0x40, 0x41, 0x42, 0x43):
style.bitmapId = self.readUI16()
style.start_bitmap_matrix = self.readMatrix()
style.end_bitmap_matrix = self.readMatrix()
return style
def readLineStyles(self, version):
count = self.readUI8()
if count == 0xFF and version > 1:
count = self.readUI16()
if version >= 4:
return [self.readLineStyle2(version) for _ in range(count)]
else:
return [self.readLineStyle(version) for _ in range(count)]
def readLineStyle2(self, version):
style = LineStyle2()
style.width = self.readUI16()
style.start_cap_style = self.readUB(2)
style.join_style = self.readUB(2)
style.flags = self.readUB(10)
style.end_cap_style = self.readUB(2)
if style.join_style == 2: # JoinStyleMiter
style.miterLimitFactor = self.readUI16()
if style.flags & 0x0200: # HasFill
style.fill_style = self.readFillStyle(version)
else:
style.color = self.readRGBA()
return style
def readLineStyle(self, version):
style = LineStyle()
style.width = self.readUI16()
style.color = self.readRGBA() if version >= 3 else self.readRGB()
return style
def readMorphLineStyles(self, version):
count = self.readUI8()
if count == 0xFF:
count = self.readUI16()
if version >= 4:
return [self.readMorphLineStyle2(version) for _ in range(count)]
else:
return [self.readMorphLineStyle(version) for _ in range(count)]
def readMorphLineStyle2(self):
style = LineStyle2()
style.start_width = self.readUI16()
style.end_width = self.readUI16()
style.start_cap_style = self.readUB(2)
style.join_style = self.readUB(2)
style.flags = self.readUB(10)
style.end_cap_style = self.readUB(2)
if style.join_style == 2: # JoinStyleMiter
style.miterLimitFactor = self.readUI16()
if style.flags & 0x0200: # HasFill
style.fill_style = self.readMorphFillStyle()
else:
style.start_color = self.readRGBA()
style.end_color = self.readRGBA()
return style
def readMorphLineStyle(self):
style = MorphLineStyle()
style.start_width = self.readUI16()
style.end_width = self.readUI16()
style.start_color = self.readRGBA()
style.end_color = self.readRGBA()
return style
def readGradient(self, version):
gradient = Gradient()
gradient.spread_mode = self.readUB(2)
gradient.interpolation_mode = self.readUB(2)
gradient.control_points = self.readGradientControlPoints(version)
return gradient
def readFocalGradient(self, version):
gradient = FocalGradient()
gradient.spread_mode = self.readUB(2)
gradient.interpolation_mode = self.readUB(2)
gradient.control_points = self.readGradientControlPoints(version)
gradient.focal_point = self.readSI16()
return gradient
def readGradientControlPoints(self, version):
control_points = []
count = self.readUB(4)
for _ in range(count):
control_point = GradientControlPoint()
control_point.ratio = self.readUI8()
control_point.color = self.readRGBA() if version >= 3 else self.readRGB()
control_points.append(control_point)
return control_points
def readMorphGradient(self):
gradient = MorphGradient()
gradient.records = []
count = self.readUI8()
for _ in range(count):
record = MorphGradientRecord()
record.start_ratio = self.readUI8()
record.start_color = self.readRGBA()
record.end_ratio = self.readUI8()
record.end_color = self.readRGBA()
gradient.records.append(record)
return gradient
def readColorTransformAlpha(self):
transform = ColorTransformAlpha()
has_add_terms = self.readUB(1)
has_mult_terms = self.readUB(1)
transform.num_bits = self.readUB(4)
if has_mult_terms:
transform.red_mult_term = self.readSB(transform.num_bits)
transform.green_mult_term = self.readSB(transform.num_bits)
transform.blue_mult_term = self.readSB(transform.num_bits)
transform.alpha_mult_term = self.readSB(transform.num_bits)
if has_add_terms:
transform.red_add_term = self.readSB(transform.num_bits)
transform.green_add_term = self.readSB(transform.num_bits)
transform.blue_add_term = self.readSB(transform.num_bits)
transform.alpha_add_term = self.readSB(transform.num_bits)
self.alignToByte()
return transform
def readColorTransform(self):
transform = ColorTransform()
has_add_terms = self.readUB(1)
has_mult_terms = self.readUB(1)
transform.num_bits = self.readUB(4)
if has_mult_terms:
transform.red_mult_term = self.readSB(transform.num_bits)
transform.green_mult_term = self.readSB(transform.num_bits)
transform.blue_mult_term = self.readSB(transform.num_bits)
if has_add_terms:
transform.red_add_term = self.readSB(transform.num_bits)
transform.green_add_term = self.readSB(transform.num_bits)
transform.blue_add_term = self.readSB(transform.num_bits)
self.alignToByte()
return transform
def readMatrix(self):
matrix = Matrix()
if(self.readUB(1)):
matrix.num_scale_bits = self.readUB(5)
matrix.scale_x = self.readSB(matrix.num_scale_bits)
matrix.scale_y = self.readSB(matrix.num_scale_bits)
if(self.readUB(1)):
matrix.num_rotate_bits = self.readUB(5)
matrix.rotate_skew0 = self.readSB(matrix.num_rotate_bits)
matrix.rotate_skew1 = self.readSB(matrix.num_rotate_bits)
matrix.num_translate_bits = self.readUB(5)
matrix.translate_x = self.readSB(matrix.num_translate_bits)
matrix.translate_y = self.readSB(matrix.num_translate_bits)
self.alignToByte()
return matrix
def readRect(self):
rect = Rect()
rect.num_bits = num_bits = self.readUB(5)
rect.left = self.readSB(num_bits)
rect.right = self.readSB(num_bits)
rect.top = self.readSB(num_bits)
rect.bottom = self.readSB(num_bits)
self.alignToByte()
return rect
def readARGB(self):
rgb = RGBA()
rgb.alpha = self.readUI8()
rgb.red = self.readUI8()
rgb.green = self.readUI8()
rgb.blue = self.readUI8()
return rgb
def readRGBA(self):
rgb = RGBA()
rgb.red = self.readUI8()
rgb.green = self.readUI8()
rgb.blue = self.readUI8()
rgb.alpha = self.readUI8()
return rgb
def readRGB(self):
rgb = RGBA()
rgb.red = self.readUI8()
rgb.green = self.readUI8()
rgb.blue = self.readUI8()
rgb.alpha = 255
return rgb
def readEncUI32StringTable(self):
table = {}
count = self.readEncUI32()
for _ in range(count):
index = self.readEncUI32()
string = self.readString()
table[index] = string
return table
def readStringTable(self):
table = {}
count = self.readUI16()
for _ in range(count):
index = self.readUI16()
string = self.readString()
table[index] = string
return table
def readString(self):
length = self.byte_buffer.find(b"\x00")
while length == -1:
if not self.fillBuffer():
break
data = self.readBytes(length)
string = data.decode()
self.readUI8()
return string
def alignToByte(self):
self.bits_remaining = 0
def readSB(self, count):
if count > 0:
value = self.readUB(count)
if value & (1 << count - 1) != 0:
# negative
value |= -1 << count
return value
else:
return 0
def readUB(self, count):
if count > 0:
# the next available bit is always at the 31st bit of the buffer
while self.bits_remaining < count:
data = self.readBytes(1)
if len(data) == 1:
result = self.ui8.unpack(data)
ui8 = result[0]
else:
ui8 = 0
self.bit_buffer = self.bit_buffer | (ui8 << (24 - self.bits_remaining))
self.bits_remaining += 8
value = (self.bit_buffer >> (32 - count)) & ~(-1 << count)
self.bits_remaining -= count
# mask 32 bits in case of 64 bit system
self.bit_buffer = ((self.bit_buffer << count) & (-1 << (32 - self.bits_remaining))) & 0xFFFFFFFF
return value
else:
return 0
def readUI8(self):
'''Read an unsigned 8 bit integer.
'''
self.alignToByte()
data = self.readBytes(1)
if len(data) == 1:
result = self.ui8.unpack(data)
return result[0]
else:
return 0
def readSI16(self):
'''Read an signed 16 bit integer.
'''
self.alignToByte()
data = self.readBytes(2)
if len(data) == 2:
result = self.si16.unpack(data)
return result[0]
else:
return 0
def readUI16(self):
'''Read an unsigned 16 bit integer.
'''
self.alignToByte()
data = self.readBytes(2)
if len(data) == 2:
result = self.ui16.unpack(data)
return result[0]
else:
return 0
def readSI32(self):
'''Read an signed 32 bit integer.
'''
self.alignToByte()
data = self.readBytes(4)
if len(data) == 4:
result = self.si32.unpack(data)
return result[0]
else:
return 0
def readUI32(self):
'''Read an unsigned 32 bit integer.
'''
self.alignToByte()
data = self.readBytes(4)
if len(data) == 4:
result = self.ui32.unpack(data)
return result[0]
else:
return 0
def readEncUI32(self):
self.alignToByte()
result = 0
shift = 0
while shift < 32:
ui8 = self.readUI8()
result |= (ui8 & 0x7F) << shift
shift += 7
if not (ui8 & 0x80):
break
return result
def readF32(self):
'''Read a 32-bit floating point
'''
self.alignToByte()
data = self.readBytes(4)
if len(data) == 4:
result = self.f32.unpack(data)
return result[0]
else:
return NaN
def readF64(self):
'''Read a 32-bit floating point
'''
self.alignToByte()
data = self.readBytes(8)
if len(data) == 8:
result = self.f64.unpack(data)
return result[0]
else:
return NaN
def readBytes(self, count):
'''Read a certain number of bytes
'''
while len(self.byte_buffer) < count:
if not self.fillBuffer():
break
if count > self.bytes_remaining:
count = self.bytes_remaining
result = self.byte_buffer[0:count]
del self.byte_buffer[0:count]
self.bytes_remaining -= count
return result
def fillBuffer(self):
'''Fill the buffer with more data
'''
chunk = self.source.read(4096)
if len(chunk) == 0:
return False
if self.decompressor:
chunk = self.decompressor.decompress(chunk)
self.byte_buffer.extend(chunk)
return True
def startDecompression(self):
'''Begin decompressing data using the zlib algorithm
'''
self.decompressor = decompressobj()
decompressed_buffer = self.decompressor.decompress(self.byte_buffer)
del self.byte_buffer[:]
self.byte_buffer.extend(decompressed_buffer)
| Python |
'''
Created on Jul 21, 2012
@author: Chung Leong
'''
from zlib import compressobj
from struct import Struct
from flaczki.swf.tags import *
class SWFAssembler(object):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
self.ui8 = Struct('<B')
self.si16 = Struct('<h')
self.ui16 = Struct('<H')
self.si32 = Struct('<i')
self.ui32 = Struct('<I')
self.f32 = Struct('f')
self.f64 = Struct('d')
self.tag_codes_and_handlers = {
CSMTextSettings: (74, self.writeCSMTextSettingsTag),
DefineScalingGrid: (78, self.writeDefineScalingGridTag),
DefineBinaryData: (87, self.writeDefineBinaryDataTag),
DefineBits: (6, self.writeDefineBitsTag),
DefineBitsJPEG2: (21, self.writeDefineBitsJPEG2Tag),
DefineBitsJPEG3: (35, self.writeDefineBitsJPEG3Tag),
DefineBitsJPEG4: (90, self.writeDefineBitsJPEG4Tag),
DefineBitsLossless: (20, self.writeDefineBitsLosslessTag),
DefineBitsLossless2: (36, self.writeDefineBitsLossless2Tag),
DefineButton: (7, self.writeDefineButtonTag),
DefineButton2: (34, self.writeDefineButton2Tag),
DefineButtonCxform: (23, self.writeDefineButtonCxformTag),
DefineButtonSound: (17, self.writeDefineButtonSoundTag),
DefineEditText: (37, self.writeDefineEditTextTag),
DefineFont: (10, self.writeDefineFontTag),
DefineFont2: (48, self.writeDefineFont2Tag),
DefineFont3: (75, self.writeDefineFont3Tag),
DefineFont4: (91, self.writeDefineFont4Tag),
DefineFontAlignZones: (73, self.writeDefineFontAlignZonesTag),
DefineFontInfo: (13, self.writeDefineFontInfoTag),
DefineFontInfo2: (62, self.writeDefineFontInfo2Tag),
DefineFontName: (88, self.writeDefineFontNameTag),
DefineMorphShape: (46, self.writeDefineMorphShapeTag),
DefineMorphShape2: (84, self.writeDefineMorphShape2Tag),
DefineSceneAndFrameLabelData: (86, self.writeDefineSceneAndFrameLabelDataTag),
DefineShape: (2, self.writeDefineShapeTag),
DefineShape2: (22, self.writeDefineShape2Tag),
DefineShape3: (32, self.writeDefineShape3Tag),
DefineShape4: (83, self.writeDefineShape4Tag),
DefineSprite: (39, self.writeDefineSpriteTag),
DefineText: (11, self.writeDefineTextTag),
DefineText2: (33, self.writeDefineText2Tag),
DefineSound: (14, self.writeDefineSoundTag),
DefineVideoStream: (60, self.writeDefineVideoStreamTag),
DoInitAction: (59, self.writeDoInitActionTag),
DoABC: (82, self.writeDoABCTag),
DoAction: (12, self.writeDoActionTag),
EnableDebugger: (58, self.writeEnableDebuggerTag),
EnableDebugger2: (64, self.writeEnableDebugger2Tag),
End: (0, self.writeEndTag),
ExportAssets: (56, self.writeExportAssetsTag),
FileAttributes: (69, self.writeFileAttributesTag),
FrameLabel: (43, self.writeFrameLabelTag),
ImportAssets: (57, self.writeImportAssetsTag),
ImportAssets2: (71, self.writeImportAssets2Tag),
JPEGTables: (8, self.writeJPEGTablesTag),
Metadata: (77, self.writeMetadataTag),
Protect: (24, self.writeProtectTag),
PlaceObject: (4, self.writePlaceObjectTag),
PlaceObject2: (26, self.writePlaceObject2Tag),
PlaceObject3: (70, self.writePlaceObject3Tag),
RemoveObject: (5, self.writeRemoveObjectTag),
RemoveObject2: (28, self.writeRemoveObject2Tag),
ScriptLimits: (65, self.writeScriptLimitsTag),
SetBackgroundColor: (9, self.writeSetBackgroundColorTag),
SetTabIndex: (66, self.writeSetTabIndexTag),
ShowFrame: (1, self.writeShowFrameTag),
StartSound: (15, self.writeStartSoundTag),
StartSound2: (89, self.writeStartSound2Tag),
SoundStreamHead: (18, self.writeSoundStreamHeadTag),
SoundStreamHead2: (45, self.writeSoundStreamHead2Tag),
SoundStreamBlock: (19, self.writeSoundStreamBlockTag),
SymbolClass: (76, self.writeSymbolClassTag),
VideoFrame: (61, self.writeVideoFrameTag)
}
def assemble(self, destination, swf_file):
self.destination = destination
self.byte_buffer = None
self.bytes_remaining = 8
self.buffer_stack = []
self.bit_buffer = 0
self.bits_remaining = 0
self.compressor = None
# convert all tags to generic ones first so we know the total length
# names = [tag.__class__.__name__ for tag in swf_file.tags]
generic_tags = [tag if isinstance(tag, Generic) else self.createGenericTag(tag) for tag in swf_file.tags];
# signature
signature = swf_file.version << 24
signature |= 0x535743 if swf_file.compressed else 0x535746
self.writeUI32(signature)
# file length
file_length = 8 + (((swf_file.frame_size.num_bits * 4 + 5) + 7) >> 3) + 4
for tag in generic_tags:
file_length += tag.header_length + tag.length
self.writeUI32(file_length)
if swf_file.compressed:
# start compressing data
self.startCompression()
self.writeRect(swf_file.frame_size)
# frame rate and count
self.writeUI16(swf_file.frame_rate)
self.writeUI16(swf_file.frame_count)
for tag in generic_tags:
self.writeTag(tag)
if swf_file.compressed:
self.stopCompression()
self.destination = None
def createGenericTag(self, tag):
tag_code, handler = self.tag_codes_and_handlers[tag.__class__]
self.startBuffer()
handler(tag)
data = self.endBuffer()
generic_tag = Generic()
generic_tag.code = tag_code
generic_tag.data = data
generic_tag.length = len(data)
# use the short format only for tags with no data--just to be safe
generic_tag.header_length = 6 if generic_tag.length > 0 else 2
return generic_tag
def writeTag(self, tag):
if not isinstance(tag, Generic):
tag = self.createGenericTag(tag)
if tag.header_length == 2:
tag_code_and_length = (tag.code << 6) | tag.length
self.writeUI16(tag_code_and_length)
else:
tag_code_and_length = (tag.code << 6) | 0x003F
self.writeUI16(tag_code_and_length)
self.writeUI32(tag.length)
self.writeBytes(tag.data)
def writeCSMTextSettingsTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUB(tag.renderer, 2)
self.writeUB(tag.gridFit, 3)
self.writeUB(tag.reserved1, 3)
self.writeF32(tag.thickness)
self.writeF32(tag.sharpness)
self.writeUI8(tag.reserved2)
def writeDefineBinaryDataTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI32(tag.reserved)
self.writeBytes(tag.data)
def writeDefineBitsTag(self, tag):
self.writeUI16(tag.character_id)
self.writeBytes(tag.image_data)
def writeDefineBitsLosslessTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(tag.format)
self.writeUI16(tag.width)
self.writeUI16(tag.height)
if tag.format == 3:
self.writeUI8(tag.color_table_size)
self.writeBytes(tag.image_data)
def writeDefineBitsLossless2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(tag.format)
self.writeUI16(tag.width)
self.writeUI16(tag.height)
if tag.format == 3:
self.writeUI8(tag.colorTableSize)
self.writeBytes(tag.image_data)
def writeDefineBitsJPEG2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeBytes(tag.image_data)
def writeDefineBitsJPEG3Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI32(len(tag.image_data))
self.writeBytes(tag.image_data)
self.writeBytes(tag.alpha_data)
def writeDefineBitsJPEG4Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI32(len(tag.image_data))
self.writeUI16(tag.deblockingParam)
self.writeBytes(tag.image_data)
self.writeBytes(tag.alpha_data)
def writeDefineButtonTag(self, tag):
self.writeUI16(tag.character_id)
self.writeButtonRecords(tag.characters, 1)
self.writeBytes(tag.actions)
def writeDefineButton2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(tag.flags)
if tag.actions != None:
self.startBuffer()
self.writeButtonRecords(tag.characters, 2)
data = self.endBuffer()
action_offset = len(data) + 2
self.writeUI16(action_offset)
self.writeBytes(data)
self.writeBytes(tag.actions)
else:
self.writeUI16(0)
self.writeButtonRecords(tag.characters, 2)
def writeDefineButtonCxformTag(self, tag):
self.writeUI16(tag.character_id)
self.writeColorTransform(tag.color_transform)
def writeDefineButtonSoundTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI16(tag.over_up_to_idle_id)
if tag.over_up_to_idle_id != 0:
self.writeSoundInfo(tag.over_up_to_idle_info)
self.writeUI16(tag.idle_to_over_up_id)
if tag.idle_to_over_up_id != 0:
self.writeSoundInfo(tag.idle_to_over_up_info)
self.writeUI16(tag.over_up_to_over_down_id)
if tag.over_up_to_over_down_id != 0:
self.writeSoundInfo(tag.over_up_to_over_down_info)
self.writeUI16(tag.over_down_to_over_up_id)
if tag.over_down_to_over_up_id != 0:
self.writeSoundInfo(tag.over_down_to_over_up_info)
def writeDefineEditTextTag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.bounds)
self.writeUI16(tag.flags)
if tag.flags & 0x0001: # HasFont
self.writeUI16(tag.font_id)
self.writeUI16(tag.font_height)
if tag.flags & 0x8000: # HasFontClass
self.writeString(tag.font_class)
if tag.flags & 0x0004: # HasTextColor
self.writeRGBA(tag.text_color)
if tag.flags & 0x0002: # HasMaxLength
self.writeUI16(tag.maxLength)
if tag.flags & 0x2000: # HasLayout
self.writeUI8(tag.align)
self.writeUI16(tag.leftMargin)
self.writeUI16(tag.rightMargin)
self.writeUI16(tag.indent)
self.writeUI16(tag.leading)
self.writeString(tag.variable_name)
if tag.flags & 0x0080: # HasText
self.writeString(tag.initialText)
def writeDefineFontTag(self, tag):
glyph_count = len(tag.glyph_table)
offset = glyph_count << 1
self.writeUI16(tag.character_id)
shape_table = []
for glyph in tag.glyph_table:
self.writeUI16(offset)
self.startBuffer()
self.writeShape(glyph)
data = self.endBuffer()
shape_table.append(data)
offset += len(data)
for data in shape_table:
self.writeBytes(data)
def writeDefineFont2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(tag.flags)
self.writeUI8(tag.language_code)
self.writeUI8(len(tag.name))
self.writeBytes(tag.name)
glyph_count = len(tag.glyph_table)
self.writeUI16(glyph_count)
shape_table = []
if tag.flags & 0x08: # WideOffsets
offset = glyph_count * 4 + 4
for glyph in tag.glyph_table:
self.writeUI32(offset)
self.startBuffer()
self.writeShape(glyph)
data = self.endBuffer()
shape_table.append(data)
offset += len(data)
self.writeUI32(offset)
else:
offset = glyph_count * 2 + 2
for glyph in tag.glyph_table:
self.writeUI16(offset)
self.startBuffer()
self.writeShape(glyph)
data = self.endBuffer()
shape_table.append(data)
offset += len(data)
self.writeUI16(offset)
for data in shape_table:
self.writeBytes(data)
if tag.flags & 0x04: # WideCodes
for code in tag.code_table:
self.writeUI16(code)
else:
for code in tag.code_table:
self.writeUI8(code)
if tag.flags & 0x80 or tag.ascent != None: # HasLayout
self.writeSI16(tag.ascent)
self.writeSI16(tag.descent)
self.writeSI16(tag.leading)
for advance in tag.advance_table:
self.writeUI16(advance)
for bound in tag.bound_table:
self.writeRect(bound)
if tag.flags & 0x04: # WideCodes
self.writeWideKerningRecords(tag.kerning_table)
else:
self.writeKerningRecords(tag.kerning_table)
def writeDefineFont3Tag(self, tag):
self.writeDefineFont2Tag(tag)
def writeDefineFont4Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(tag.flags)
self.writeString(tag.name)
self.writeBytes(tag.cff_data)
def writeDefineFontAlignZonesTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUB(tag.table_hint, 2)
self.writeZoneRecords(tag.zone_table)
def writeDefineFontInfoTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(len(tag.name))
self.writeBytes(tag.name)
self.writeUI8(tag.flags)
if tag.flags & 0x01: # WideCodes
for code in tag.code_table:
self.writeUI16(code)
else:
for code in tag.code_table:
self.writeUI8(code)
def writeDefineFontInfo2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI8(len(tag.name))
self.writeBytes(tag.name)
self.writeUI8(tag.flags)
self.writeUI8(tag.languageCode)
if tag.flags & 0x01: # WideCodes
for code in tag.code_table:
self.writeUI16(code)
else:
for code in tag.code_table:
self.writeUI8(code)
def writeDefineFontNameTag(self, tag):
self.writeUI16(tag.character_id)
self.writeString(tag.name)
self.writeString(tag.copyright)
def writeDefineMorphShapeTag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.start_bounds)
self.writeRect(tag.end_bounds)
self.writeMorphShapeWithStyle(tag.morph_shape, 3) # use structures of DefineShape3
def writeDefineMorphShape2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.start_bounds)
self.writeRect(tag.end_bounds)
self.writeRect(tag.start_edge_bounds)
self.writeRect(tag.end_edge_bounds)
self.writeUI8(tag.flags)
self.writeMorphShapeWithStyle(tag.morph_shape, 4) # use structures of DefineShape4
def writeDefineScalingGridTag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.splitter)
def writeDefineSceneAndFrameLabelDataTag(self, tag):
self.writeEncUI32StringTable(tag.scene_names)
self.writeEncUI32StringTable(tag.frame_labels)
def writeDefineShapeTag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.shape_bounds)
self.writeShapeWithStyle(tag.shape, 1)
def writeDefineShape2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.shape_bounds)
self.writeShapeWithStyle(tag.shape, 2)
def writeDefineShape3Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.shape_bounds)
self.writeShapeWithStyle(tag.shape, 3)
def writeDefineShape4Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.shape_bounds)
self.writeRect(tag.edge_bounds)
self.writeUI8(tag.flags)
self.writeShapeWithStyle(tag.shape, 4)
def writeDefineSoundTag(self, tag):
self.writeUB(tag.format, 4)
self.writeUB(tag.sampleRate, 2)
self.writeUB(tag.sampleSize, 1)
self.writeUB(tag.type, 1)
self.writeUI32(tag.sample_count)
self.writeBytes(tag.data)
def writeDefineSpriteTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI16(tag.frame_count)
for child in tag.tags:
self.writeTag(child)
def writeDefineTextTag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.bounds)
self.writeMatrix(tag.matrix)
self.writeUI8(tag.glyph_bits)
self.writeUI8(tag.advance_bits)
self.writeTextRecords(tag.text_records, tag.glyph_bits, tag.advance_bits, 1)
def writeDefineText2Tag(self, tag):
self.writeUI16(tag.character_id)
self.writeRect(tag.bounds)
self.writeMatrix(tag.matrix)
self.writeUI8(tag.glyph_bits)
self.writeUI8(tag.advance_bits)
self.writeTextRecords(tag.text_records, tag.glyph_bits, tag.advance_bits, 2)
def writeDefineVideoStreamTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI16(tag.frame_count)
self.writeUI16(tag.width)
self.writeUI16(tag.height)
self.writeUI8(tag.flags)
self.writeUI8(tag.codecId)
def writeDoABCTag(self, tag):
self.writeUI32(tag.flags)
self.writeString(tag.byte_code_name)
self.writeBytes(tag.byte_codes)
def writeDoActionTag(self, tag):
self.writeBytes(tag.actions)
def writeDoInitActionTag(self, tag):
self.writeUI16(tag.character_id)
self.writeBytes(tag.actions)
def writeEndTag(self, tag):
pass
def writeEnableDebuggerTag(self, tag):
self.writeString(tag.password)
def writeEnableDebugger2Tag(self, tag):
self.writeUI16(tag.reserved)
self.writeString(tag.password)
def writeExportAssetsTag(self, tag):
self.writeStringTable(tag.names)
def writeFileAttributesTag(self, tag):
self.writeUI32(tag.flags)
def writeFrameLabelTag(self, tag):
self.writeString(tag.name)
if tag.anchor != None:
tag.writeString(tag.anchor)
def writeImportAssetsTag(self, tag):
self.writeString(tag.url)
self.writeStringTable(tag.names)
def writeImportAssets2Tag(self, tag):
self.writeString(tag.url)
self.writeUI8(tag.reserved1)
self.writeUI8(tag.reserved2)
self.writeStringTable(table.names)
def writeJPEGTablesTag(self, tag):
self.writeBytes(tag.jpeg_data)
def writeMetadataTag(self, tag):
self.writeString(tag.metadata)
def writePlaceObjectTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI16(tag.depth)
self.writeMatrix(tag.matrix)
if tag.color_transform != None:
self.writeColorTransform(tag.color_transform)
def writePlaceObject2Tag(self, tag):
self.writeUI8(tag.flags)
self.writeUI16(tag.depth)
if tag.flags & 0x02: # HasCharacter
self.writeUI16(tag.character_id)
if tag.flags & 0x04: # HasMatrix
self.writeMatrix(tag.matrix)
if tag.flags & 0x08: # HasColorTransform
self.writeColorTransformAlpha(tag.color_transform)
if tag.flags & 0x10: # HasRatio
self.writeUI16(tag.ratio)
if tag.flags & 0x20: # HasName
self.writeString(tag.name)
if tag.flags & 0x40: # HasClipDepth
self.writeUI16(tag.clipDepth)
if tag.flags & 0x80: # HasClipActions
self.writeUI16(0)
if self.swf_version >= 6:
self.writeUI32(tag.allEventFlags)
else:
self.writeUI16(tag.allEventFlags)
self.writeClipActions(tag.clip_actions)
def writePlaceObject3Tag(self, tag):
self.writeUI16(tag.flags)
self.writeUI16(tag.depth)
if tag.flags & 0x0800: # HasClassName
self.writeString(tag.class_name)
if tag.flags & 0x0002: # HasCharacter
self.writeUI16(tag.character_id)
if tag.flags & 0x0004: # HasMatrix
self.writeMatrix(tag.matrix)
if tag.flags & 0x0008: # HasColorTransform
self.writeColorTransformAlpha(tag.color_transform)
if tag.flags & 0x0010: # HasRatio
self.writeUI16(tag.ratio)
if tag.flags & 0x0020: # HasName
self.writeString(tag.name)
if tag.flags & 0x0040: # HasClipDepth
self.writeUI16(tag.clipDepth)
if tag.flags & 0x0100: # HasFilterList
self.writeFilters(tag.filters)
if tag.flags & 0x0200: # HasBlendMode
self.writeUI8(tag.blend_mode)
if tag.flags & 0x0400: # HasCacheAsBitmap
self.writeUI8(tag.bitmapCache)
if tag.flags & 0x0080: # HasClipActions
self.writeClipActions(tag.clip_actions)
if tag.flags & 0x2000: # HasVisibility
self.writeUI8(tag.visibility)
if tag.flags & 0x4000: # HasBackgroundColor
self.writeRGBA(tag.bitmap_cache_background_color)
if tag.flags & 0x0080: # HasClipActions
self.writeUI16(0)
if self.swf_version >= 6:
self.writeUI32(tag.allEventFlags)
else:
self.writeUI16(tag.allEventFlags)
self.writeClipActions(tag.clip_actions)
def writeProtectTag(self, tag):
self.writeString(tag.password)
def writeRemoveObjectTag(self, tag):
self.writeUI16(tag.character_id)
self.writeUI16(tag.depth)
def writeRemoveObject2Tag(self, tag):
self.writeUI16(tag.depth)
def writeScriptLimitsTag(self, tag):
self.writeUI16(tag.max_recursion_depth)
self.writeUI16(tag.script_timeout_seconds)
def writeSetBackgroundColorTag(self, tag):
self.writeRGB(tag.color)
def writeSetTabIndexTag(self, tag):
self.writeUI16(tag.depth)
self.writeUI16(tag.tab_index)
def writeShowFrameTag(self, tag):
pass
def writeSoundStreamBlockTag(self, tag):
self.writeBytes(tag.data)
def writeSoundStreamHeadTag(self, tag):
self.writeUI16(tag.flags)
self.writeUI16(tag.sample_count)
if tag.flags & 0xF000 == 0x2000:
self.writeS16(tag.latency_seek)
def writeSoundStreamHead2Tag(self, tag):
self.writeUB(0, 4)
self.writeUB(tag.playback_sample_rate, 2)
self.writeUB(tag.playback_sample_size, 1)
self.writeUB(tag.playback_type, 1)
self.writeUB(tag.format, 4)
self.writeUB(tag.sample_rate, 2)
self.writeUB(tag.sample_size, 1)
self.writeUB(tag.type, 1)
self.writeUI16(tag.sample_count)
if tag.format == 2:
self.writeS16(tag.latency_seek)
def writeStartSoundTag(self, tag):
self.writeUI16(tag.character_id)
self.writeSoundInfo(tag.info)
def writeStartSound2Tag(self, tag):
self.writeString(tag.class_name)
self.writeSoundInfo(tag.info)
def writeSymbolClassTag(self, tag):
self.writeStringTable(tag.names)
def writeVideoFrameTag(self, tag):
self.writeUI16(tag.stream_id)
self.writeUI16(tag.frame_number)
self.writeBytes(tag.data)
def writeZoneRecords(self, records):
for record in records:
self.writeUI8(1) # number of zone data--always 1
self.writeUI16(record.zone_data1)
self.writeUI16(record.zone_data2)
self.writeUI8(record.flags)
self.writeUI16(record.alignment_coordinate)
self.writeUI16(record.range)
def writeKerningRecords(self, kerns):
self.writeUI16(len(kerns))
for kern in kerns:
self.writeUI8(kern.code1)
self.writeUI8(kern.code2)
self.writeUI16(kern.adjustment)
def writeWideKerningRecords(self, kerns):
self.writeUI16(len(kerns))
for kern in kerns:
self.writeUI16(kern.code1)
self.writeUI16(kern.code2)
self.writeUI16(kern.adjustment)
def writeClipActions(self, clip_actions):
clip_actions = []
for clip_action in clip_actions:
if self.swf_version >= 6:
self.writeUI32(clip_action.eventFlags)
else:
self.writeUI16(clip_action.eventFlags)
self.writeUI32(len(clip_action.actions))
if clip_action.eventFlags & 0x00020000: # KeyPress
self.writeUI8(clip_action.keyCode)
self.writeBytes(clip_action.actions)
if self.swf_version >= 6:
self.writeUI32(0)
else:
self.writeUI16(0)
def writeFilters(self, filters):
self.writeUI8(len(filters))
for f in range(filters):
if isinstance(f, DropShadowFilter):
drop_shadow = f
self.writeUI8(0)
self.writeRGBA(drop_shadow.shadowColor)
self.writeSI32(drop_shadow.blur_x)
self.writeSI32(drop_shadow.blur_y)
self.writeSI32(drop_shadow.angle)
self.writeSI32(drop_shadow.distance)
self.writeSI16(drop_shadow.strength)
self.writeUB(drop_shadow.flags, 3)
self.writeUB(drop_shadow.passes, 5)
elif isinstance(f, BlurFilter):
blur = f
self.writeUI8(1)
self.writeSI32(blur.blur_x)
self.writeSI32(blur.blur_y)
self.writeUB(blur.passes, 5)
elif isinstance(f, GlowFilter):
glow = f
self.writeUI8(2)
self.writeRGBA(glow.color)
self.writeSI32(glow.blur_x)
self.writeSI32(glow.blur_y)
self.writeSI16(glow.strength)
self.writeUB(glow.flags, 3)
self.writeUB(glow.passes, 5)
elif isinstance(f, BevelFilter):
bevel = f
self.writeUI8(3)
self.writeRGBA(bevel.highlight_color)
self.writeRGBA(bevel.shadow_color)
self.writeSI32(bevel.blur_x)
self.writeSI32(bevel.blur_y)
self.writeSI32(bevel.angle)
self.writeSI32(bevel.distance)
self.writeSI16(bevel.strength)
self.writeUB(bevel.flags, 4)
self.writeUB(bevel.passes, 4)
elif isinstance(f, GradientGlowFilter):
gradient_glow = f
self.writeUI8(4)
self.writeUI8(len(gradient_glow.colors))
for rgb in gradient_glow.colors:
self.writeRGBA(rgb)
for ratio in gradient_glow.ratios:
self.writeUI8(ratio)
self.writeSI32(gradient_glow.blur_x)
self.writeSI32(gradient_glow.blur_y)
self.writeSI32(gradient_glow.angle)
self.writeSI32(gradient_glow.distance)
self.writeSI16(gradient_glow.strength)
self.writeUB(gradient_glow.flags, 4)
self.writeUB(gradient_glow.passes, 4)
elif isinstance(f, ConvolutionFilter):
convolution = f
self.writeUI8(5)
self.writeUI8(convolution.matrix_x)
self.writeUI8(convolution.matrix_y)
self.writeFloat(convolution.divisor)
self.writeFloat(convolution.bias)
for m in convolution.matrix:
self.writeFloat(m)
self.writeRGBA(convolution.default_color)
self.writeUI8(convolution.flags)
elif isinstance(f, ColorMatrixFilter):
color_matrix = f
self.writeUI8(6)
color_matrix.matrix = []
for _ in range(20):
color_matrix.matrix.append(self.writeFloat())
filters.append(color_matrix)
elif isinstance(f, GradientBevelFilter):
gradient_bevel = f
self.writeUI8(7)
self.writeUI8(len(gradient_bevel.colors))
for rgb in gradient_bevel.colors:
self.writeRGBA(rgb)
for ratio in gradient_bevel.ratios:
self.writeUI8(ratio)
self.writeSI32(gradient_bevel.blur_x)
self.writeSI32(gradient_bevel.blur_y)
self.writeSI32(gradient_bevel.angle)
self.writeSI32(gradient_bevel.distance)
self.writeSI16(gradient_bevel.strength)
self.writeUB(gradient_bevel.flags, 4)
self.writeUB(gradient_bevel.passes, 4)
def writeTextRecords(self, records, glyph_bits, advance_bits, version):
for record in records:
self.writeUI8(record.flags)
if record.flags & 0x08: # HasFont
self.writeUI16(record.font_id)
if record.flags & 0x04: # HasColor
if version >= 2:
self.writeRGBA(record.textColor)
else:
self.writeRGB(record.textColor)
if record.flags & 0x02: # HasXOffset
self.writeSI16(record.x_offset)
if record.flags & 0x01: # HasYOffset
self.writeSI16(record.y_offset)
if record.flags & 0x08: # HasFont
self.writeUI16(record.text_height)
self.writeGlyphEntries(record.glyphs, glyph_bits, advance_bits)
self.writeUI8(0)
def writeGlyphEntries(self, glyphs, glyph_bits, advance_bits):
self.writeUI8(len(glyphs))
for glyph in glyphs:
self.writeUB(glyph.index, glyph_bits)
self.writeUB(glyph.advance, advance_bits)
def writeSoundInfo(self, info):
self.writeUI8(info.flags)
if info.flags & 0x01: # HasInPoint
self.writeUI32(info.in_point)
if info.flags & 0x02: # HasOutPoint
self.writeUI32(info.out_point)
if info.flags & 0x04: # HasLoops
self.writeUI32(info.loop_count)
if info.flags & 0x08: # HasEnvelope
self.writeSoundEnvelopes(info.envelopes)
def writeSoundEnvelopes(self, envelopes):
self.writeUI8(len(envelopes))
for envelope in envelopes:
self.writeUI32(envelope.position_44)
self.writeUI16(envelope.left_level)
self.writeUI16(envelope.right_level)
def writeButtonRecords(self, records, version):
for record in records:
self.writeUI8(record.flags)
self.writeUI16(record.character_id)
self.writeUI16(record.place_depth)
self.writeMatrix(record.matrix)
if version == 2:
self.writeColorTransformAlpha(record.color_transform)
if version == 2 and record.flags & 0x10: # HasFilterList
self.writeFilters(record.filters)
if version == 2 and record.flags & 0x20: # HasBlendMode
self.writeUI8(record.blend_mode)
self.writeUI8(0)
def writeShape(self, shape):
self.writeUB(shape.num_fill_bits, 4)
self.writeUB(shape.num_line_bits, 4)
self.writeShapeRecords(shape.edges, shape.num_fill_bits, shape.num_line_bits, 1)
def writeShapeWithStyle(self, shape, version):
self.writeFillStyles(shape.fill_styles, version)
self.writeLineStyles(shape.line_styles, version)
self.writeUB(shape.num_fill_bits, 4)
self.writeUB(shape.num_line_bits, 4)
self.writeShapeRecords(shape.edges, shape.num_fill_bits, shape.num_line_bits, version)
def writeMorphShapeWithStyle(self, shape, version):
self.startBuffer()
self.writeMorphFillStyles(shape.fill_styles)
self.writeMorphLineStyles(shape.line_styles, version)
self.writeUB(shape.start_num_fill_bits, 4)
self.writeUB(shape.start_num_line_bits, 4)
self.writeShapeRecords(shape.startEdges, shape.start_num_fill_bits, shape.start_num_line_bits, version)
data = self.endBuffer()
end_edges_offset = len(data)
self.writeUI32(end_edges_offset)
self.writeUB(shape.end_num_fill_bits, 4)
self.writeUB(shape.end_num_line_bits, 4)
self.writeShapeRecords(shape.endEdges, shape.end_num_fill_bits, shape.end_num_line_bits, version)
def writeShapeRecords(self, records, num_fill_bits, num_line_bits, version):
for record in records:
if isinstance(record, StraightEdge):
line = record
self.writeUB(0x03, 2) # straight edge
self.writeUB(line.num_bits - 2, 4)
if line.delta_x != 0 and line.delta_y != 0:
self.writeUB(0x01, 1) # general line
self.writeSB(line.delta_x, line.num_bits)
self.writeSB(line.delta_y, line.num_bits)
else:
if line.delta_x != 0:
self.writeUB(0x00, 2) # horizontal
self.writeSB(line.delta_x, line.num_bits)
else:
self.writeUB(0x01, 2) # vertical
self.writeSB(line.delta_y, line.num_bits)
elif isinstance(record, QuadraticCurve):
curve = record
self.writeUB(0x02, 2) # curve
self.writeUB(curve.num_bits - 2, 4)
self.writeSB(curve.control_delta_x, curve.num_bits)
self.writeSB(curve.control_delta_y, curve.num_bits)
self.writeSB(curve.anchor_delta_x, curve.num_bits)
self.writeSB(curve.anchor_delta_y, curve.num_bits)
elif isinstance(record, StyleChange):
self.writeUB(0x00, 1) # change style
change = record
flags = 0x00
if change.num_move_bits != None:
flags |= 0x01 # HasMove
if change.fill_style0 != None:
flags |= 0x02 # HasFillStyle0
if change.fill_style1 != None:
flags |= 0x04 # HasFillStyle1
if change.line_style != None:
flags |= 0x08 # HasLineStyle
if change.num_fill_bits != None:
flags |= 0x10 # HasNewStyles
self.writeUB(flags, 5)
if flags & 0x01: # HasMove
self.writeSB(change.num_move_bits, 5)
self.writeSB(change.move_delta_x, change.num_move_bits)
self.writeSB(change.move_delta_y, change.num_move_bits)
if flags & 0x02: # HasFillStyle0
self.writeUB(change.fill_style0, num_fill_bits)
if flags & 0x04: # HasFillStyle1
self.writeUB(change.fill_style1, num_fill_bits)
if flags & 0x08: # HasLineStyle
self.writeUB(change.line_style, num_line_bits)
if flags & 0x10: # HasNewStyles
self.writeFillStyles(change.new_fill_styles, version)
self.writeLineStyles(change.new_line_styles, version)
self.writeUB(change.num_fill_bits, 4)
self.writeUB(change.num_line_bits, 4)
num_fill_bits = change.num_fill_bits
num_line_bits = change.num_line_bits
self.writeUB(0x00, 6)
self.alignToByte()
def writeFillStyles(self, styles, version):
count = len(styles)
if count < 255:
self.writeUI8(count)
else:
self.writeUI8(0xFF)
self.writeUI16(count)
for style in styles:
self.writeFillStyle(style, version)
def writeFillStyle(self, style, version):
self.writeUI8(style.type)
if style.type == 0x00:
if version >= 3:
self.writeRGBA(style.color)
else:
self.writeRGB(style.color)
elif style.type in (0x10, 0x12, 0x13):
self.writeMatrix(style.gradient_matrix)
if style.type == 0x13:
self.writeFocalGradient(style.gradient, version)
else:
self.writeGradient(style.gradient, version)
elif style.type in (0x40, 0x41, 0x42, 0x43):
self.writeUI16(style.bitmap_id)
self.writeMatrix(style.bitmap_matrix)
def writeMorphFillStyles(self, styles):
count = len(styles)
if count < 255:
self.writeUI8(count)
else:
self.writeUI8(0xFF)
self.writeUI16(count)
for style in styles:
self.writeMorphFillStyle(style)
def writeMorphFillStyle(self, style):
style = MorphFillStyle()
self.writeUI8(style.type)
if style.type == 0x00:
self.writeRGBA(style.start_color)
self.writeRGBA(style.end_color)
elif style.type in (0x10, 0x12):
self.writeMatrix(style.start_gradient_matrix)
self.writeMatrix(style.end_gradient_matrix)
self.writeMorphGradient(style.gradient)
elif style.type in (0x40, 0x41, 0x42, 0x43):
self.writeUI16(style.bitmapId)
self.writeMatrix(style.start_bitmap_matrix)
self.writeMatrix(style.end_bitmap_matrix)
def writeLineStyles(self, styles, version):
count = len(styles)
if count < 255:
self.writeUI8(count)
else:
self.writeUI8(0xFF)
self.writeUI16(count)
for style in styles:
if version >= 4:
self.writeLineStyle2(style, version)
else:
self.writeLineStyle(style, version)
def writeLineStyle2(self, style, version):
self.writeUI16(style.width)
self.writeUB(style.start_cap_style, 2)
self.writeUB(style.join_style, 2)
self.writeUB(style.flags, 10)
self.writeUB(style.end_cap_style, 2)
if style.join_style == 2: # JoinStyleMiter
self.writeUI16(style.miterLimitFactor)
if style.flags & 0x0200: # HasFill
self.writeFillStyle(style.fill_style, version)
else:
self.writeRGBA(style.color)
def writeLineStyle(self, style, version):
self.writeUI16(style.width)
if version >= 3:
self.writeRGBA(style.color)
else:
self.writeRGB(style.color)
def writeMorphLineStyles(self, styles, version):
count = len(styles)
if count < 255:
self.writeUI8(count)
else:
self.writeUI8(0xFF)
self.writeUI16(count)
for style in styles:
if version >= 4:
self.writeMorphLineStyle2(style)
else:
self.writeMorphLineStyle(style)
def writeMorphLineStyle2(self, style):
self.writeUI16(style.start_width)
self.writeUI16(style.end_width)
self.writeUB(style.start_cap_style, 2)
self.writeUB(style.join_style, 2)
self.writeUB(style.flags, 10)
self.writeUB(style.end_cap_style, 2)
if style.join_style == 2: # JoinStyleMiter
self.writeUI16(style.miterLimitFactor)
if style.flags & 0x0200: # HasFill
self.writeMorphFillStyle(style.fill_style)
else:
self.writeRGBA(style.start_color)
self.writeRGBA(style.end_color)
def writeMorphLineStyle(self, style):
self.writeUI16(style.start_width)
self.writeUI16(style.end_width)
self.writeRGBA(style.start_color)
self.writeRGBA(style.end_color)
def writeGradient(self, gradient, version):
self.writeUB(gradient.spread_mode, 2)
self.writeUB(gradient.interpolation_mode, 2)
self.writeGradientControlPoints(gradient.control_points, version)
def writeFocalGradient(self, gradient, version):
self.writeUB(gradient.spread_mode, 2)
self.writeUB(gradient.interpolation_mode, 2)
self.writeGradientControlPoints(gradient.control_points, version)
self.writeSI16(gradient.focal_point)
def writeGradientControlPoints(self, control_points, version):
self.writeUB(len(control_points), 4)
for control_point in control_points:
self.writeUI8(control_point.ratio)
if version >= 3:
self.writeRGBA(control_point.color)
else:
self.writeRGB(control_point.color)
def writeMorphGradient(self, gradient):
self.writeUI8(len(gradient.records))
for record in gradient.records:
self.writeUI8(record.start_ratio)
self.writeRGBA(record.start_color)
self.writeUI8(record.end_ratio)
self.writeRGBA(record.end_color)
def writeColorTransformAlpha(self, transform):
has_add_terms = transform.red_add_term != None
has_mult_terms = transform.red_mult_term != None
self.writeUB(has_add_terms, 1)
self.writeUB(has_mult_terms, 1)
self.writeUB(transform.num_bits, 4)
if has_mult_terms:
self.writeSB(transform.red_mult_term, transform.num_bits)
self.writeSB(transform.green_mult_term, transform.num_bits)
self.writeSB(transform.blue_mult_term, transform.num_bits)
self.writeSB(transform.alpha_mult_term, transform.num_bits)
if has_add_terms:
self.writeSB(transform.red_add_term, transform.num_bits)
self.writeSB(transform.green_add_term, transform.num_bits)
self.writeSB(transform.blue_add_term, transform.num_bits)
self.writeSB(transform.alpha_add_term, transform.num_bits)
self.alignToByte()
def writeColorTransform(self, transform):
has_add_terms = transform.red_add_term != None
has_mult_terms = transform.red_mult_term != None
self.writeUB(has_add_terms, 1)
self.writeUB(has_mult_terms, 1)
self.writeUB(transform.num_bits, 4)
if has_mult_terms:
self.writeSB(transform.red_mult_term, transform.num_bits)
self.writeSB(transform.green_mult_term, transform.num_bits)
self.writeSB(transform.blue_mult_term, transform.num_bits)
if has_add_terms:
self.writeSB(transform.red_add_term, transform.num_bits)
self.writeSB(transform.green_add_term, transform.num_bits)
self.writeSB(transform.blue_add_term, transform.num_bits)
self.alignToByte()
def writeMatrix(self, matrix):
if matrix.num_scale_bits != None:
self.writeUB(1, 1);
self.writeUB(matrix.num_scale_bits, 5)
self.writeSB(matrix.scale_x, matrix.num_scale_bits)
self.writeSB(matrix.scale_y, matrix.num_scale_bits)
else:
self.writeUB(0, 1)
if matrix.num_rotate_bits != None:
self.writeUB(1, 1)
self.writeUB(matrix.num_rotate_bits, 5)
self.writeSB(matrix.rotate_skew0, matrix.num_rotate_bits)
self.writeSB(matrix.rotate_skew1, matrix.num_rotate_bits)
else :
self.writeUB(0, 1)
self.writeUB(matrix.num_translate_bits, 5)
self.writeSB(matrix.translate_x, matrix.num_translate_bits)
self.writeSB(matrix.translate_y, matrix.num_translate_bits)
self.alignToByte()
def writeRect(self, rect):
self.writeUB(rect.num_bits, 5)
self.writeSB(rect.left, rect.num_bits)
self.writeSB(rect.right, rect.num_bits)
self.writeSB(rect.top, rect.num_bits)
self.writeSB(rect.bottom, rect.num_bits)
self.alignToByte()
def writeARGB(self, rgb):
self.writeUI8(rgb.alpha)
self.writeUI8(rgb.red)
self.writeUI8(rgb.green)
self.writeUI8(rgb.blue)
def writeRGBA(self, rgb):
self.writeUI8(rgb.red)
self.writeUI8(rgb.green)
self.writeUI8(rgb.blue)
self.writeUI8(rgb.alpha)
def writeRGB(self, rgb):
self.writeUI8(rgb.red)
self.writeUI8(rgb.green)
self.writeUI8(rgb.blue)
def writeEncUI32StringTable(self, table):
self.writeEncUI32(len(table))
for index, string in table.items():
self.writeEncUI32(index)
self.writeString(string)
def writeStringTable(self, table):
self.writeUI16(len(table))
for index, string in table.items():
self.writeUI16(index)
self.writeString(string)
def writeString(self, string):
self.alignToByte()
data = string.encode()
self.writeBytes(data)
self.writeUI8(0)
def alignToByte(self):
if self.bits_remaining > 0:
data = self.ui8.pack((self.bit_buffer >> 24) & 0x000000FF)
self.bits_remaining = 0
self.bit_buffer = 0
self.writeBytes(data)
def writeSB(self, value, num_bits):
if value < 0:
# mask out the upper bits
value &= ~(-1 << num_bits)
self.writeUB(value, num_bits)
def writeUB(self, value, num_bits):
self.bit_buffer |= (value << (32 - num_bits - self.bits_remaining))
self.bits_remaining += num_bits
while self.bits_remaining > 8:
data = self.ui8.pack((self.bit_buffer >> 24) & 0x000000FF)
self.bits_remaining -= 8
self.bit_buffer = ((self.bit_buffer << 8) & (-1 << (32 - self.bits_remaining))) & 0xFFFFFFFF
self.writeBytes(data)
def writeUI8(self, value):
'''Write an unsigned 8 bit integer.
'''
self.alignToByte()
data = self.ui8.pack(value)
self.writeBytes(data)
def writeSI16(self, value):
'''Write an signed 16 bit integer.
'''
self.alignToByte()
data = self.si16.pack(value)
self.writeBytes(data)
def writeUI16(self, value):
'''Write an unsigned 16 bit integer.
'''
self.alignToByte()
data = self.ui16.pack(value)
self.writeBytes(data)
def writeSI32(self, value):
'''Write an signed 32 bit integer.
'''
self.alignToByte()
data = self.si32.pack(value)
self.writeBytes(data)
def writeUI32(self, value):
'''Write an unsigned 32 bit integer.
'''
self.alignToByte()
data = self.ui32.pack(value)
self.writeBytes(data)
def writeEncUI32(self, value):
self.alignToByte()
if value & 0xFFFFFF80 == 0:
data = self.ui8.pack(value)
elif value & 0xFFFFC000 == 0:
data = self.ui8.pack(value & 0x7F | 0x80, (value >> 7) & 0x7F)
elif value & 0xFFE00000 == 0:
data = self.ui8.pack(value & 0x7F | 0x80, (value >> 7) & 0x7F | 0x80, (value >> 14) & 0x7F)
elif value & 0xF0000000 == 0:
data = self.ui8.pack(value & 0x7F | 0x80, (value >> 7) & 0x7F | 0x80, (value >> 14) & 0x7F | 0x80, (value >> 21) & 0x7F)
else:
# the last byte can only have four bits
data = self.ui8.pack(value & 0x7F | 0x80, (value >> 7) & 0x7F | 0x80, (value >> 14) & 0x7F | 0x80, (value >> 21) & 0x7F | 0x80, (value >> 28) & 0x0F);
self.writeBytes(data)
def writeF32(self, value):
'''Write a 32-bit floating point.
'''
self.alignToByte()
data = self.f32.pack(value)
self.writeBytes(data)
def writeF64(self, value):
'''Write a 64-bit floating point.
'''
self.alignToByte()
data = self.f64.pack(value)
self.writeBytes(data)
def writeBytes(self, data):
'''Write a certain number of bytes.
'''
if self.byte_buffer != None:
self.byte_buffer.extend(data)
else:
if self.compressor != None:
data = self.compressor.compress(data)
self.destination.write(data)
def startBuffer(self):
'''Start capturing output contents.
'''
if self.byte_buffer != None:
self.buffer_stack.append(self.byte_buffer)
self.byte_buffer = bytearray()
def endBuffer(self):
'''Stop buffering output and return captured contents.
'''
data = self.byte_buffer;
self.byte_buffer = self.buffer_stack.pop() if len(self.buffer_stack) > 0 else None;
return data
def startCompression(self):
'''Begin compressing data using the zlib algorithm.
'''
self.compressor = compressobj()
def stopCompression(self):
self.alignToByte()
if self.compressor:
data = self.compressor.flush()
self.compressor = None
self.destination.write(data)
| Python |
'''
Created on Jul 21, 2012
@author: Chung Leong
'''
class Generic(object):
code = None
header_length = None
length = None
data = None
class Character(object):
character_id = None
class CSMTextSettings(object):
character_id = None
renderer = None
grid_fit = None
thickness = None
sharpness = None
reserved1 = None
reserved2 = None
class End(object):
pass
class DefineBinaryData(Character):
reserved = None
data = None
swf_file = None
class DefineBits(Character):
image_data = None
class DefineBitsLossless(Character):
format = None
width = None
height = None
color_table_size = None
image_data = None
class DefineBitsLossless2(DefineBitsLossless):
pass
class DefineBitsJPEG2(Character):
image_data = None
class DefineBitsJPEG3(DefineBitsJPEG2):
alpha_data = None
class DefineBitsJPEG4(DefineBitsJPEG3):
deblocking_param = None
class DefineButton(Character):
characters = None
actions = None
class DefineButton2(DefineButton):
flags = None
class DefineButtonCxform(object):
character_id = None
color_transform = None
class DefineButtonSound(object):
character_id = None
over_up_to_idle_id = None
over_up_to_idle_info = None
idle_to_over_up_id = None
idle_to_over_up_info = None
over_up_to_over_down_id = None
over_up_to_over_down_info = None
over_down_to_over_up_id = None
over_down_to_over_up_info = None
class DefineEditText(Character):
bounds = None
flags = None
font_id = None
font_height = None
font_class = None
text_color = None
max_length = None
align = None
left_margin = None
right_margin = None
indent = None
leading = None
variable_name = None
initial_text = None
class DefineFont(Character):
glyph_table = None
class DefineFont2(DefineFont):
flags = None
name = None
ascent = None
descent = None
leading = None
language_code = None
code_table = None
advance_table = None
bound_table = None
kerning_table = None
class DefineFont3(DefineFont2):
pass
class DefineFont4(Character):
flags = None
name = None
cff_data = None
class DefineFontAlignZones(object):
character_id = None
table_hint = None
zone_table = None
class DefineFontInfo(object):
character_id = None
name = None
flags = None
code_table = None
class DefineFontInfo2(DefineFontInfo):
language_code = None
class DefineFontName(object):
character_id = None
name = None
copyright = None
class DefineMorphShape(Character):
start_bounds = None
end_bounds = None
fill_styles = None
line_styles = None
start_edges = None
end_edges = None
class DefineMorphShape2(DefineMorphShape):
flags = None
start_edge_bounds = None
end_edge_bounds = None
class DefineScalingGrid(object):
character_id = None
splitter = None
class DefineSceneAndFrameLabelData(object):
scene_names = None
frame_labels = None
class DefineShape(Character):
shape_bounds = None
shape = None
class DefineShape2(DefineShape):
pass
class DefineShape3(DefineShape2):
pass
class DefineShape4(DefineShape3):
flags = None
edge_bounds = None
class DefineSound(Character):
format = None
sample_size = None
sample_rate = None
type = None
sample_count = None
data = None
class DefineSprite(Character):
frame_count = None
tags = None
class DefineText(Character):
bounds = None
matrix = None
glyph_bits = None
advance_bits = None
text_records = None
class DefineText2(DefineText):
pass
class DefineVideoStream(Character):
frame_count = None
width = None
height = None
flags = None
codec_id = None
class DoABC(object):
flags = None
byte_code_name = None
byte_codes = None
abc_file = None
class DoAction(object):
actions = None
class DoInitAction(object):
character_id = None
actions = None
class EnableDebugger(object):
password = None
class EnableDebugger2(EnableDebugger):
reserved = None
class ExportAssets(object):
names = None
class FileAttributes(object):
flags = None
class FrameLabel(object):
name = None
anchor = None
class ImportAssets(object):
names = None
url = None
class ImportAssets2(ImportAssets):
reserved1 = None
reserved2 = None
class JPEGTables(object):
jpeg_data = None
class Metadata(object):
metadata = None
class PlaceObject(object):
character_id = None
depth = None
matrix = None
color_transform = None
class PlaceObject2(PlaceObject):
flags = None
ratio = None
name = None
clip_depth = None
clip_actions = None
all_events_flags = None
class PlaceObject3(PlaceObject2):
class_name = None
filters = None
blend_mode = None
bitmap_cache = None
bitmap_cache_background_color = None
visibility = None
class Protect(object):
password = None
class RemoveObject(object):
character_id = None
depth = None
class RemoveObject2(object):
depth = None
class ScriptLimits(object):
max_recursion_depth = None
script_timeout_seconds = None
class SetBackgroundColor(object):
color = None
class SetTabIndex(object):
depth = None
tab_index = None
class ShowFrame(object):
pass
class SoundStreamBlock(object):
data = None
class SoundStreamHead(object):
playback_sample_size = None
playback_sample_rate = None
playback_type = None
format = None
sample_size = None
sample_rate = None
type = None
sample_count = None
latency_seek = None
class SoundStreamHead2(SoundStreamHead):
pass
class StartSound(object):
info = None
class StartSound2(object):
class_name = None
info = None
class SymbolClass(object):
names = None
class VideoFrame(object):
stream_id = None
frame_number = None
data = None
class ZoneRecord(object):
zone_data1 = None
zone_data2 = None
flags = None
alignment_coordinate = None
range = None
class KerningRecord(object):
code1 = None
code2 = None
adjustment = None
class DropShadowFilter(object):
shadow_color = None
highlight_color = None
blur_x = None
blur_y = None
angle = None
distance = None
strength = None
flags = None
passes = None
class BlurFilter(object):
blur_x = None
blur_y = None
passes = None
class GlowFilter(object):
color = None
blur_x = None
blur_y = None
strength = None
flags = None
passes = None
class BevelFilter(object):
shadow_color = None
highlight_color = None
blur_x = None
blur_y = None
angle = None
distance = None
strength = None
flags = None
passes = None
class GradientGlowFilter(object):
colors = None
ratios = None
blur_x = None
blur_y = None
angle = None
distance = None
strength = None
flags = None
passes = None
class ConvolutionFilter(object):
matrix_x = None
matrix_y = None
divisor = None
bias = None
matrix = None
default_color = None
flags = None
class ColorMatrixFilter(object):
matrix = None
class GradientBevelFilter(object):
colors = None
ratios = None
blur_x = None
blur_y = None
angle = None
distance = None
strength = None
flags = None
passes = None
class SoundInfo(object):
flags = None
in_point = None
out_point = None
loop_count = None
envelopes = None
class SoundEnvelope(object):
position_44 = None
left_level = None
right_level = None
class ButtonRecord(Character):
flags = None
place_depth = None
matrix = None
color_transform = None
filters = None
blend_mode = None
class ClipAction(object):
event_flags = None
key_code = None
actions = None
class GlyphEntry(object):
index = None
advance = None
class Shape(object):
num_fill_bits = None
num_line_bits = None
edges = None
class ShapeWithStyle(Shape):
line_styles = None
fill_styles = None
class MorphShapeWithStyle(object):
line_styles = None
fill_styles = None
start_num_fill_bits = None
start_num_line_bits = None
end_num_fill_bits = None
end_num_line_bits = None
start_edges = None
end_edges = None
class StraightEdge(object):
num_bits = None
delta_x = None
delta_y = None
class QuadraticCurve(object):
num_bits = None
control_delta_x = None
control_delta_y = None
anchor_delta_x = None
anchor_delta_y = None
class StyleChange(object):
num_move_bits = None
move_delta_x = None
move_delta_y = None
fill_style0 = None
fill_style1 = None
line_style = None
new_fill_styles = None
new_line_styles = None
num_fill_bits = None
num_line_bits = None
class TextRecord(object):
flags = None
font_id = None
text_color = None
x_offset = None
y_offset = None
text_height = None
glyphs = None
class FillStyle(object):
type = None
color = None
gradient_matrix = None
gradient = None
bitmap_id = None
bitmap_matrix = None
class MorphFillStyle(object):
type = None
start_color = None
end_color = None
start_gradient_matrix = None
end_gradient_matrix = None
gradient = None
bitmap_id = None
start_bitmap_matrix = None
end_bitmap_matrix = None
class LineStyle(object):
width = None
color = None
class LineStyle2(object):
width = None
start_cap_style = None
end_cap_style = None
join_style = None
flags = None
miter_limit_factor = None
fill_style = None
style = None
class MorphLineStyle(object):
start_width = None
end_width = None
start_color = None
end_color = None
class Gradient(object):
spread_mode = None
interpolation_mode = None
control_points = None
class FocalGradient(Gradient):
focal_point = None
class GradientControlPoint(object):
ratio = None
color = None
class MorphGradient(object):
records = None
class MorphGradientRecord(object):
start_ratio = None
start_color = None
end_ratio = None
end_color = None
class ColorTransform(object):
num_bits = None
red_mult_term = None
green_mult_term = None
blue_mult_term = None
red_add_term = None
green_add_term = None
blue_add_term = None
class ColorTransformAlpha(ColorTransform):
alpha_mult_term = None
alpha_add_term = None
class Matrix(object):
num_scale_bits = None
scale_x = None
scale_y = None
num_rotate_bits = None
rotate_skew0 = None
rotate_skew1 = None
num_traslate_bits = None
translate_x = None
translate_y = None
class Rect(object):
num_bits = None
left = None
right = None
top = None
bottom = None
class RGBA(object):
red = None
green = None
blue = None
alpha = None
| Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
from gevent.wsgi import WSGIServer
from gis import app
http_server = WSGIServer(('', 5001), app)
http_server.serve_forever() | Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
from flask.ext.sqlalchemy import SQLAlchemy
from gis import app
from datetime import datetime
db = SQLAlchemy(app)
def setnone(v):
if v=='':
return None
else:
return v
def setzero(v):
if v=='':
return 0
else:
return v
class card(db.Model):
__tablename__='card'
card_id = db.Column(db.Integer, primary_key=True)
card_date = db.Column(db.Date, nullable=False)
card_dept = db.Column(db.Text, nullable=False)
card_fibername=db.Column(db.Text, nullable=False)
card_fibercode=db.Column(db.Text, nullable=False)
card_count=db.Column(db.Integer, nullable=False)
card_use=db.Column(db.Text)
card_action=db.Column(db.Text)
card_gis=db.Column(db.Boolean)
card_memo=db.Column(db.Text)
card_fibercore=db.Column(db.Integer)
card_fiberlen=db.Column(db.Integer)
card_source=db.Column(db.Text)
card_update=db.Column(db.DateTime)
card_cardprint=db.Column(db.Boolean)
card_usedate=db.Column(db.Date)
card_userid=db.Column(db.Integer,db.ForeignKey('user.id'))
def __init__(self, card_date, card_dept,card_fibername,card_fibercode,card_count,card_use=None,card_action=None,card_gis=False,card_memo=None,card_fibercore=None,card_fiberlen=None,card_source=None,card_cardprint=False,card_usedate=None):
self.card_date = card_date
self.card_dept = card_dept
self.card_fibername=card_fibername
self.card_fibercode=card_fibercode
self.card_count=card_count
self.card_use=card_use
self.card_action=card_action
self.card_gis=card_gis
self.card_memo=card_memo
self.card_fibercore=card_fibercore
self.card_fiberlen=card_fiberlen
self.card_source=card_source
self.card_update=datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
self.card_cardprint=card_cardprint
self.card_usedate=card_usedate
def __repr__(self):
return '<card %r:%r>' % (self.card_date,self.card_fibername)
ROLE_USER = 0
ROLE_ADMIN = 1
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
nickname = db.Column(db.String(64), index = True, unique = True)
email = db.Column(db.String(120), index = True, unique = True)
role = db.Column(db.SmallInteger, default = ROLE_USER)
cards=db.relationship('card',backref='author',lazy='dynamic')
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % (self.nickname)
| Python |
# -*- coding: utf-8 -*-
import cx_Oracle
con = cx_Oracle.connect('gis/ndtvgis@192.168.20.79/GIS')
# print con.version
cur = con.cursor()
# tegjsbdz 面板端子
# teqy 区域 type=2
# tejz 分前端 zqybm=teqy.bm
# tejf 机房 jflx=1,jzbm=tejz.bm
# tegjjx 光交 jzbm=tejz.bm
# teodf ODF sysm=0,jfbm.tejf.bm 不确定
# 或者 sysm=0,jzbm=tejz.bm
# ODF和机房的关系
# tepnt 的type=87是odf,ztid=tejf.id0
cur.execute("select * from tegjjx gj,tegjsbdz dz where gj.id0='14795' and gj.id0=dz.devid order by dz.mkcol,dz.mkrow,dz.dzcol")
rows=cur.fetchall()
print len(rows)
# for row in rows:
# print row
cur.close()
con.close() | Python |
# -*- coding: utf-8 -*-
import cx_Oracle
con = cx_Oracle.connect('gis/ndtvgis@192.168.20.79/GIS')
print con.version
cursor = con.cursor()
cursor.execute("select * from tegjd where bm=:bm",{'bm':'HS.ZFY/SQY/GJD01'})
rows=cursor.fetchall()
for row in rows:
print row
cursor.execute("select * from tegjd where bm like :bm",{'bm':'HS.ZFY/SQY/GJD%'})
for result in cursor:
print result[0],result[1],result[2]
cursor.close()
con.close() | Python |
# -*- coding: utf-8 -*-
from sqlalchemy import *
from sqlalchemy.sql import select
from sqlalchemy.schema import *
# create the engine for oracle db
# we need to install cx_Oracle and sqlalchemy in advance.
db_engine=create_engine('oracle://gis:ndtvgis@192.168.20.79:1521/GIS', echo=True)
# test the ddl to db
# this is tested in VM and works fine.
# db_engine.execute("create table zy_user(name varchar2(10), address varchar2(50))")
# reflect the table into sqlalchemy
# we should use the meta to do the reflect in version 0.9
meta=MetaData()
t=Table('tegjd',meta,autoload=True,autoload_with=db_engine)
# autoload the keys
# print t.c.keys()
# create the insert script
# ins=t.insert()
# print str(ins)
# check all the column names and do a select to fetch the data directly from table
conn=db_engine.connect()
s=select([t]).where(t.c.bm=='HS.ZFY/SQY/GJD01') # 提供查询条件
result=conn.execute(s)
for row in result:
print row[t.c.id0],row[t.c.mc] # 看这里,直接用t.c.name就可以调用name列的值了,c代表column。不用做映射,不用配置文件,简单到无语吧?...
print row
# remember to close the cursor
result.close() | Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
# SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
DEBUG=True
DEBUG_TOOLBAR=True
SECRET_KEY='development key'
USERNAME='admin'
PASSWORD='default'
CSRF_ENABLED = True
OPENID_PROVIDERS = [
{ 'name':'QQ','url':'https://graph.qq.com/oauth2.0/me'},
{ 'name': 'Google', 'url': 'https://www.google.com/accounts/o8/id' },
{ 'name': 'Yahoo', 'url': 'https://me.yahoo.com' },
{ 'name': 'AOL', 'url': 'http://openid.aol.com/<username>' },
{ 'name': 'Flickr', 'url': 'http://www.flickr.com/<username>' },
{ 'name': 'MyOpenID', 'url': 'https://www.myopenid.com' }]
SQLALCHEMY_DATABASE_URI='postgresql://postgres:ggcall@192.168.20.77/gis'
CARD_FOLDER=os.path.join(basedir, 'static','card')
| Python |
# -*- coding: utf-8 -*-
import os
from flask.ext.openid import OpenID
from config import basedir
__author__ = 'gongqf'
from flask_login import LoginManager
from flask import Flask
from flask_appconfig import AppConfig
from flask_debugtoolbar import DebugToolbarExtension
login_manager = LoginManager()
def create_app(configfile=None):
app = Flask(__name__)
AppConfig(app,configfile)
# app.config.from_object(__name__)
app.config.from_object('config')
# toolbar=DebugToolbarExtension(app)
return app
app=create_app()
login_manager.init_app(app)
login_manager.login_view='login'
oid=OpenID(app,os.path.join(basedir,'tmp'))
import views
| Python |
# -*- coding: utf-8 -*-
__author__ = 'gongqf'
import win32com
from win32com.client import Dispatch, constants
w = win32com.client.Dispatch('Word.Application')
# 或者使用下面的方法,使用启动独立的进程:
# w = win32com.client.DispatchEx('Word.Application')
# 后台运行,不显示,不警告
w.Visible = True
w.DisplayAlerts = True
# 打开新的文件
# doc = w.Documents.Open( FileName = 'new.doc' )
doc = w.Documents.Add() # 创建新的文档
doc.PageSetup.PaperSize = 7 # 纸张大小, A3=6, A4=7
doc.PageSetup.PageWidth = 8.6*28.35 # 直接设置纸张大小, 使用该设置后PaperSize设置取消
doc.PageSetup.PageHeight = 5.49*28.35 # 直接设置纸张大小
doc.PageSetup.Orientation = 1 # 页面方向, 竖直=0, 水平=1
doc.PageSetup.TopMargin = 1*28.35 # 页边距上=3cm,1cm=28.35pt
doc.PageSetup.BottomMargin = 0.3*28.35 # 页边距下=3cm
doc.PageSetup.LeftMargin = 0.3*28.35 # 页边距左=2.5cm
doc.PageSetup.RightMargin = 0.3*28.35 # 页边距右=2.5cm
doc.PageSetup.TextColumns.SetCount(1) # 设置页面
sel = w.Selection # 获取Selection对象
sel.InsertBreak(8) # 插入分栏符=8, 分页符=7
sel.Font.Name = "黑体" # 字体
sel.Font.Size = 24 # 字大
sel.Font.Bold = True # 粗体
sel.Font.Italic = True # 斜体
sel.Font.Underline = True # 下划线
sel.ParagraphFormat.LineSpacing = 2*12 # 设置行距,1行=12磅
sel.ParagraphFormat.Alignment = 1 # 段落对齐,0=左对齐,1=居中,2=右对齐
sel.TypeText("XXXX") # 插入文字
sel.TypeParagraph() # 插入空行
# 注注注注::::ParagraphFormat属性必须使用TypeParagraph()之后才能二次生效!
pic = sel.InlineShapes.AddPicture(r'c:\liantu.png') # 插入图片,缺省嵌入型
# pic.WrapFormat.Type = 0 # 修改文字环绕方式:0=四周型,1=紧密型,3=文字上方,5=文字下方
pic.Borders.OutsideLineStyle = constants.wdLineStyleSingleWavy # 设置图片4边线,1=实线
pic.Borders.OutsideLineWidth = constants.wdLineWidth075pt # 设置边线宽度,对应对话框中数值依次2,4,6,8,12,18,24,36,48
pic.Borders(-1).LineStyle = 1 # -1=上边线,-2=左边线,-3下边线,-4=右边线
pic.Borders(-1).LineWidth = 8 # 依次2,4,6,8,12,18,24,36,48
# 注注注注::::InlineShapes方式插入图片类似于插入字符(嵌入式),Shapes插入图片缺省是浮动的。
tab=doc.Tables.Add(sel.Range, 16, 2) # 增加一个16行2列的表格
tab.Style = "网格型" # 显示表格边框
tab.Columns(1).SetWidth(5*28.35, 0) # 调整第1列宽度,1cm=28.35pt
tab.Columns(2).SetWidth(9*28.35, 0) # 调整第2列宽度
tab.Rows.Alignment = 1 # 表格对齐,0=左对齐,1=居中,2=右对齐
tab.CellCellCellCell(1,1).Range.Text = "xxx" # 填充内容,注意Excel中使用wSheet.Cells(i,j)
sel.MoveDown(5, 16) # 向下移动2行,5=以行为单位
# 注注注注::::插入n行表格之后必须使用MoveDown(5,n)移动到表格之后才能进行其它操作,否则报错!
#
# # 插入文字
# myRange = worddoc.Range(0,0)
# myRange.InsertBefore('Hello from Python!')
#
# # 使用样式
# wordSel = myRange.Select()
# # wordSel.Style = constants.wdStyleHeading1
#
# # 正文文字替换
# w.Selection.Find.ClearFormatting()
# w.Selection.Find.Replacement.ClearFormatting()
# w.Selection.Find.Execute('ello', False, False, False, False, False, True, 1, True, '111', 2)
#
# # 页眉文字替换
# w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
# w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
# w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute('222', False, False, False, False, False, True, 1, False, '223', 2)
#
# # 表格操作
# # worddoc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
# # worddoc.Tables[0].Rows.Add() # 增加一行
#
# # 转换为html
# wc = win32com.client.constants
# w.ActiveDocument.WebOptions.RelyOnCSS = 1
# w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
# w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
# w.ActiveDocument.WebOptions.OrganizeInFolder = 0
# w.ActiveDocument.WebOptions.UseLongFileNames = 1
# w.ActiveDocument.WebOptions.RelyOnVML = 0
# w.ActiveDocument.WebOptions.AllowPNG = 1
# # w.ActiveDocument.SaveAs( FileName = 'c:\\1.html', FileFormat = wc.wdFormatHTML )
#
# # 打印
# # worddoc.PrintOut()
# doc.SaveAs(r'c:\1.doc')
# doc.Close()
# 关闭
# doc.Close()
# w.Documents.Close(wc.wdDoNotSaveChanges)
w.Quit() | Python |
# -*- coding: utf-8 -*-
import cx_Oracle
con = cx_Oracle.connect('gis/ndtvgis@192.168.20.79/GIS')
# print con.version
cursor = con.cursor()
cursor.execute("select sum(gdcd) from tegdd t")
for result in cursor:
print u'统计管道段长度:',result[0]
cursor.execute("select count(*) from tersj")
for result in cursor:
print u'统计人手井数量:',result[0]
cursor.execute("select count(*) from tegjd")
for result in cursor:
print u'统计光节点数量:',result[0]
cursor.execute("SELECT count(*) FROM tegld where id0 in (SELECT glid FROM tegljg group by glid having count(*)>4)")
for result in cursor:
print u'查询有光缆路由的光缆段数量(>4):',result[0]
cursor.close()
con.close() | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.