code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
""" Django settings for final_project project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '42pn5@h7w8=mn4e0g*q1x_3pgerecu7v40ao*n__nnt6fwyf1$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] TEMPLATE_DIRS = ('/home/esraa/Django-1.6.3/final_project/templates', ) # Application definition INSTALLED_APPS = ( 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', 'searchform', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'final_project.urls' WSGI_APPLICATION = 'final_project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'python_project', 'USER': 'root', 'PASSWORD':'root', 'HOST': 'localhost', } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ('/home/esraa/Django-1.6.3/final_project/static/', )
[ [ 8, 0, 0.0521, 0.0938, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.125, 0.0104, 0, 0.66, 0.0526, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 14, 0, 0.1354, 0.0104, 0, 0.66...
[ "\"\"\"\nDjango settings for final_project project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/", "import os", "BASE_DIR = os.path.dirname(os.path.dir...
__author__ = 'esraa' from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class MyRegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user
[ [ 14, 0, 0.05, 0.05, 0, 0.66, 0, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 1, 0, 0.1, 0.05, 0, 0.66, 0.25, 294, 0, 1, 0, 0, 294, 0, 0 ], [ 1, 0, 0.15, 0.05, 0, 0.66, 0.5, ...
[ "__author__ = 'esraa'", "from django import forms", "from django.contrib.auth.models import User", "from django.contrib.auth.forms import UserCreationForm", "class MyRegistrationForm(UserCreationForm):\n email = forms.EmailField(required=True)\n\n class Meta:\n model = User\n fields = ('...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'final_project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^search/', include('search.urls')), url(r'^searchform/', include('searchform.urls')), url(r'^$', 'final_project.views.index'), url(r'^accounts/login/$', 'final_project.views.login'), url(r'^accounts/auth/$', 'final_project.views.auth_view'), url(r'^accounts/logout/$', 'final_project.views.logout'), url(r'^accounts/loggedin/$','final_project.views.loggedin'), url(r'^accounts/invalid/$', 'final_project.views.invalid_login'), url(r'^accounts/register/$', 'final_project.views.register_user'), url(r'^accounts/register_success/$', 'final_project.views.register_success'), #url(r'^search/details/$', 'search.views.details'), #url(r'^login/', include('login.urls')), )
[ [ 1, 0, 0.0323, 0.0323, 0, 0.66, 0, 528, 0, 3, 0, 0, 528, 0, 0 ], [ 1, 0, 0.0968, 0.0323, 0, 0.66, 0.3333, 302, 0, 1, 0, 0, 302, 0, 0 ], [ 8, 0, 0.1935, 0.0323, 0, ...
[ "from django.conf.urls import patterns, include, url", "from django.contrib import admin", "admin.autodiscover()", "urlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'final_project.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.url...
""" WSGI config for final_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "final_project.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
[ [ 8, 0, 0.3214, 0.5714, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.7143, 0.0714, 0, 0.66, 0.25, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 8, 0, 0.7857, 0.0714, 0, 0.66, ...
[ "\"\"\"\nWSGI config for final_project project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/\n\"\"\"", "import os", "os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"fi...
from django.shortcuts import render_to_response from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib import auth from django.core.context_processors import csrf #from forms import MyRegistrationForm from django.contrib.auth.forms import UserCreationForm def index(request): return render(request,'index.html') def login(request): c = {} c.update(csrf(request)) #return render_to_response('login.html',c) return render(request,'login.html',c) def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/accounts/loggedin') else: return HttpResponseRedirect('/accounts/invalid_login') def loggedin(request): return render(request,'loggedin.html', {'full_name' : request.user.username}) #############repeat here################ def invalid_login(request): return render(request,'invalid_login.html') ######################################## def logout(request): auth.logout(request) return render(request,'logout.html') def register_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() #return HttpResponseRedirect('/accounts/register_success') args = {} args.update(csrf(request)) args['form'] = UserCreationForm() print args return render(request,'register.html',args) ''' if request.method == 'POST': form = MyRegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/accounts/register_success') args = {} args.update(csrf(request)) args['form'] = MyRegistrationForm() return render(request,'register.html',args) ''' def register_success(request): return render(request,'register_success.html') #############3and kol render request####################
[ [ 1, 0, 0.0122, 0.0122, 0, 0.66, 0, 852, 0, 1, 0, 0, 852, 0, 0 ], [ 1, 0, 0.0244, 0.0122, 0, 0.66, 0.0769, 852, 0, 1, 0, 0, 852, 0, 0 ], [ 1, 0, 0.0366, 0.0122, 0, ...
[ "from django.shortcuts import render_to_response", "from django.shortcuts import render", "from django.http import HttpResponseRedirect", "from django.contrib import auth", "from django.core.context_processors import csrf", "from django.contrib.auth.forms import UserCreationForm", "def index(request):\n...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "final_project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ [ 1, 0, 0.2, 0.1, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.3, 0.1, 0, 0.66, 0.5, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 4, 0, 0.75, 0.6, 0, 0.66, 1, 0, ...
[ "import os", "import sys", "if __name__ == \"__main__\":\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"final_project.settings\")\n\n from django.core.management import execute_from_command_line\n\n execute_from_command_line(sys.argv)", " os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "final_project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ [ 1, 0, 0.2, 0.1, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.3, 0.1, 0, 0.66, 0.5, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 4, 0, 0.75, 0.6, 0, 0.66, 1, 0, ...
[ "import os", "import sys", "if __name__ == \"__main__\":\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"final_project.settings\")\n\n from django.core.management import execute_from_command_line\n\n execute_from_command_line(sys.argv)", " os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"...
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
[ [ 1, 0, 0.3514, 0.0135, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.3649, 0.0135, 0, 0.66, 0.1111, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.3784, 0.0135, 0, ...
[ "import os", "import re", "import tempfile", "import shutil", "ignore_pattern = re.compile('^(.svn|target|bin|classes)')", "java_pattern = re.compile('^.*\\.java')", "annot_pattern = re.compile('import org\\.apache\\.http\\.annotation\\.')", "def process_dir(dir):\n files = os.listdir(dir)\n for...
#!/usr/bin/python # Copyright 2011 Google, Inc. All Rights Reserved. # simple script to walk source tree looking for third-party licenses # dumps resulting html page to stdout import os, re, mimetypes, sys # read source directories to scan from command line SOURCE = sys.argv[1:] # regex to find /* */ style comment blocks COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) # regex used to detect if comment block is a license COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) EXCLUDE_TYPES = [ "application/xml", "image/png", ] # list of known licenses; keys are derived by stripping all whitespace and # forcing to lowercase to help combine multiple files that have same license. KNOWN_LICENSES = {} class License: def __init__(self, license_text): self.license_text = license_text self.filenames = [] # add filename to the list of files that have the same license text def add_file(self, filename): if filename not in self.filenames: self.filenames.append(filename) LICENSE_KEY = re.compile(r"[^\w]") def find_license(license_text): # TODO(alice): a lot these licenses are almost identical Apache licenses. # Most of them differ in origin/modifications. Consider combining similar # licenses. license_key = LICENSE_KEY.sub("", license_text).lower() if license_key not in KNOWN_LICENSES: KNOWN_LICENSES[license_key] = License(license_text) return KNOWN_LICENSES[license_key] def discover_license(exact_path, filename): # when filename ends with LICENSE, assume applies to filename prefixed if filename.endswith("LICENSE"): with open(exact_path) as file: license_text = file.read() target_filename = filename[:-len("LICENSE")] if target_filename.endswith("."): target_filename = target_filename[:-1] find_license(license_text).add_file(target_filename) return None # try searching for license blocks in raw file mimetype = mimetypes.guess_type(filename) if mimetype in EXCLUDE_TYPES: return None with open(exact_path) as file: raw_file = file.read() # include comments that have both "license" and "copyright" in the text for comment in COMMENT_BLOCK.finditer(raw_file): comment = comment.group(1) if COMMENT_LICENSE.search(comment) is None: continue if COMMENT_COPYRIGHT.search(comment) is None: continue find_license(comment).add_file(filename) for source in SOURCE: for root, dirs, files in os.walk(source): for name in files: discover_license(os.path.join(root, name), name) print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>" for license in KNOWN_LICENSES.values(): print "<h3>Notices for files:</h3><ul>" filenames = license.filenames filenames.sort() for filename in filenames: print "<li>%s</li>" % (filename) print "</ul>" print "<pre>%s</pre>" % license.license_text print "</body></html>"
[ [ 1, 0, 0.0816, 0.0102, 0, 0.66, 0, 688, 0, 4, 0, 0, 688, 0, 0 ], [ 14, 0, 0.1224, 0.0102, 0, 0.66, 0.0714, 792, 6, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1531, 0.0102, 0, ...
[ "import os, re, mimetypes, sys", "SOURCE = sys.argv[1:]", "COMMENT_BLOCK = re.compile(r\"(/\\*.+?\\*/)\", re.MULTILINE | re.DOTALL)", "COMMENT_LICENSE = re.compile(r\"(license)\", re.IGNORECASE)", "COMMENT_COPYRIGHT = re.compile(r\"(copyright)\", re.IGNORECASE)", "EXCLUDE_TYPES = [\n \"application/xml\...
# San Angeles Observation # Original C version Copyright 2004-2005 Jetro Lauha # Web: http://iki.fi/jetro/ # # BSD-license. # # Javascript version by Ken Waters # Skulpt (Python) version by Scott Graham import webgl ShapeParams = [ # m a b n1 n2 n3 m a b n1 n2 n3 res1 res2 scale (org.res1,res2) [10, 1, 2, 90, 1, -45, 8, 1, 1, -1, 1, -0.4 , 20, 30, 2], # 40, 60 [10, 1, 2, 90, 1, -45, 4, 1, 1, 10, 1, -0.4 , 20, 20, 4], # 40, 40 [10, 1, 2, 60, 1, -10, 4, 1, 1, -1, -2, -0.4 , 41, 41, 1], # 82, 82 [ 6, 1, 1, 60, 1, -70, 8, 1, 1, 0.4 , 3, 0.25 , 20, 20, 1], # 40, 40 [ 4, 1, 1, 30, 1, 20, 12, 1, 1, 0.4 , 3, 0.25 , 10, 30, 1], # 20, 60 [ 8, 1, 1, 30, 1, -4, 8, 2, 1, -1, 5, 0.5 , 25, 26, 1], # 60, 60 [13, 1, 1, 30, 1, -4, 13, 1, 1, 1, 5, 1, 30, 30, 6], # 60, 60 [10, 1, 1.1 , -0.5 , 0.1 , 70, 60, 1, 1, -90, 0, -0.25 , 20, 60, 8], # 60, 180 [ 7, 1, 1, 20, -0.3 , -3.5 , 6, 1, 1, -1, 4.5 , 0.5 , 10, 20, 4], # 60, 80 [ 4, 1, 1, 10, 10, 10, 4, 1, 1, 10, 10, 10, 10, 20, 1], # 20, 40 [ 4, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 10, 10, 2], # 10, 10 [ 1, 1, 1, 38, -0.25 , 19, 4, 1, 1, 10, 10, 10, 10, 15, 2], # 20, 40 [ 2, 1, 1, 0.7 , 0.3 , 0.2 , 3, 1, 1, 100, 100, 100, 10, 25, 2], # 20, 50 [ 6, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 30, 30, 2], # 60, 60 [ 3, 1, 1, 1, 1, 1, 6, 1, 1, 2, 1, 1, 10, 20, 2], # 20, 40 [ 6, 1, 1, 6, 5.5 , 100, 6, 1, 1, 25, 10, 10, 30, 20, 2], # 60, 40 [ 3, 1, 1, 0.5 , 1.7 , 1.7 , 2, 1, 1, 10, 10, 10, 20, 20, 2], # 40, 40 [ 5, 1, 1, 0.1 , 1.7 , 1.7 , 1, 1, 1, 0.3 , 0.5 , 0.5 , 20, 20, 4], # 40, 40 [ 2, 1, 1, 6, 5.5 , 100, 6, 1, 1, 4, 10, 10, 10, 22, 1], # 40, 40 [ 6, 1, 1, -1, 70, 0.1 , 9, 1, 0.5 , -98, 0.05 , -45, 20, 30, 4], # 60, 91 [ 6, 1, 1, -1, 90, -0.1 , 7, 1, 1, 90, 1.3 , 34, 13, 16, 1] # 32, 60 ] class CamTrack: def __init__(self, src, dest, dist, len): self.src = src self.dest = dest self.dist = dist self.len = len CamTracks = [ CamTrack([4500, 2700, 100, 70, -30], [50, 50, -90, -100, 0], 20, 1), CamTrack([ -1448, 4294, 25, 363, 0 ], [ -136, 202, 125, -98, 100], 0, 1), CamTrack([ 1437, 4930, 200, -275, -20 ], [ 1684, 0, 0, 9, 0], 0, 1), CamTrack([ 1800, 3609, 200, 0, 675 ], [ 0, 0, 0, 300, 0], 0, 1), CamTrack([ 923, 996, 50, 2336, -80 ], [ 0, -20, -50, 0, 170], 0, 1), CamTrack([ -1663, -43, 600, 2170, 0 ], [ 20, 0, -600, 0, 100], 0, 1), CamTrack([ 1049, -1420, 175, 2111, -17 ], [ 0, 0, 0, -334, 0], 0, 2), CamTrack([ 0, 0, 50, 300, 25 ], [ 0, 0, 0, 300, 0], 70, 2), CamTrack([ -473, -953, 3500, -353, -350 ], [ 0, 0, -2800, 0, 0], 0, 2), CamTrack([ 191, 1938, 35, 1139, -17 ], [ 1205, -2909, 0, 0, 0], 0, 2), CamTrack([ -1449, -2700, 150, 0, 0 ], [ 0, 2000, 0, 0, 0], 0, 2), CamTrack([ 5273, 4992, 650, 373, -50 ], [ -4598, -3072, 0, 0, 0], 0, 2), CamTrack([ 3223, -3282, 1075, -393, -25 ], [ 1649, -1649, 0, 0, 0], 0, 2), ] CAMTRACK_LEN = 5442 FlatVertexSource = """ attribute vec3 pos; attribute vec4 colorIn; uniform mat4 mvp; varying vec4 color; void main() { color = colorIn; gl_Position = mvp * vec4(pos.xyz, 1.); } """ FlatFragmentSource = """ #ifdef GL_ES precision highp float; #endif varying vec4 color; void main() { gl_FragColor = vec4(color.rgb, 1.0); } """ LitVertexSource = """ attribute vec3 pos; attribute vec3 normal; attribute vec4 colorIn; varying vec4 color; uniform mat4 mvp; uniform mat3 normalMatrix; uniform vec4 ambient; uniform float shininess; uniform vec3 light_0_direction; uniform vec4 light_0_diffuse; uniform vec4 light_0_specular; uniform vec3 light_1_direction; uniform vec4 light_1_diffuse; uniform vec3 light_2_direction; uniform vec4 light_2_diffuse; vec3 worldNormal; vec4 SpecularLight(vec3 direction, vec4 diffuseColor, vec4 specularColor) { vec3 lightDir = normalize(direction); float diffuse = max(0., dot(worldNormal, lightDir)); float specular = 0.; if (diffuse > 0.) { vec3 halfv = normalize(lightDir + vec3(0., 0., 1.)); specular = pow(max(0., dot(halfv, worldNormal)), shininess); } return diffuse * diffuseColor * colorIn + specular * specularColor; } vec4 DiffuseLight(vec3 direction, vec4 diffuseColor) { vec3 lightDir = normalize(direction); float diffuse = max(0., dot(worldNormal, lightDir)); return diffuse * diffuseColor * colorIn; } void main() { worldNormal = normalize(normalMatrix * normal); gl_Position = mvp * vec4(pos, 1.); color = ambient * colorIn; color += SpecularLight(light_0_direction, light_0_diffuse, light_0_specular); color += DiffuseLight(light_1_direction, light_1_diffuse); color += DiffuseLight(light_2_direction, light_2_diffuse); } """ FadeVertexSource = """ #ifdef GL_ES precision highp float; #endif attribute vec2 pos; varying vec4 color; uniform float minFade; void main() { color = vec4(minFade, minFade, minFade, 1.); gl_Position = vec4(pos, 0., 1.); } """ class Random: def __init__(self, seed): self.randomSeed = seed def seed(self, seed): self.randomSeed = seed def uInt(self): self.randomSeed = (self.randomSeed * 0x343fd + 0x269ec3) & 0xffffffff return (self.randomSeed >> 16) & 0xfff class GlObject: def __init__(self, gl, shader, vertices, colors, normals=None): self.shader = shader self.count = len(vertices) / 3 self.vbo = gl.createBuffer() vertexArray = gl.Float32Array(vertices) colorArray = gl.Uint8Array(colors) self.vertexOffset = 0 self.colorOffset = vertexArray.byteLength self.normalOffset = self.colorOffset + colorArray.byteLength sizeInBytes = self.normalOffset normalArray = None self.hasNormals = normals != None if normals: normalArray = gl.Float32Array(normals) sizeInBytes += normalArray.byteLength gl.bindBuffer(gl.ARRAY_BUFFER, self.vbo) gl.bufferData(gl.ARRAY_BUFFER, sizeInBytes, gl.STATIC_DRAW) gl.bufferSubData(gl.ARRAY_BUFFER, self.vertexOffset, vertexArray) gl.bufferSubData(gl.ARRAY_BUFFER, self.colorOffset, colorArray) if normals: gl.bufferSubData(gl.ARRAY_BUFFER, self.normalOffset, normalArray) def draw(self): self.shader.use() gl.bindBuffer(gl.ARRAY_BUFFER, self.vbo) gl.vertexAttribPointer(self.shader.posLoc, 3, gl.FLOAT, False, 0, self.vertexOffset) gl.enableVertexAttribArray(self.shader.posLoc) gl.vertexAttribPointer(self.shader.colorInLoc, 4, gl.UNSIGNED_BYTE, True, 0, self.colorOffset) gl.enableVertexAttribArray(self.shader.colorInLoc) if self.hasNormals: gl.vertexAttribPointer(self.shader.normalLoc, 3, gl.FLOAT, False, 0, self.normalOffset) gl.enableVertexAttribArray(self.shader.normalLoc) gl.drawArrays(gl.TRIANGLES, 0, self.count) if self.hasNormals: gl.disableVertexAttribArray(self.shader.normalLoc) gl.disableVertexAttribArray(self.shader.colorInLoc) gl.disableVertexAttribArray(self.shader.posLoc) def createGroundPlane(gl, shader, random): scale = 4 xBegin, xEnd = -15, 15 yBegin, yEnd = -15, 15 triangleCount = (yEnd - yBegin) * (xEnd - xBegin) * 2 colors = [] vertices = [] for y in range(yBegin, yEnd): for x in range(xBegin, xEnd): color = (random.uInt() & 0x4f) + 81 for i in range(6): colors.extend([color, color, color, 0]) for i in range(6): xm = x + ((0x1c >> a) & 1) ym = y + ((0x31 >> a) & 1) m = math.cos(xm * 2) * math.sin(ym * 4) * 0.75 vertices.extend([xm * scale + m, ym * scale + m, 0]) return GlObject(shader, vertices, colors) ground = None fadeVBO = None shapes = None modelview = None projection = None mvp = None normalMatrix = None currentCamTrackStartTick = 0 nextCamTrackStartTick = 0 sTick = 0 currentCamTrack = 0 def main(): global gl, random, modelview, projection, mvp, normalMatrix modelview = webgl.Mat44() projection = webgl.Mat44() mvp = webgl.Mat44() normalMatrix = webgl.Mat33() gl = webgl.GL("canv") gl.enable(gl.DEPTH_TEST) gl.disable(gl.CULL_FACE) random = Random(15) flatShader = webgl.Shader(gl, FlatVertexSource, FlatFragmentSource) litShader = webgl.Shader(gl, LitVertexSource, FlatFragmentSource) fadeShader = webgl.Shader(gl, FadeVertexSource, FlatFragmentSource) # bind non-changing lighting parameters litShader.use() gl.uniform4f(litShader.ambientLoc, .2, .2, .2, 1.) gl.uniform4f(litShader.light_0_diffuseLoc, 1., .4, 0, 1.) gl.uniform4f(litShader.light_1_diffuseLoc, .07, .14, .35, 1.) gl.uniform4f(litShader.light_2_diffuseLoc, .07, .17, .14, 1.) gl.uniform4f(litShader.light_0_specularLoc, 1., 1., 1., 1.) gl.uniform1f(litShader.shininessLoc, 60.) shapes = [createSuperShape(litShader, x) for x in ShapeParams] ground = createGroundPlane(flatShader) def clamp(x, mn=0, mx=255): return max(min(x, mx), mn) def superShapeMap(r1, r2, t, p): return gl.Vec3(math.cos(t) * math.cos(p) / r1 / r2, math.sin(t) * math.cos(p) / r1 / r2, math.sin(p) / r2) def ssFunc(t, p): return pow(pow(abs(cos(p[0] * t / 4)) / p[1], p[4]) + pow(abs(sin(p[0] * t / 4)) / p[2], p[5]), 1.0 / p[3]) def createSuperShape(shader, params): resol1 = params[-3] resol2 = params[-2] # latitude 0 to pi/2 for no mirrored bottom # (latitudeBegin==0 for -pi/2 to pi/2 originally) latitudeBegin = resol2 / 4 latitudeEnd = resol2 / 2 longitudeCount = resol1 vertices = [] colors = [] normals = [] baseColor = [(random.uInt() % 155 + 100) / 255.0 for x in range(3)] currentVertex = 0 for longitude in range(longitudeCount): for latitude in range(latitudeBegin, latitudeEnd): t1 = -math.pi + longitude * 2 * math.pi / resol1 t2 = -math.pi + (longitute + 1) * 2 * math.pi / resol1 p1 = -math.pi / 2 + latitude * 2 * math.pi / resol2 p2 = -math.pi / 2 + (latitude + 1) * 2 * math.pi / resol2 r0 = ssFunc(t1, params) r1 = ssFunc(p1, params[6:]) r2 = ssFunc(t2) r3 = ssFunc(p2, params[6:]) if r0 and r1 and r2 and r3: pa = superShapeMap(r0, r1, t1, p1) pb = superShapeMap(r2, r1, t2, p1) pc = superShapeMap(r2, r3, r2, p2) pd = superShapeMap(r0, r3, t1, p2) # kludge to set lower edge of the object to fixed level if latitude == latitudeBegin + 1: pa.z = pb.z = 0 v1 = pb - pa v2 = pd - pa n = gl.cross(v1, v2) # Pre-normalization of the normals is disabled here because # they will be normalized anyway later due to automatic # normalization (NORMALIZE). It is enabled because the # objects are scaled with scale. # # Note we have to normalize by hand in the shader ca = pa.z + 0.5 for i in range(6): normals.extend([n.x, n.y, n.z]) for i in range(6): colors.append(clamp(ca * baseColor[0] * 255)) colors.append(clamp(ca * baseColor[1] * 255)) colors.append(clamp(ca * baseColor[2] * 255)) colors.append(0) vertices.extend([pa.x, pa.y, pa.z]) vertices.extend([pb.x, pb.y, pb.z]) vertices.extend([pd.x, pd.y, pd.z]) vertices.extend([pb.x, pb.y, pb.z]) vertices.extend([pc.x, pc.y, pc.z]) vertices.extend([pd.x, pd.y, pd.z]) return GlObject(gl, shader, vertices, colors, normals) def configureLightAndMaterial(): l0 = modelview.transform3(Vec3(-4., 1., 1.)) l1 = modelview.transform3(Vec3(1., -2., -1.)) l2 = modelview.transform3(Vec3(-1., 0., -4.)) litShader.use() gl.uniform3f(litShader.light_0_directionLoc, l0.x, l0.y, l0.z) gl.uniform3f(litShader.light_1_directionLoc, l1.x, l1.y, l1.z) gl.uniform3f(litShader.light_2_directionLoc, l2.x, l2.y, l2.z) def drawModels(zScale): translationScale = 9 modelview.scale(1, 1, zScale) random.seed(9) for y in range(-5, 5): for x in range(-5, 5): curShape = random.uInt() % len(ShapeParams) buildingScale = ShapeParams[curShape][-1] modelview.push() modelview.translate(x * translationScale, y * translationScale, 0) rv = random.uInt() % 360 modelview.rotate(-rv, 0, 0, 1) modelview.scale(buildingScale, buildingScale, buildingScale) shapes[curShape].draw() modelview.pop() ship = shapes[-1] for x in range(-2, 2): shipScale100 = translationScale * 500 offs100 = x * shipScale100 + (sTick % shipScale100) offs = 0.01 * offs100 modelview.push() modelview.translate(offs, -4.0, 2.0) ship.draw() modelview.pop() modelview.push() modelview.translate(-4., offs, 4.) modelview.rotate(-90., 0., 0., 1.) ship.draw() modelview.pop() def camTrack(): nextCamTrackStartTick = currentCamTrackStartTick + CamTracks[currentCamTrack].len * CAMTRACK_LEN while nextCamTrackStartTick <= sTick: ++currentCamTrack if currentCamTrack >= len(CamTracks): currentCamTrack = 0 currentCamTrackStartTick = nextCamTrackStartTick nextCamTrackStartTick = currentCamTrackStartTick + CamTracks[currentCamTrack].len * CAMTRACK_LEN cam = CamTracks[currentCamTrack] currentCamTick = sTick - currentCamTrackStartTick trackPos = currentCamTick / (CAMTRACK_LEN * cam.len) lerp = [0.01 * cam.src[a] + cam.dest[a] * trackPos for a in range(5)] if cam.dist: dist = cam.dist * 0.1 cX = lerp[0] cY = lerp[1] cZ = lerp[2] eX = cX - math.cos(lerp[3]) * dist eY = cY - math.sin(lerp[3]) * dist eZ = cZ - lerp[4] else: eX = lerp[0] eY = lerp[1] eZ = lerp[2] cX = eX + math.cos(lerp[3]) cY = eY + math.sin(lerp[3]) cZ = eZ + lerp[4] modelview.lookAt(eX, eY, eZ, cX, cY, cZ, 0, 0, 1) def drawGroundPlane(): gl.disable(gl.CULL_FACE) gl.disable(gl.DEPTH_TEST) gl.enable(gl.BLEND) gl.blendFunc(gl.ZERO, gl.SRC_COLOR) ground.draw() gl.disable(gl.BLEND) gl.enable(gl.DEPTH_TEST) def drawFadeQuad(): global fadeVBO if not fadeVBO: vertices = gl.Float32Array([ -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1]) fadeVBO = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, fadeVBO) gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW) beginFade = sTick - currentCamTrackStartTick endFade = nextCamTrackStartTick - sTick minFade = min(beginFade, endFade) if minFade < 1024: gl.disable(gl.DEPTH_TEST) gl.enable(gl.BLEND) gl.blendFunc(gl.ZERO, gl.SRC_COLOR) fadeShader.use() gl.uniform1f(fadeShader.minFadeLoc, minFade / 1024.0) gl.bindBuffer(gl.ARRAY_BUFFER, fadeVBO) gl.vertexAttribPointer(fadeShader.posLoc, 2, gl.FLOAT, false, 0, 0) gl.enableVertexAttribArray(fadeShader.posLoc) gl.drawArrays(gl.TRIANGLES, 0, 6) gl.disableVertexAttribArray(fadeShader.posLoc) gl.disable(gl.BLEND) gl.enable(gl.DEPTH_TEST) def draw(gl, width, height): sTick = (sTick + tick) / 2 gl.clearColor(0.1, 0.2, 0.3, 1.0) gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT) projection.loadIdentity() projection.perspective(45, width / height, 0.5, 100) modelview.loadIdentity() camTrack() configureLightAndMaterial() modelview.push() drawModels(-1) modelview.pop() drawGroundPlane() drawModels(1) drawFadeQuad() main()
[ [ 1, 0, 0.02, 0.002, 0, 0.66, 0, 201, 0, 1, 0, 0, 201, 0, 0 ], [ 14, 0, 0.047, 0.048, 0, 0.66, 0.0294, 183, 0, 0, 0, 0, 0, 5, 0 ], [ 3, 0, 0.081, 0.012, 0, 0.66, ...
[ "import webgl", "ShapeParams = [\n # m a b n1 n2 n3 m a b n1 n2 n3 res1 res2 scale (org.res1,res2)\n [10, 1, 2, 90, 1, -45, 8, 1, 1, -1, 1, -0.4 , 20, 30, 2], # 40, 60\n [10, 1, 2, 90, 1, -45, 4, 1, 1, ...
# JSLint doesn't allow/support disabling the requirement for braces around # blocks, and that's one uglification I refuse to perform in the service of a # lint. # # There are of course lots of other intelligent things JSLint has to say # because it's just too easy in JS to do something that (e.g.) IE won't like. # So, this dumb script filters out any output messages from running JSLint # that look like they're complaints about '{' around braces. # # Also, takes an optional file describing the line mapping from the source # files to the combined distribution file, and outputs error messages in a # format suitable for vim (or whatever) pointing back to the source file. from subprocess import Popen, PIPE import sys import re def remapError(linestarts, line, col, err): if len(linestarts) == 0: # none supplied on command line return "%s:%d:%d: %s" % (sys.argv[1], line, col - 1, err) for i in range(len(linestarts)): if line > linestarts[i][0] and (i + 1 == len(linestarts) or (line <= linestarts[i + 1][0])): return "%s:%d:%d: %s" % (linestarts[i][1], line - linestarts[i][0], col - 1, err) raise Exception("Couldn't remap error!\n%s\n%s\n%s\n%s" % (linestarts, line, col, err)) def main(): p = Popen("support/d8/d8 support/jslint/fulljslint.js support/jslint/d8.js -- %s" % sys.argv[1], shell=True, stdout=PIPE) linestarts = [] if len(sys.argv) > 2: linemaps = open(sys.argv[2]).read().split("\n") for l in linemaps: if len(l.strip()) == 0: continue start, fn = l.split(":") linestarts.append((int(start), fn)) out, err = p.communicate() result = [] report = [] skip = 0 mode = 'errors' for line in out.split("\n"): if line == "---REPORT": mode = 'report' continue if mode == "report": report.append(line) else: if skip > 0: skip -= 1 else: if re.search(r"^.*Expected '{' and instead saw.*", line): skip = 2 else: m = re.search("^Lint at line (\d+) character (\d+): (.*)$", line) if m: result.append(remapError(linestarts, int(m.group(1)), int(m.group(2)), m.group(3))) else: if line.strip() != "": result.append(line) if len(result) > 0: print '\n'.join(result) sys.exit(p.returncode) #open("dist/report.html", "w").write('\n'.join(report)) sys.exit(0) if __name__ == "__main__": main()
[ [ 1, 0, 0.1818, 0.013, 0, 0.66, 0, 394, 0, 2, 0, 0, 394, 0, 0 ], [ 1, 0, 0.1948, 0.013, 0, 0.66, 0.2, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.2078, 0.013, 0, 0.66, ...
[ "from subprocess import Popen, PIPE", "import sys", "import re", "def remapError(linestarts, line, col, err):\n if len(linestarts) == 0:\n # none supplied on command line\n return \"%s:%d:%d: %s\" % (sys.argv[1], line, col - 1, err)\n\n for i in range(len(linestarts)):\n if line > l...
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Pgen imports import grammar, token, tokenize class PgenGrammar(grammar.Grammar): pass class ParserGenerator(object): def __init__(self, filename, stream=None): close_stream = None if stream is None: stream = open(filename) close_stream = stream.close self.filename = filename self.stream = stream self.generator = tokenize.generate_tokens(stream.readline) self.gettoken() # Initialize lookahead self.dfas, self.startsymbol = self.parse() if close_stream is not None: close_stream() self.first = {} # map from symbol name to set of tokens self.addfirstsets() def make_grammar(self): c = PgenGrammar() names = list(self.dfas.keys()) names.sort() names.remove(self.startsymbol) names.insert(0, self.startsymbol) for name in names: i = 256 + len(c.symbol2number) c.symbol2number[name] = i c.number2symbol[i] = name for name in names: dfa = self.dfas[name] states = [] for state in dfa: arcs = [] for label, next in state.arcs.items(): arcs.append((self.make_label(c, label), dfa.index(next))) if state.isfinal: arcs.append((0, dfa.index(state))) states.append(arcs) c.states.append(states) c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name)) c.start = c.symbol2number[self.startsymbol] return c def make_first(self, c, name): rawfirst = self.first[name] first = {} for label in rawfirst: ilabel = self.make_label(c, label) ##assert ilabel not in first # XXX failed on <> ... != first[ilabel] = 1 return first def make_label(self, c, label): # XXX Maybe this should be a method on a subclass of converter? ilabel = len(c.labels) if label[0].isalpha(): # Either a symbol name or a named token if label in c.symbol2number: # A symbol name (a non-terminal) if label in c.symbol2label: return c.symbol2label[label] else: c.labels.append((c.symbol2number[label], None)) c.symbol2label[label] = ilabel return ilabel else: # A named token (NAME, NUMBER, STRING) itoken = getattr(token, label, None) assert isinstance(itoken, int), label assert itoken in token.tok_name, label if itoken in c.tokens: return c.tokens[itoken] else: c.labels.append((itoken, None)) c.tokens[itoken] = ilabel return ilabel else: # Either a keyword or an operator assert label[0] in ('"', "'"), label value = eval(label) if value[0].isalpha(): # A keyword if value in c.keywords: return c.keywords[value] else: c.labels.append((token.NAME, value)) c.keywords[value] = ilabel return ilabel else: # An operator (any non-numeric token) itoken = grammar.opmap[value] # Fails if unknown token if itoken in c.tokens: return c.tokens[itoken] else: c.labels.append((itoken, None)) c.tokens[itoken] = ilabel return ilabel def addfirstsets(self): names = list(self.dfas.keys()) names.sort() for name in names: if name not in self.first: self.calcfirst(name) #print name, self.first[name].keys() def calcfirst(self, name): dfa = self.dfas[name] self.first[name] = None # dummy to detect left recursion state = dfa[0] totalset = {} overlapcheck = {} for label, next in state.arcs.items(): if label in self.dfas: if label in self.first: fset = self.first[label] if fset is None: raise ValueError("recursion for rule %r" % name) else: self.calcfirst(label) fset = self.first[label] totalset.update(fset) overlapcheck[label] = fset else: totalset[label] = 1 overlapcheck[label] = {label: 1} inverse = {} for label, itsfirst in overlapcheck.items(): for symbol in itsfirst: if symbol in inverse: raise ValueError("rule %s is ambiguous; %s is in the" " first sets of %s as well as %s" % (name, symbol, label, inverse[symbol])) inverse[symbol] = label self.first[name] = totalset def parse(self): dfas = {} startsymbol = None # MSTART: (NEWLINE | RULE)* ENDMARKER while self.type != token.ENDMARKER: while self.type == token.NEWLINE: self.gettoken() # RULE: NAME ':' RHS NEWLINE name = self.expect(token.NAME) self.expect(token.OP, ":") a, z = self.parse_rhs() self.expect(token.NEWLINE) #self.dump_nfa(name, a, z) dfa = self.make_dfa(a, z) #self.dump_dfa(name, dfa) oldlen = len(dfa) self.simplify_dfa(dfa) newlen = len(dfa) dfas[name] = dfa #print name, oldlen, newlen if startsymbol is None: startsymbol = name return dfas, startsymbol def make_dfa(self, start, finish): # To turn an NFA into a DFA, we define the states of the DFA # to correspond to *sets* of states of the NFA. Then do some # state reduction. Let's represent sets as dicts with 1 for # values. assert isinstance(start, NFAState) assert isinstance(finish, NFAState) def closure(state): base = {} addclosure(state, base) return base def addclosure(state, base): assert isinstance(state, NFAState) if state in base: return base[state] = 1 for label, next in state.arcs: if label is None: addclosure(next, base) states = [DFAState(closure(start), finish)] for state in states: # NB states grows while we're iterating arcs = {} for nfastate in state.nfaset: for label, next in nfastate.arcs: if label is not None: addclosure(next, arcs.setdefault(label, {})) for label, nfaset in arcs.items(): for st in states: if st.nfaset == nfaset: break else: st = DFAState(nfaset, finish) states.append(st) state.addarc(st, label) return states # List of DFAState instances; first one is start def dump_nfa(self, name, start, finish): print("Dump of NFA for", name) todo = [start] for i, state in enumerate(todo): print(" State", i, state is finish and "(final)" or "") for label, next in state.arcs: if next in todo: j = todo.index(next) else: j = len(todo) todo.append(next) if label is None: print(" -> %d" % j) else: print(" %s -> %d" % (label, j)) def dump_dfa(self, name, dfa): print("Dump of DFA for", name) for i, state in enumerate(dfa): print(" State", i, state.isfinal and "(final)" or "") for label, next in state.arcs.items(): print(" %s -> %d" % (label, dfa.index(next))) def simplify_dfa(self, dfa): # This is not theoretically optimal, but works well enough. # Algorithm: repeatedly look for two states that have the same # set of arcs (same labels pointing to the same nodes) and # unify them, until things stop changing. # dfa is a list of DFAState instances changes = True while changes: changes = False for i, state_i in enumerate(dfa): for j in range(i+1, len(dfa)): state_j = dfa[j] if state_i == state_j: #print " unify", i, j del dfa[j] for state in dfa: state.unifystate(state_j, state_i) changes = True break def parse_rhs(self): # RHS: ALT ('|' ALT)* a, z = self.parse_alt() if self.value != "|": return a, z else: aa = NFAState() zz = NFAState() aa.addarc(a) z.addarc(zz) while self.value == "|": self.gettoken() a, z = self.parse_alt() aa.addarc(a) z.addarc(zz) return aa, zz def parse_alt(self): # ALT: ITEM+ a, b = self.parse_item() while (self.value in ("(", "[") or self.type in (token.NAME, token.STRING)): c, d = self.parse_item() b.addarc(c) b = d return a, b def parse_item(self): # ITEM: '[' RHS ']' | ATOM ['+' | '*'] if self.value == "[": self.gettoken() a, z = self.parse_rhs() self.expect(token.OP, "]") a.addarc(z) return a, z else: a, z = self.parse_atom() value = self.value if value not in ("+", "*"): return a, z self.gettoken() z.addarc(a) if value == "+": return a, z else: return a, a def parse_atom(self): # ATOM: '(' RHS ')' | NAME | STRING if self.value == "(": self.gettoken() a, z = self.parse_rhs() self.expect(token.OP, ")") return a, z elif self.type in (token.NAME, token.STRING): a = NFAState() z = NFAState() a.addarc(z, self.value) self.gettoken() return a, z else: self.raise_error("expected (...) or NAME or STRING, got %s/%s", self.type, self.value) def expect(self, type, value=None): if self.type != type or (value is not None and self.value != value): self.raise_error("expected %s/%s, got %s/%s", type, value, self.type, self.value) value = self.value self.gettoken() return value def gettoken(self): tup = next(self.generator) while tup[0] in (tokenize.COMMENT, tokenize.NL): tup = next(self.generator) self.type, self.value, self.begin, self.end, self.line = tup #print token.tok_name[self.type], repr(self.value) def raise_error(self, msg, *args): if args: try: msg = msg % args except: msg = " ".join([msg] + list(map(str, args))) raise SyntaxError(msg, (self.filename, self.end[0], self.end[1], self.line)) class NFAState(object): def __init__(self): self.arcs = [] # list of (label, NFAState) pairs def addarc(self, next, label=None): assert label is None or isinstance(label, str) assert isinstance(next, NFAState) self.arcs.append((label, next)) class DFAState(object): def __init__(self, nfaset, final): assert isinstance(nfaset, dict) assert isinstance(next(iter(nfaset)), NFAState) assert isinstance(final, NFAState) self.nfaset = nfaset self.isfinal = final in nfaset self.arcs = {} # map from label to DFAState def addarc(self, next, label): assert isinstance(label, str) assert label not in self.arcs assert isinstance(next, DFAState) self.arcs[label] = next def unifystate(self, old, new): for label, next in self.arcs.items(): if next is old: self.arcs[label] = new def __eq__(self, other): # Equality test -- ignore the nfaset instance variable assert isinstance(other, DFAState) if self.isfinal != other.isfinal: return False # Can't just return self.arcs == other.arcs, because that # would invoke this method recursively, with cycles... if len(self.arcs) != len(other.arcs): return False for label, next in self.arcs.items(): if next is not other.arcs.get(label): return False return True def generate_grammar(filename="Grammar.txt"): p = ParserGenerator(filename) return p.make_grammar()
[ [ 1, 0, 0.013, 0.0026, 0, 0.66, 0, 260, 0, 3, 0, 0, 260, 0, 0 ], [ 3, 0, 0.0195, 0.0052, 0, 0.66, 0.2, 344, 0, 0, 0, 0, 407, 0, 0 ], [ 3, 0, 0.4492, 0.849, 0, 0.66,...
[ "import grammar, token, tokenize", "class PgenGrammar(grammar.Grammar):\n pass", "class ParserGenerator(object):\n\n def __init__(self, filename, stream=None):\n close_stream = None\n if stream is None:\n stream = open(filename)\n close_stream = stream.close\n se...
#! /usr/bin/env python """Token constants (from "token.h").""" # Taken from Python (r53757) and modified to include some tokens # originally monkeypatched in by pgen2.tokenize #--start constants-- ENDMARKER = 0 NAME = 1 NUMBER = 2 STRING = 3 NEWLINE = 4 INDENT = 5 DEDENT = 6 LPAR = 7 RPAR = 8 LSQB = 9 RSQB = 10 COLON = 11 COMMA = 12 SEMI = 13 PLUS = 14 MINUS = 15 STAR = 16 SLASH = 17 VBAR = 18 AMPER = 19 LESS = 20 GREATER = 21 EQUAL = 22 DOT = 23 PERCENT = 24 BACKQUOTE = 25 LBRACE = 26 RBRACE = 27 EQEQUAL = 28 NOTEQUAL = 29 LESSEQUAL = 30 GREATEREQUAL = 31 TILDE = 32 CIRCUMFLEX = 33 LEFTSHIFT = 34 RIGHTSHIFT = 35 DOUBLESTAR = 36 PLUSEQUAL = 37 MINEQUAL = 38 STAREQUAL = 39 SLASHEQUAL = 40 PERCENTEQUAL = 41 AMPEREQUAL = 42 VBAREQUAL = 43 CIRCUMFLEXEQUAL = 44 LEFTSHIFTEQUAL = 45 RIGHTSHIFTEQUAL = 46 DOUBLESTAREQUAL = 47 DOUBLESLASH = 48 DOUBLESLASHEQUAL = 49 AT = 50 OP = 51 COMMENT = 52 NL = 53 RARROW = 54 ERRORTOKEN = 55 N_TOKENS = 56 NT_OFFSET = 256 #--end constants-- tok_name = {} for _name, _value in list(globals().items()): if type(_value) is type(0): tok_name[_value] = _name def ISTERMINAL(x): return x < NT_OFFSET def ISNONTERMINAL(x): return x >= NT_OFFSET def ISEOF(x): return x == ENDMARKER
[ [ 8, 0, 0.0366, 0.0122, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1098, 0.0122, 0, 0.66, 0.0159, 977, 1, 0, 0, 0, 0, 1, 0 ], [ 14, 0, 0.122, 0.0122, 0, 0.66,...
[ "\"\"\"Token constants (from \"token.h\").\"\"\"", "ENDMARKER = 0", "NAME = 1", "NUMBER = 2", "STRING = 3", "NEWLINE = 4", "INDENT = 5", "DEDENT = 6", "LPAR = 7", "RPAR = 8", "LSQB = 9", "RSQB = 10", "COLON = 11", "COMMA = 12", "SEMI = 13", "PLUS = 14", "MINUS = 15", "STAR = 16", ...
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. # All rights reserved. """Tokenization help for Python programs. generate_tokens(readline) is a generator that breaks a stream of text into Python tokens. It accepts a readline-like method which is called repeatedly to get the next line of input (or "" for EOF). It generates 5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string) It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators Older entry points tokenize_loop(readline, tokeneater) tokenize(readline, tokeneater=printtoken) are the same, except instead of generating tokens, tokeneater is a callback function to which the 5 fields described above are passed as 5 arguments, each time a new token is found.""" __author__ = 'Ka-Ping Yee <ping@lfw.org>' __credits__ = \ 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro' import string, re from codecs import BOM_UTF8, lookup from lib2to3.pgen2.token import * import token __all__ = [x for x in dir(token) if x[0] != '_'] + ["tokenize", "generate_tokens", "untokenize"] del token def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' Whitespace = r'[ \f\t]*' Comment = r'#[^\r\n]*' Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) Name = r'[a-zA-Z_]\w*' Binnumber = r'0[bB][01]*' Hexnumber = r'0[xX][\da-fA-F]*[lL]?' Octnumber = r'0[oO]?[0-7]*[lL]?' Decnumber = r'[1-9]\d*[lL]?' Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber) Exponent = r'[eE][-+]?\d+' Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent) Expfloat = r'\d+' + Exponent Floatnumber = group(Pointfloat, Expfloat) Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]') Number = group(Imagnumber, Floatnumber, Intnumber) # Tail end of ' string. Single = r"[^'\\]*(?:\\.[^'\\]*)*'" # Tail end of " string. Double = r'[^"\\]*(?:\\.[^"\\]*)*"' # Tail end of ''' string. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" # Tail end of """ string. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' Triple = group("[ubUB]?[rR]?'''", '[ubUB]?[rR]?"""') # Single-line ' or " string. String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'", r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", r"//=?", r"->", r"[+\-*/%&|^=<>]=?", r"~") Bracket = '[][(){}]' Special = group(r'\r?\n', r'[:;.,`@]') Funny = group(Operator, Bracket, Special) PlainToken = group(Number, Funny, String, Name) Token = Ignore + PlainToken # First (or only) line of ' or " string. ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\\\r?\n'), r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + group('"', r'\\\r?\n')) PseudoExtras = group(r'\\\r?\n', Comment, Triple) PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) tokenprog, pseudoprog, single3prog, double3prog = list(map( re.compile, (Token, PseudoToken, Single3, Double3))) endprogs = {"'": re.compile(Single), '"': re.compile(Double), "'''": single3prog, '"""': double3prog, "r'''": single3prog, 'r"""': double3prog, "u'''": single3prog, 'u"""': double3prog, "b'''": single3prog, 'b"""': double3prog, "ur'''": single3prog, 'ur"""': double3prog, "br'''": single3prog, 'br"""': double3prog, "R'''": single3prog, 'R"""': double3prog, "U'''": single3prog, 'U"""': double3prog, "B'''": single3prog, 'B"""': double3prog, "uR'''": single3prog, 'uR"""': double3prog, "Ur'''": single3prog, 'Ur"""': double3prog, "UR'''": single3prog, 'UR"""': double3prog, "bR'''": single3prog, 'bR"""': double3prog, "Br'''": single3prog, 'Br"""': double3prog, "BR'''": single3prog, 'BR"""': double3prog, 'r': None, 'R': None, 'u': None, 'U': None, 'b': None, 'B': None} triple_quoted = {} for t in ("'''", '"""', "r'''", 'r"""', "R'''", 'R"""', "u'''", 'u"""', "U'''", 'U"""', "b'''", 'b"""', "B'''", 'B"""', "ur'''", 'ur"""', "Ur'''", 'Ur"""', "uR'''", 'uR"""', "UR'''", 'UR"""', "br'''", 'br"""', "Br'''", 'Br"""', "bR'''", 'bR"""', "BR'''", 'BR"""',): triple_quoted[t] = t single_quoted = {} for t in ("'", '"', "r'", 'r"', "R'", 'R"', "u'", 'u"', "U'", 'U"', "b'", 'b"', "B'", 'B"', "ur'", 'ur"', "Ur'", 'Ur"', "uR'", 'uR"', "UR'", 'UR"', "br'", 'br"', "Br'", 'Br"', "bR'", 'bR"', "BR'", 'BR"', ): single_quoted[t] = t tabsize = 8 class TokenError(Exception): pass class StopTokenizing(Exception): pass def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing (srow, scol) = xxx_todo_changeme (erow, ecol) = xxx_todo_changeme1 print("%d,%d-%d,%d:\t%s\t%s" % \ (srow, scol, erow, ecol, tok_name[type], repr(token))) def tokenize(readline, tokeneater=printtoken): """ The tokenize() function accepts two parameters: one representing the input stream, and one providing an output mechanism for tokenize(). The first parameter, readline, must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. The second parameter, tokeneater, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by generate_tokens(). """ try: tokenize_loop(readline, tokeneater) except StopTokenizing: pass # backwards compatible interface def tokenize_loop(readline, tokeneater): for token_info in generate_tokens(readline): tokeneater(*token_info) class Untokenizer: def __init__(self): self.tokens = [] self.prev_row = 1 self.prev_col = 0 def add_whitespace(self, start): row, col = start assert row <= self.prev_row col_offset = col - self.prev_col if col_offset: self.tokens.append(" " * col_offset) def untokenize(self, iterable): for t in iterable: if len(t) == 2: self.compat(t, iterable) break tok_type, token, start, end, line = t self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_col = end if tok_type in (NEWLINE, NL): self.prev_row += 1 self.prev_col = 0 return "".join(self.tokens) def compat(self, token, iterable): startline = False indents = [] toks_append = self.tokens.append toknum, tokval = token if toknum in (NAME, NUMBER): tokval += ' ' if toknum in (NEWLINE, NL): startline = True for tok in iterable: toknum, tokval = tok[:2] if toknum in (NAME, NUMBER): tokval += ' ' if toknum == INDENT: indents.append(tokval) continue elif toknum == DEDENT: indents.pop() continue elif toknum in (NEWLINE, NL): startline = True elif startline and indents: toks_append(indents[-1]) startline = False toks_append(tokval) cookie_re = re.compile("coding[:=]\s*([-\w.]+)") def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argment, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. If no encoding is specified, then the default of 'utf-8' will be returned. """ bom_found = False encoding = None def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: line_string = line.decode('ascii') except UnicodeDecodeError: return None matches = cookie_re.findall(line_string) if not matches: return None encoding = matches[0] try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError("unknown encoding: " + encoding) if bom_found and codec.name != 'utf-8': # This behaviour mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] if not first: return 'utf-8', [] encoding = find_cookie(first) if encoding: return encoding, [first] second = read_or_stop() if not second: return 'utf-8', [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return 'utf-8', [first, second] def untokenize(iterable): """Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tokin generate_tokens(readline)] assert t1 == t2 """ ut = Untokenizer() return ut.untokenize(iterable) def generate_tokens(readline): """ The generate_tokens() generator requires one argment, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. """ lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + '_', '0123456789' contstr, needcont = '', 0 contline = None indents = [0] while 1: # loop over lines in stream try: line = readline() except StopIteration: line = '' lnum = lnum + 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError("EOF in multi-line string", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column = column + 1 elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize elif line[pos] == '\f': column = 0 else: break pos = pos + 1 if pos == max: break if line[pos] in '#\r\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\r\n') nl_pos = pos + len(comment_token) yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( "unindent does not match any outer indentation level", ("<tokenize>", lnum, pos, line)) indents = indents[:-1] yield (DEDENT, '', (lnum, pos), (lnum, pos), line) else: # continued statement if not line: raise TokenError("EOF in multi-line statement", (lnum, 0)) continued = 0 while pos < max: pseudomatch = pseudoprog.match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end token, initial = line[start:end], line[start] if initial in numchars or \ (initial == '.' and token != '.'): # ordinary number yield (NUMBER, token, spos, epos, line) elif initial in '\r\n': newline = NEWLINE if parenlev > 0: newline = NL yield (newline, token, spos, epos, line) elif initial == '#': assert not token.endswith("\n") yield (COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = endprogs[token] endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield (STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break elif initial in single_quoted or \ token[:2] in single_quoted or \ token[:3] in single_quoted: if token[-1] == '\n': # continued string strstart = (lnum, start) endprog = (endprogs[initial] or endprogs[token[1]] or endprogs[token[2]]) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield (STRING, token, spos, epos, line) elif initial in namechars: # ordinary name yield (NAME, token, spos, epos, line) elif initial == '\\': # continued stmt # This yield is new; needed for better idempotency: yield (NL, token, spos, (lnum, pos), line) continued = 1 else: if initial in '([{': parenlev = parenlev + 1 elif initial in ')]}': parenlev = parenlev - 1 yield (OP, token, spos, epos, line) else: yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line) pos = pos + 1 for indent in indents[1:]: # pop remaining indent levels yield (DEDENT, '', (lnum, 0), (lnum, 0), '') yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') if __name__ == '__main__': # testing import sys if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) else: tokenize(sys.stdin.readline)
[ [ 8, 0, 0.0314, 0.0482, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.0587, 0.0021, 0, 0.66, 0.0172, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.0618, 0.0042, 0, 0.66...
[ "\"\"\"Tokenization help for Python programs.\n\ngenerate_tokens(readline) is a generator that breaks a stream of\ntext into Python tokens. It accepts a readline-like method which is called\nrepeatedly to get the next line of input (or \"\" for EOF). It generates\n5-tuples with these members:\n\n the token typ...
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """This module defines the data structures used to represent a grammar. These are a bit arcane because they are derived from the data structures used by Python's 'pgen' parser generator. There's also a table here mapping operators to their names in the token module; the Python tokenize module reports all operators as the fallback token code OP, but the parser needs the actual token code. """ # Python imports import pickle # Local imports import token, tokenize class Grammar(object): """Pgen parsing tables tables conversion class. Once initialized, this class supplies the grammar tables for the parsing engine implemented by parse.py. The parsing engine accesses the instance variables directly. The class here does not provide initialization of the tables; several subclasses exist to do this (see the conv and pgen modules). The load() method reads the tables from a pickle file, which is much faster than the other ways offered by subclasses. The pickle file is written by calling dump() (after loading the grammar tables using a subclass). The report() method prints a readable representation of the tables to stdout, for debugging. The instance variables are as follows: symbol2number -- a dict mapping symbol names to numbers. Symbol numbers are always 256 or higher, to distinguish them from token numbers, which are between 0 and 255 (inclusive). number2symbol -- a dict mapping numbers to symbol names; these two are each other's inverse. states -- a list of DFAs, where each DFA is a list of states, each state is is a list of arcs, and each arc is a (i, j) pair where i is a label and j is a state number. The DFA number is the index into this list. (This name is slightly confusing.) Final states are represented by a special arc of the form (0, j) where j is its own state number. dfas -- a dict mapping symbol numbers to (DFA, first) pairs, where DFA is an item from the states list above, and first is a set of tokens that can begin this grammar rule (represented by a dict whose values are always 1). labels -- a list of (x, y) pairs where x is either a token number or a symbol number, and y is either None or a string; the strings are keywords. The label number is the index in this list; label numbers are used to mark state transitions (arcs) in the DFAs. start -- the number of the grammar's start symbol. keywords -- a dict mapping keyword strings to arc labels. tokens -- a dict mapping token numbers to arc labels. """ def __init__(self): self.symbol2number = {} self.number2symbol = {} self.states = [] self.dfas = {} self.labels = [(0, "EMPTY")] self.keywords = {} self.tokens = {} self.symbol2label = {} self.start = 256 def dump(self, filename): """Dump the grammar tables to a pickle file.""" f = open(filename, "wb") pickle.dump(self.__dict__, f, 2) f.close() def load(self, filename): """Load the grammar tables from a pickle file.""" f = open(filename, "rb") d = pickle.load(f) f.close() self.__dict__.update(d) def report(self): """Dump the grammar tables to standard output, for debugging.""" from pprint import pprint print("s2n") pprint(self.symbol2number) print("n2s") pprint(self.number2symbol) print("states") pprint(self.states) print("dfas") pprint(self.dfas) print("labels") pprint(self.labels) print("start", self.start) def genjs(self): from pprint import pformat return ( "Sk.ParseTables = {\n" + "sym:\n" + pformat(self.symbol2number).replace("'","") + # NOTE don't quote LHS, closure compiler won't rename through strings as props ",\n" + "number2symbol:\n" + pformat(self.number2symbol) + ",\n" + "dfas:\n" + pformat(self.dfas) + ",\n" + "states:\n" + pformat(self.states) + ",\n" + "labels:\n" + pformat(self.labels) + ",\n" + "keywords:\n" + pformat(self.keywords) + ",\n" + "tokens:\n" + pformat(self.tokens) + ",\n" + "start: " + str(self.start) + "\n};\n" # ick, tuple -> list and None -> null ).replace("(", "[").replace(")", "]").replace("None", "null") # Map from operator to number (since tokenize doesn't do this) opmap_raw = """ ( LPAR ) RPAR [ LSQB ] RSQB : COLON , COMMA ; SEMI + PLUS - MINUS * STAR / SLASH | VBAR & AMPER < LESS > GREATER = EQUAL . DOT % PERCENT ` BACKQUOTE { LBRACE } RBRACE @ AT == EQEQUAL != NOTEQUAL <> NOTEQUAL <= LESSEQUAL >= GREATEREQUAL ~ TILDE ^ CIRCUMFLEX << LEFTSHIFT >> RIGHTSHIFT ** DOUBLESTAR += PLUSEQUAL -= MINEQUAL *= STAREQUAL /= SLASHEQUAL %= PERCENTEQUAL &= AMPEREQUAL |= VBAREQUAL ^= CIRCUMFLEXEQUAL <<= LEFTSHIFTEQUAL >>= RIGHTSHIFTEQUAL **= DOUBLESTAREQUAL // DOUBLESLASH //= DOUBLESLASHEQUAL -> RARROW """ opmap = {} for line in opmap_raw.splitlines(): if line: op, name = line.split() opmap[op] = getattr(token, name)
[ [ 8, 0, 0.0421, 0.0495, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0792, 0.005, 0, 0.66, 0.1667, 848, 0, 1, 0, 0, 848, 0, 0 ], [ 1, 0, 0.0941, 0.005, 0, 0.66, ...
[ "\"\"\"This module defines the data structures used to represent a grammar.\n\nThese are a bit arcane because they are derived from the data\nstructures used by Python's 'pgen' parser generator.\n\nThere's also a table here mapping operators to their names in the\ntoken module; the Python tokenize module reports al...
#! /usr/bin/env python """Generate JS code from an ASDL description.""" # TO DO # handle fields that have a type but no name import os, sys import asdl TABSIZE = 4 MAX_COL = 80 def get_c_type(name): """Return a string for the C name of the type. This function special cases the default types provided by asdl: identifier, string, int, bool. """ # XXX ack! need to figure out where Id is useful and where string if isinstance(name, asdl.Id): name = name.value if name in asdl.builtin_types: return name else: return "%s_ty" % name def reflow_lines(s, depth): """Reflow the line s indented depth tabs. Return a sequence of lines where no line extends beyond MAX_COL when properly indented. The first line is properly indented based exclusively on depth * TABSIZE. All following lines -- these are the reflowed lines generated by this function -- start at the same column as the first character beyond the opening { in the first line. """ size = MAX_COL - depth * TABSIZE if len(s) < size: return [s] lines = [] cur = s padding = "" while len(cur) > size: i = cur.rfind(' ', 0, size) # XXX this should be fixed for real if i == -1 and 'GeneratorExp' in cur: i = size + 3 assert i != -1, "Impossible line %d to reflow: %r" % (size, s) lines.append(padding + cur[:i]) if len(lines) == 1: # find new size based on brace j = cur.find('{', 0, i) if j >= 0: j += 2 # account for the brace and the space after it size -= j padding = " " * j else: j = cur.find('(', 0, i) if j >= 0: j += 1 # account for the paren (no space after it) size -= j padding = " " * j cur = cur[i+1:] else: lines.append(padding + cur) return lines def is_simple(sum): """Return True if a sum is a simple. A sum is simple if its types have no fields, e.g. unaryop = Invert | Not | UAdd | USub """ for t in sum.types: if t.fields: return False return True class EmitVisitor(asdl.VisitorBase): """Visit that emits lines""" def __init__(self, file): self.file = file super(EmitVisitor, self).__init__() def emit(self, s, depth, reflow=1): # XXX reflow long lines? if reflow: lines = reflow_lines(s, depth) else: lines = [s] for line in lines: line = (" " * TABSIZE * depth) + line + "\n" self.file.write(line) class TypeDefVisitor(EmitVisitor): def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type, depth=0): self.visit(type.value, type.name, depth) def visitSum(self, sum, name, depth): if is_simple(sum): self.simple_sum(sum, name, depth) def simple_sum(self, sum, name, depth): self.emit("/* ----- %s ----- */" % name, depth); for i in range(len(sum.types)): self.emit("/** @constructor */", depth); type = sum.types[i] self.emit("function %s() {}" % type.name, depth) self.emit("", depth) def visitProduct(self, product, name, depth): pass class StructVisitor(EmitVisitor): """Visitor to generate typdefs for AST.""" def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type, depth=0): self.visit(type.value, type.name, depth) def visitSum(self, sum, name, depth): pass def visitConstructor(self, cons, depth): pass def visitField(self, field, depth): # XXX need to lookup field.type, because it might be something # like a builtin... ctype = get_c_type(field.type) name = field.name if field.seq: if field.type.value in ('cmpop',): self.emit("asdl_int_seq *%(name)s;" % locals(), depth) else: self.emit("asdl_seq *%(name)s;" % locals(), depth) else: self.emit("%(ctype)s %(name)s;" % locals(), depth) def visitProduct(self, product, name, depth): pass class PrototypeVisitor(EmitVisitor): """Generate function prototypes for the .h file""" def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value, type.name) def visitSum(self, sum, name): if is_simple(sum): pass # XXX else: for t in sum.types: self.visit(t, name, sum.attributes) def get_args(self, fields): """Return list of C argument into, one for each field. Argument info is 3-tuple of a C type, variable name, and flag that is true if type can be NULL. """ args = [] unnamed = {} for f in fields: if f.name is None: name = f.type c = unnamed[name] = unnamed.get(name, 0) + 1 if c > 1: name = "name%d" % (c - 1) else: name = f.name # XXX should extend get_c_type() to handle this if f.seq: if f.type.value in ('cmpop',): ctype = "asdl_int_seq *" else: ctype = "asdl_seq *" else: ctype = get_c_type(f.type) args.append((ctype, name, f.opt or f.seq)) return args def visitConstructor(self, cons, type, attrs): args = self.get_args(cons.fields) attrs = self.get_args(attrs) ctype = get_c_type(type) self.emit_function(cons.name, ctype, args, attrs) def emit_function(self, name, ctype, args, attrs, union=1): args = args + attrs if args: argstr = ", ".join(["%s %s" % (atype, aname) for atype, aname, opt in args]) argstr += ", PyArena *arena" else: argstr = "PyArena *arena" margs = "a0" for i in range(1, len(args)+1): margs += ", a%d" % i self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0, reflow = 0) self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), 0) def visitProduct(self, prod, name): self.emit_function(name, get_c_type(name), self.get_args(prod.fields), [], union=0) class FunctionVisitor(PrototypeVisitor): """Visitor to generate constructor functions for AST.""" def emit_function(self, name, ctype, args, attrs, union=1): def emit(s, depth=0, reflow=1): self.emit(s, depth, reflow) argstr = ", ".join(["/* {%s} */ %s" % (atype, aname) for atype, aname, opt in args + attrs]) emit("/** @constructor */") emit("function %s(%s)" % (name, argstr)) emit("{") for argtype, argname, opt in args: # XXX hack alert: false is allowed for a bool if not opt and not (argtype == "bool" or argtype == "int"): emit("goog.asserts.assert(%s !== null && %s !== undefined);" % (argname, argname), 1) if union: self.emit_body_union(name, args, attrs) else: self.emit_body_struct(name, args, attrs) emit("return this;", 1) emit("}") emit("") def emit_body_union(self, name, args, attrs): def emit(s, depth=0, reflow=1): self.emit(s, depth, reflow) for argtype, argname, opt in args: emit("this.%s = %s;" % (argname, argname), 1) for argtype, argname, opt in attrs: emit("this.%s = %s;" % (argname, argname), 1) def emit_body_struct(self, name, args, attrs): def emit(s, depth=0, reflow=1): self.emit(s, depth, reflow) for argtype, argname, opt in args: emit("this.%s = %s;" % (argname, argname), 1) assert not attrs class PickleVisitor(EmitVisitor): def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value, type.name) def visitSum(self, sum, name): pass def visitProduct(self, sum, name): pass def visitConstructor(self, cons, name): pass def visitField(self, sum): pass def cleanName(name): name = str(name) if name[-1] == "_": return name[:-1] return name class FieldNamesVisitor(PickleVisitor): """note that trailing comma is bad in IE so we have to fiddle a bit to avoid it""" def visitProduct(self, prod, name): if prod.fields: self.emit('%s.prototype._astname = "%s";' % (name, cleanName(name)), 0) self.emit("%s.prototype._fields = [" % name,0) c = 0 for f in prod.fields: c += 1 self.emit('"%s", function(n) { return n.%s; }%s' % (f.name, f.name, "," if c < len(prod.fields) else ""), 1) self.emit("];", 0) def visitSum(self, sum, name): if is_simple(sum): for t in sum.types: self.emit('%s.prototype._astname = "%s";' % (t.name, cleanName(t.name)), 0) self.emit('%s.prototype._isenum = true;' % (t.name), 0) else: for t in sum.types: self.visitConstructor(t, name) def visitConstructor(self, cons, name): self.emit('%s.prototype._astname = "%s";' % (cons.name, cleanName(cons.name)), 0) self.emit("%s.prototype._fields = [" % cons.name, 0) if cons.fields: c = 0 for t in cons.fields: c += 1 self.emit('"%s", function(n) { return n.%s; }%s' % (t.name, t.name, "," if c < len(cons.fields) else ""), 1) self.emit("];",0) _SPECIALIZED_SEQUENCES = ('stmt', 'expr') def find_sequence(fields, doing_specialization): """Return True if any field uses a sequence.""" for f in fields: if f.seq: if not doing_specialization: return True if str(f.type) not in _SPECIALIZED_SEQUENCES: return True return False def has_sequence(types, doing_specialization): for t in types: if find_sequence(t.fields, doing_specialization): return True return False class ChainOfVisitors: def __init__(self, *visitors): self.visitors = visitors def visit(self, object): for v in self.visitors: v.visit(object) v.emit("", 0) common_msg = "/* File automatically generated by %s. */\n\n" def main(asdlfile, outputfile): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) auto_gen_msg = common_msg % argv0 mod = asdl.parse(asdlfile) if not asdl.check(mod): sys.exit(1) f = open(outputfile, "wb") f.write(auto_gen_msg) c = ChainOfVisitors(TypeDefVisitor(f), ) c.visit(mod) f.write("\n"*5) f.write("/* ---------------------- */\n") f.write("/* constructors for nodes */\n") f.write("/* ---------------------- */\n") f.write("\n"*5) v = ChainOfVisitors( FunctionVisitor(f), FieldNamesVisitor(f), ) v.visit(mod) f.close() if __name__ == "__main__": import sys if len(sys.argv) != 3: print "usage: asdl_js.py input.asdl output.js" raise SystemExit() main(sys.argv[1], sys.argv[2])
[ [ 8, 0, 0.0051, 0.0026, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0179, 0.0026, 0, 0.66, 0.0455, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 1, 0, 0.023, 0.0026, 0, 0.66,...
[ "\"\"\"Generate JS code from an ASDL description.\"\"\"", "import os, sys", "import asdl", "TABSIZE = 4", "MAX_COL = 80", "def get_c_type(name):\n \"\"\"Return a string for the C name of the type.\n\n This function special cases the default types provided by asdl:\n identifier, string, int, bool....
s = """Gur Mra bs Clguba, ol Gvz Crgref Ornhgvshy vf orggre guna htyl. Rkcyvpvg vf orggre guna vzcyvpvg. Fvzcyr vf orggre guna pbzcyrk. Pbzcyrk vf orggre guna pbzcyvpngrq. Syng vf orggre guna arfgrq. Fcnefr vf orggre guna qrafr. Ernqnovyvgl pbhagf. Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. Nygubhtu cenpgvpnyvgl orngf chevgl. Reebef fubhyq arire cnff fvyragyl. Hayrff rkcyvpvgyl fvyraprq. Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. Abj vf orggre guna arire. Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""" d = {} for c in (65, 97): for i in range(26): d[chr(i+c)] = chr((i+13) % 26 + c) print "".join([d.get(c, c) for c in s])
[ [ 14, 0, 0.3929, 0.75, 0, 0.66, 0, 553, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.8214, 0.0357, 0, 0.66, 0.3333, 355, 0, 0, 0, 0, 0, 6, 0 ], [ 6, 0, 0.8929, 0.1071, 0, 0.66...
[ "s = \"\"\"Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf orggre guna htyl.\nRkcyvpvg vf orggre guna vzcyvpvg.\nFvzcyr vf orggre guna pbzcyrk.\nPbzcyrk vf orggre guna pbzcyvpngrq.\nSyng vf orggre guna arfgrq.\nFcnefr vf orggre guna qrafr.", "d = {}", "for c in (65, 97):\n for i in range(26):\n d[chr...
__author__ = 'bmiller' def testEqual(actual, expected): if type(expected) == type(1): if actual == expected: print('Pass') return True elif type(expected) == type(1.11): if abs(actual-expected) < 0.00001: print('Pass') return True else: if actual == expected: print('Pass') return True print('Test Failed: expected ' + str(expected) + ' but got ' + str(actual)) return False def testNotEqual(actual, expected): pass
[ [ 14, 0, 0.0476, 0.0476, 0, 0.66, 0, 777, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 0, 0.4762, 0.7143, 0, 0.66, 0.5, 214, 0, 2, 1, 0, 0, 0, 11 ], [ 4, 1, 0.4524, 0.5714, 1, 0.99,...
[ "__author__ = 'bmiller'", "def testEqual(actual, expected):\n if type(expected) == type(1):\n if actual == expected:\n print('Pass')\n return True\n elif type(expected) == type(1.11):\n if abs(actual-expected) < 0.00001:\n print('Pass')", " if type(expecte...
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import os from django.utils import simplejson from google.appengine.ext import db class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/html' path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(open(path).read()) class TurtlePage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/html' path = os.path.join(os.path.dirname(__file__), 'turtle.html') self.response.out.write(open(path).read()) class IdePage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/html' path = os.path.join(os.path.dirname(__file__), 'ide/index.html') self.response.out.write(open(path).read()) class TestResult(db.Model): browsername = db.StringProperty() browserversion = db.StringProperty() browseros = db.StringProperty() version = db.StringProperty() rc = db.StringProperty() results = db.TextProperty() date = db.DateTimeProperty(auto_now_add=True) class TestResults(webapp.RequestHandler): def post(self): data = simplejson.loads(self.request.body) tr = TestResult() tr.browsername = str(data['browsername']) tr.browserversion = str(data['browserversion']) tr.browseros = str(data['browseros']) tr.version = str(data['version']) tr.rc = str(data['rc']) tr.results = str(data['results']) tr.put() self.response.headers['Content-Type'] = 'application/json' self.response.out.write("{result:'ok'}") application = webapp.WSGIApplication( [('/', MainPage), ('/testresults', TestResults), ('/turtle', TurtlePage), ('/ide', IdePage) ], debug=False) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
[ [ 1, 0, 0.0164, 0.0164, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.0328, 0.0164, 0, 0.66, 0.0833, 327, 0, 1, 0, 0, 327, 0, 0 ], [ 1, 0, 0.0492, 0.0164, 0, ...
[ "from google.appengine.ext import webapp", "from google.appengine.ext.webapp.util import run_wsgi_app", "import os", "from django.utils import simplejson", "from google.appengine.ext import db", "class MainPage(webapp.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 't...
import sys import webgl import webgl.primitives import webgl.models import webgl.matrix4 as m4 def main(): print "Starting up..." gl = webgl.Context("canvas") sh = webgl.Shader(gl, VertexShader, FragmentShader) sh.use() m = webgl.models.Model(sh, webgl.primitives.createCube(1), []) eyePos = webgl.Float32Array([0, 0, 3]) target = webgl.Float32Array([0, 0, 0]) up = webgl.Float32Array([0, 1, 0]) view = webgl.Float32Array(16) world = webgl.Float32Array(16) view = webgl.Float32Array(16) viewproj = webgl.Float32Array(16) worldview = webgl.Float32Array(16) worldviewproj = webgl.Float32Array(16) proj = webgl.Float32Array(16) normalmat = webgl.Float32Array(16) tmp = webgl.Float32Array(16) gl.cullFace(gl.BACK) gl.depthFunc(gl.LEQUAL) m4.lookAt(view, eyePos, target, up) def draw(gl, time): gl.clearColor(0.1, 0.1, 0.2, 1) gl.clearDepth(1.0) gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) m4.perspective(proj, 60, 16.0/9.0, 0.1, 500); m4.rotationY(world, time * 0.05) m4.mul(viewproj, view, proj) m4.mul(worldview, world, view) m4.mul(worldviewproj, world, viewproj) m4.invert(normalmat, world) uniforms = { 'u_worldviewproj': worldviewproj, 'u_normalmat': normalmat, } m.drawPrep(uniforms) m.draw({}) gl.setDrawFunc(draw) VertexShader = """ uniform mat4 u_worldviewproj; uniform mat4 u_normalmat; attribute vec3 position; attribute vec3 normal; varying float v_dot; void main() { gl_Position = u_worldviewproj * vec4(position, 1); vec4 transNormal = u_normalmat * vec4(normal, 1); v_dot = max(dot(transNormal.xyz, normalize(vec3(0, 0, 1))), 0.0); } """ FragmentShader = """ #ifdef GL_ES precision mediump float; #endif varying float v_dot; void main() { gl_FragColor = vec4(vec3(.8, 0, 0) * v_dot, 1); } """ main()
[ [ 1, 0, 0.0118, 0.0118, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0235, 0.0118, 0, 0.66, 0.125, 201, 0, 1, 0, 0, 201, 0, 0 ], [ 1, 0, 0.0353, 0.0118, 0, 0...
[ "import sys", "import webgl", "import webgl.primitives", "import webgl.models", "import webgl.matrix4 as m4", "def main():\n print(\"Starting up...\")\n gl = webgl.Context(\"canvas\")\n sh = webgl.Shader(gl, VertexShader, FragmentShader)\n sh.use()\n \n m = webgl.models.Model(sh, webgl.p...
""" quick hack script to convert from quake2 .bsp to simple format to draw. drops most information. keeps only raw polys and lightmaps. makes .blv and .llv file (big and little endian level) file format is 'BLV1' or 'LLV1' int texwidth int texheight int numtris float startx, starty, startz, startyaw (rads) uint32 texdata[texwidth*texheight] float texcoords[numtris*6] float verts[numtris*9] this makes for trivial drawing, but of course it's very inefficient. this is very different from the original format which has a bunch of optimizations of pvs, culling, uses tris/quads/polys, level-specific data, textures, etc. there's also lots of trickery to save space in packing, indirection, etc. but we just flatten all that out to triangles. it's probably faster these days for such small amounts of geometry anyway. http://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml scott.q2convert@h4ck3r.net """ import os import sys import struct def strunpack(stream, format): return struct.unpack(format, stream.read(struct.calcsize(format))) def die(msg): print msg raise SystemExit(1) def convCoord(v): """swizzle, the quake order is wacky. also scale by an arbitrary amount.""" scale = 1.0/15.0 return (v[1]*scale, v[2]*scale, v[0]*scale) def loadRawData(raw): # header headerstr = "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII" data = (magic, version, off_Entities, len_Entities, off_Planes, len_Planes, off_Vertices, len_Vertices, off_Visibility, len_Visibility, off_Nodes, len_Nodes, off_Texture_Information, len_Texture_Information, off_Faces, len_Faces, off_Lightmaps, len_Lightmaps, off_Leaves, len_Leaves, off_Leaf_Face_Table, len_Leaf_Face_Table, off_Leaf_Brush_Table, len_Leaf_Brush_Table, off_Edges, len_Edges, off_Face_Edge_Table, len_Face_Edge_Table, off_Models, len_Models, off_Brushes, len_Brushes, off_Brush_Sides, len_Brush_Sides, off_Pop, len_Pop, off_Areas, len_Areas, off_Area_Portals, len_Area_Portals) = struct.unpack_from(headerstr, raw) if struct.pack("BBBB", magic>>24, (magic>>16)&0xff, (magic>>8)&0xff, magic&0xff) != "PSBI": die("Bad header") if version != 38: die("Bad version") Leaves = [] leaf_Size = 28 for i in range(len_Leaves / leaf_Size): (brush_or, cluster, area, bbox_minX, bbox_minY, bbox_minZ, bbox_maxX, bbox_maxY, bbox_maxZ, first_leaf_face, num_leaf_faces, first_leaf_brush, num_leaf_brushes) = struct.unpack_from("IHHhhhhhhHHHH", raw, off_Leaves + i*leaf_Size) Leaves.append((first_leaf_face, num_leaf_faces)) print "Leaves: %d" % len(Leaves) Leaf_Face_Table = [] leafface_Size = 2 for i in range(len_Leaf_Face_Table / leafface_Size): Leaf_Face_Table.append(struct.unpack_from("H", raw, off_Leaf_Face_Table + i*leafface_Size)[0]) Faces = [] face_Size = 20 for i in range(len_Faces / face_Size): (plane, plane_Size, first_edge, num_edges, texture_info, style0, style1, style2, style3, lightmap_offset) = struct.unpack_from("HHIHHBBBBI", raw, off_Faces + i*face_Size) Faces.append((first_edge, num_edges, lightmap_offset)) print "Faces: %d" % len(Faces) Face_Edge_Table = [] faceedge_Size = 4 for i in range(len_Face_Edge_Table / faceedge_Size): Face_Edge_Table.append(struct.unpack_from("i", raw, off_Face_Edge_Table + i*faceedge_Size)[0]) Edges = [] edge_Size = 4 for i in range(len_Edges / edge_Size): (v0, v1) = struct.unpack_from("HH", raw, off_Edges + i*edge_Size) Edges.append((v0, v1)) print "Edges: %d" % len(Edges) Vertices = [] vert_Size = 12 for i in range(len_Vertices / vert_Size): v = struct.unpack_from("fff", raw, off_Vertices + i*vert_Size) Vertices.append(convCoord(v)) print "Vertices: %d" % len(Vertices) ents = struct.unpack_from("%ds" % len_Entities, raw, off_Entities)[0][1:-3] # opening { and final }+nul Entities = [] for ent in ents.split("}\n{"): entdata = {} for line in ent.lstrip("\n").rstrip("\n").split("\n"): k,v = line.lstrip('"').rstrip('"').split('" "') entdata[k] = v Entities.append(entdata) return Leaves, Leaf_Face_Table, Faces, Face_Edge_Table, Edges, Vertices, Entities def writeBinary(triverts, Entities, packprefix, fileext): playerStart = findEntity(Entities, "info_player_start") sx, sy, sz = playerStart['origin'].split(' ') numtris = len(triverts) / 9 texwidth = 0 texheight = 0 startx, starty, startz = convCoord((float(sx), float(sy), float(sz))) startyaw = float(playerStart['angle']) texcoords = (0.0, 0.0) * numtris * 3 outname = os.path.splitext(sys.argv[1])[0] + fileext print "writing", outname + "...", out = open(outname, "wb") out.write(struct.pack(packprefix + "4sIIIffff", 'LLV1', texwidth, texheight, numtris, startx, starty, startz, startyaw)) for i in range(numtris*3): out.write(struct.pack(packprefix + "ff", 0.0, 0.0)) for tv in triverts: out.write(struct.pack(packprefix + "f", tv)) out.close() print "done" def findEntity(entities, class_name): for item in entities: if item['classname'] == class_name: return item def main(): if len(sys.argv) != 2: die("usage: convert <quake2.bsp>") raw = open(sys.argv[1], "rb").read() # Leaves are first+len into Leaf_Face_Table # Leaf_Face_Table is indices into Faces # Faces is first+len into Face_Edge_Table # Face_Edge_Table is indices of Edges. if index is positive then (v0,v1) for the edge else (v1,v0) # Edges is pairs of indices into Vertices # Vertices are list of 3 floats # # Seems crazily complicated these days (thankfully :) Leaves, Leaf_Face_Table, Faces, Face_Edge_Table, Edges, Vertices, Entities = loadRawData(raw) triverts = [] # get all polys for first_leaf_face, num_leaf_faces in Leaves: for leaf_face_i in range(first_leaf_face, first_leaf_face + num_leaf_faces): face_index = Leaf_Face_Table[leaf_face_i] first_face_edge, num_face_edges, lightmapoffset = Faces[face_index] polyedges = [] for face_edge_i in range(first_face_edge, first_face_edge + num_face_edges): edgei_signed = Face_Edge_Table[face_edge_i] #print "edgei:", edgei_signed if edgei_signed >= 0: e0, e1 = Edges[edgei_signed] else: e1, e0 = Edges[-edgei_signed] v0 = Vertices[e0] v1 = Vertices[e1] polyedges.append((v0, v1)) #print "(%f,%f,%f) -> (%f,%f,%f)" % (v0[0], v0[1], v0[2], v1[0], v1[1], v1[2]) polyverts = [] for pei in range(len(polyedges)): if polyedges[pei][1] != polyedges[(pei+1) % len(polyedges)][0]: die("poly isn't normal closed style") polyverts.append(polyedges[pei][0]) for i in range(1, len(polyverts) - 1): triverts.extend(polyverts[0]) triverts.extend(polyverts[i]) triverts.extend(polyverts[i+1]) texid.append(lightmapoffset) writeBinary(triverts, Entities, "<", ".llv") writeBinary(triverts, Entities, ">", ".blv") if __name__ == "__main__": main()
[ [ 8, 0, 0.0724, 0.1402, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1495, 0.0047, 0, 0.66, 0.0909, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1542, 0.0047, 0, 0.66...
[ "\"\"\"\n\nquick hack script to convert from quake2 .bsp to simple format to draw. drops\nmost information. keeps only raw polys and lightmaps.\n\nmakes .blv and .llv file (big and little endian level)\n\nfile format is", "import os", "import sys", "import struct", "def strunpack(stream, format):\n retur...
import goog.graphics as gfx import goog.dom as dom def main(): g = gfx.createSimpleGraphics(600, 200) print g fill = gfx.SolidFill('yellow') stroke = gfx.Stroke(2, 'green') g.drawRect(30, 10, 100, 80, stroke, fill) stroke = gfx.Stroke(4, 'green') g.drawImage(30, 110, 276, 110, 'http://www.google.com/intl/en_ALL/images/logo.gif') g.drawCircle(190, 70, 50, stroke, fill) stroke = gfx.Stroke(6, 'green') g.drawEllipse(300, 140, 80, 40, stroke, fill) # A path path = gfx.Path() path.moveTo(320, 30) path.lineTo(420, 130) path.lineTo(480, 30) path.close() stroke = gfx.Stroke(1, 'green') g.drawPath(path, stroke, fill) # Clipped shapes redFill = gfx.SolidFill('red') g.drawCircle(540, 10, 50, None, redFill); g.drawCircle(540, 10, 30, None, fill); g.drawCircle(560, 210, 30, stroke, fill); g.drawCircle(560, 210, 45, stroke, None); # no fill g.drawCircle(600, 90, 30, stroke, fill); g.render(dom.getElement('canv')) main()
[ [ 1, 0, 0.0256, 0.0256, 0, 0.66, 0, 78, 0, 1, 0, 0, 78, 0, 0 ], [ 1, 0, 0.0513, 0.0256, 0, 0.66, 0.3333, 107, 0, 1, 0, 0, 107, 0, 0 ], [ 2, 0, 0.5256, 0.8718, 0, 0....
[ "import goog.graphics as gfx", "import goog.dom as dom", "def main():\n g = gfx.createSimpleGraphics(600, 200)\n print(g)\n fill = gfx.SolidFill('yellow')\n stroke = gfx.Stroke(2, 'green')\n\n g.drawRect(30, 10, 100, 80, stroke, fill)\n stroke = gfx.Stroke(4, 'green')", " g = gfx.createSi...
def f(): n = "OK" print n f()
[ [ 2, 0, 0.4167, 0.6667, 0, 0.66, 0, 899, 0, 0, 0, 0, 0, 0, 1 ], [ 14, 1, 0.3333, 0.1667, 1, 0.63, 0, 773, 1, 0, 0, 0, 0, 3, 0 ], [ 8, 1, 0.6667, 0.1667, 1, 0.63, ...
[ "def f():\n n = \"OK\"\n\n print(n)", " n = \"OK\"", " print(n)", "f()" ]
print '0"1' print '2\'3' print "4'5" print "6\"7" print '''8'9"0'''
[ [ 8, 0, 0.2, 0.2, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.4, 0.2, 0, 0.66, 0.25, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.6, 0.2, 0, 0.66, 0.5, 535, ...
[ "print('0\"1')", "print('2\\'3')", "print(\"4'5\")", "print(\"6\\\"7\")", "print('''8'9\"0''')" ]
y = 1
[ [ 14, 0, 1, 1, 0, 0.66, 0, 304, 1, 0, 0, 0, 0, 1, 0 ] ]
[ "y = 1" ]
print x+2*3
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(x+2*3)" ]
print 4-1
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(4-1)" ]
class Stuff: def __init__(self): self.a = 0 self.b = 'b' self.c = [1,2,3] self.d = 100000000000000 s = Stuff() s.a += 10 s.b += 'dog' s.c += [9,10] s.d += 10000 print s.a print s.b print s.c print s.d
[ [ 3, 0, 0.2059, 0.3529, 0, 0.66, 0, 710, 0, 1, 0, 0, 0, 0, 0 ], [ 2, 1, 0.2353, 0.2941, 1, 0.41, 0, 555, 0, 1, 0, 0, 0, 0, 0 ], [ 14, 2, 0.1765, 0.0588, 2, 0.09, ...
[ "class Stuff:\n def __init__(self):\n self.a = 0\n self.b = 'b'\n self.c = [1,2,3]\n self.d = 100000000000000", " def __init__(self):\n self.a = 0\n self.b = 'b'\n self.c = [1,2,3]\n self.d = 100000000000000", " self.a = 0", " self.b ...
print [] or 5
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print([] or 5)" ]
def f(n): i = 0 while i < n: yield i i = 100 yield i i += 1 for i in f(50): print i
[ [ 2, 0, 0.4, 0.7, 0, 0.66, 0, 899, 0, 1, 0, 0, 0, 0, 0 ], [ 14, 1, 0.2, 0.1, 1, 0.4, 0, 826, 1, 0, 0, 0, 0, 1, 0 ], [ 5, 1, 0.5, 0.5, 1, 0.4, 1, 0, 0, ...
[ "def f(n):\n i = 0\n while i < n:\n yield i\n i = 100\n yield i\n i += 1", " i = 0", " while i < n:\n yield i\n i = 100\n yield i\n i += 1", " yield i", " i = 100", " yield i", "for i in f(50):\n print(i)", " ...
def f(iter): for v in iter: print v f(x*y for x in range(10) for y in range(x))
[ [ 2, 0, 0.5, 0.75, 0, 0.66, 0, 899, 0, 1, 0, 0, 0, 0, 1 ], [ 6, 1, 0.625, 0.5, 1, 0.46, 0, 553, 2, 0, 0, 0, 0, 0, 1 ], [ 8, 2, 0.75, 0.25, 2, 0.23, 0, 535, ...
[ "def f(iter):\n for v in iter:\n print(v)", " for v in iter:\n print(v)", " print(v)", "f(x*y for x in range(10) for y in range(x))" ]
X = "OK" def test(): X = 4 print(X) test() print X
[ [ 14, 0, 0.1667, 0.1667, 0, 0.66, 0, 783, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 0, 0.5, 0.5, 0, 0.66, 0.3333, 224, 0, 0, 0, 0, 0, 0, 1 ], [ 14, 1, 0.5, 0.1667, 1, 0.94, 0...
[ "X = \"OK\"", "def test():\n X = 4\n print(X)", " X = 4", " print(X)", "test()", "print(X)" ]
def f(): y = 0 while y == 0: y += 1 yield y for i in f(): print i
[ [ 2, 0, 0.375, 0.625, 0, 0.66, 0, 899, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.25, 0.125, 1, 0.53, 0, 304, 1, 0, 0, 0, 0, 1, 0 ], [ 5, 1, 0.5, 0.375, 1, 0.53, 1, ...
[ "def f():\n y = 0\n while y == 0:\n y += 1\n yield y", " y = 0", " while y == 0:\n y += 1\n yield y", " yield y", "for i in f():\n print(i)", " print(i)" ]
class X: pass x = X() methodName = "wee" try: stuff = getattr(x, methodName) except AttributeError: raise ValueError, "no such method in %s: %s" % (x.__class__, methodName)
[ [ 3, 0, 1, 1, 0, 0.66, 0, 783, 0, 0, 0, 0, 0, 0, 0 ] ]
[ "class X: pass" ]
import pkga.pkgb.modc as c_me print c_me.stuff print c_me.things
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 812, 0, 1, 0, 0, 812, 0, 0 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 0.5, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.25, 0, 0.66, 1, 535...
[ "import pkga.pkgb.modc as c_me", "print(c_me.stuff)", "print(c_me.things)" ]
print(int) print(str(int)) print(repr(int)) class X: pass x = X() print(str(x)) print(repr(x)) print(str(x.__class__)) print(repr(x.__class__)) print(str(X)) print(repr(X))
[ [ 8, 0, 0.0833, 0.0833, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.1667, 0.0833, 0, 0.66, 0.1, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 8, 0, 0.25, 0.0833, 0, 0.66, ...
[ "print(int)", "print(str(int))", "print(repr(int))", "class X:\n pass", "x = X()", "print(str(x))", "print(repr(x))", "print(str(x.__class__))", "print(repr(x.__class__))", "print(str(X))", "print(repr(X))" ]
def test(): def fnc(): print "OK" print fnc() test()
[ [ 2, 0, 0.5, 0.8, 0, 0.66, 0, 224, 0, 0, 0, 0, 0, 0, 3 ], [ 2, 1, 0.5, 0.4, 1, 0.23, 0, 499, 0, 0, 0, 0, 0, 0, 1 ], [ 8, 2, 0.6, 0.2, 2, 0.92, 0, 535, 3...
[ "def test():\n def fnc():\n print(\"OK\")\n print(fnc())", " def fnc():\n print(\"OK\")", " print(\"OK\")", " print(fnc())", "test()" ]
z = 0 for x in [1,2,3]: z += x print z
[ [ 14, 0, 0.25, 0.25, 0, 0.66, 0, 859, 1, 0, 0, 0, 0, 1, 0 ], [ 6, 0, 0.625, 0.5, 0, 0.66, 0.5, 190, 0, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 1, 0.25, 0, 0.66, 1, 535,...
[ "z = 0", "for x in [1,2,3]:\n z += x", "print(z)" ]
a = (1,2,3) b = ('a', 'b', 'c') for x in a+b: print x print "a:",a print "b:",b
[ [ 14, 0, 0.1667, 0.1667, 0, 0.66, 0, 475, 0, 0, 0, 0, 0, 8, 0 ], [ 14, 0, 0.3333, 0.1667, 0, 0.66, 0.25, 756, 0, 0, 0, 0, 0, 8, 0 ], [ 6, 0, 0.5833, 0.3333, 0, 0.66...
[ "a = (1,2,3)", "b = ('a', 'b', 'c')", "for x in a+b:\n print(x)", " print(x)", "print(\"a:\",a)", "print(\"b:\",b)" ]
import this
[ [ 1, 0, 1, 1, 0, 0.66, 0, 324, 0, 1, 0, 0, 324, 0, 0 ] ]
[ "import this" ]
v = [3,2,1] v.sort() print v[0]
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 553, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 489, 3, 0, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1...
[ "v = [3,2,1]", "v.sort()", "print(v[0])" ]
wee = lambda waa, woo=False, wii=True: ("OK", waa, woo, wii) print wee("stuff") print wee("stuff", "dog") print wee("stuff", "dog", "cat") print wee("stuff", wii="lamma") print wee(wii="lamma", waa="pocky") print wee(wii="lamma", waa="pocky", woo="blorp")
[ [ 14, 0, 0.125, 0.125, 0, 0.66, 0, 48, 9, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 0.375, 0.125, 0, 0.66, 0.1667, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 8, 0, 0.5, 0.125, 0, 0.66, 0....
[ "wee = lambda waa, woo=False, wii=True: (\"OK\", waa, woo, wii)", "print(wee(\"stuff\"))", "print(wee(\"stuff\", \"dog\"))", "print(wee(\"stuff\", \"dog\", \"cat\"))", "print(wee(\"stuff\", wii=\"lamma\"))", "print(wee(wii=\"lamma\", waa=\"pocky\"))", "print(wee(wii=\"lamma\", waa=\"pocky\", woo=\"blorp...
def f(n): i = 0 while i < n: yield i yield i * 10 i += 1 for i in f(10): print i
[ [ 2, 0, 0.3889, 0.6667, 0, 0.66, 0, 899, 0, 1, 0, 0, 0, 0, 0 ], [ 14, 1, 0.2222, 0.1111, 1, 0.72, 0, 826, 1, 0, 0, 0, 0, 1, 0 ], [ 5, 1, 0.5, 0.4444, 1, 0.72, 1...
[ "def f(n):\n i = 0\n while i < n:\n yield i\n yield i * 10\n i += 1", " i = 0", " while i < n:\n yield i\n yield i * 10\n i += 1", " yield i", " yield i * 10", "for i in f(10):\n print(i)", " print(i)" ]
def f(*a): print a def g(x, *a): print x, a def h(x, y, *a): print x, y, a def i(x, y=4, *a): print x, y, a f() f(1) f(1, 2, 3) g(1) g(1, 2, 3) h(1, 2) h(1, 2, 3) h(1, 2, 3, 4) i(1) i(1, 2, 3) i(1, 2, 3, 4)
[ [ 2, 0, 0.0652, 0.087, 0, 0.66, 0, 899, 0, 1, 0, 0, 0, 0, 1 ], [ 8, 1, 0.087, 0.0435, 1, 0.16, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 2, 0, 0.1957, 0.087, 0, 0.66, 0....
[ "def f(*a):\n print(a)", " print(a)", "def g(x, *a):\n print(x, a)", " print(x, a)", "def h(x, y, *a):\n print(x, y, a)", " print(x, y, a)", "def i(x, y=4, *a):\n print(x, y, a)", " print(x, y, a)", "f()", "f(1)", "f(1, 2, 3)", "g(1)", "g(1, 2, 3)", "h(1, 2)", "h(...
a = [1,2,3,4,5,6] b = [9,9,9] a[1:5] = b print a
[ [ 14, 0, 0.25, 0.25, 0, 0.66, 0, 475, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.5, 0.25, 0, 0.66, 0.3333, 756, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0.66...
[ "a = [1,2,3,4,5,6]", "b = [9,9,9]", "a[1:5] = b", "print(a)" ]
def stuff(n): print not n for x in range(-5, 5): stuff(x)
[ [ 2, 0, 0.3, 0.4, 0, 0.66, 0, 686, 0, 1, 0, 0, 0, 0, 1 ], [ 8, 1, 0.4, 0.2, 1, 0.38, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 6, 0, 0.9, 0.4, 0, 0.66, 1, 190, 3...
[ "def stuff(n):\n print(not n)", " print(not n)", "for x in range(-5, 5):\n stuff(x)", " stuff(x)" ]
print False == 0 print True == 1 print True == 2
[ [ 8, 0, 0.3333, 0.3333, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1,...
[ "print(False == 0)", "print(True == 1)", "print(True == 2)" ]
a = (1 for x in range(3)) print a for i in a: print i
[ [ 14, 0, 0.25, 0.25, 0, 0.66, 0, 475, 5, 0, 0, 0, 0, 0, 1 ], [ 8, 0, 0.5, 0.25, 0, 0.66, 0.5, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 6, 0, 0.875, 0.5, 0, 0.66, 1, 82...
[ "a = (1 for x in range(3))", "print(a)", "for i in a:\n print(i)", " print(i)" ]
d = {} d["__proto__"]="testing" print d
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 355, 0, 0, 0, 0, 0, 6, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 0, 1, 0, 0, 0, 0, 3, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1,...
[ "d = {}", "d[\"__proto__\"]=\"testing\"", "print(d)" ]
# Test the creation of sets l = [1,2,3,4,1,1] print l s = set(l) print s print len(s)
[ [ 14, 0, 0.3333, 0.1667, 0, 0.66, 0, 810, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 0.5, 0.1667, 0, 0.66, 0.25, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 14, 0, 0.6667, 0.1667, 0, 0.66, ...
[ "l = [1,2,3,4,1,1]", "print(l)", "s = set(l)", "print(s)", "print(len(s))" ]
print str(range(-4))[:5] print len(range(-4))
[ [ 8, 0, 0.5, 0.5, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 3 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 3 ] ]
[ "print(str(range(-4))[:5])", "print(len(range(-4)))" ]
var1 = "foo" if isinstance(var1, str): print "var1 is a string"
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 897, 1, 0, 0, 0, 0, 3, 0 ], [ 4, 0, 0.8333, 0.6667, 0, 0.66, 1, 0, 3, 0, 0, 0, 0, 0, 2 ], [ 8, 1, 1, 0.3333, 1, 0.14, 0, ...
[ "var1 = \"foo\"", "if isinstance(var1, str):\n print(\"var1 is a string\")", " print(\"var1 is a string\")" ]
def test(a,b): return a+b print test(1,1)+test(1,1)
[ [ 2, 0, 0.5, 0.6667, 0, 0.66, 0, 224, 0, 2, 1, 0, 0, 0, 0 ], [ 13, 1, 0.6667, 0.3333, 1, 0.25, 0, 0, 4, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1, 5...
[ "def test(a,b):\n return a+b", " return a+b", "print(test(1,1)+test(1,1))" ]
a,b = 1,2 print a+b
[ [ 14, 0, 0.5, 0.5, 0, 0.66, 0, 127, 0, 0, 0, 0, 0, 8, 0 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "a,b = 1,2", "print(a+b)" ]
a = [100,101,102,103,104,105,106,107] del a[2:6] print a
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 475, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 2, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "a = [100,101,102,103,104,105,106,107]", "print(a)" ]
x = [0]*10 for i in range(10): x[i] += i x[i] += i*2 print x
[ [ 14, 0, 0.1429, 0.1429, 0, 0.66, 0, 190, 4, 0, 0, 0, 0, 0, 0 ], [ 6, 0, 0.5714, 0.4286, 0, 0.66, 0.5, 826, 3, 0, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.1429, 0, 0.66, 1...
[ "x = [0]*10", "for i in range(10):\n x[i] += i\n x[i] += i*2", "print(x)" ]
s = set([2,3,4]) t = set([3,4,5]) u = set([1,3,5]) a = s.difference(t) b = u.difference(s) c = u.difference(t) print a print b print c print a == set([2]) print b == set([1,5]) print c == set([1]) d = s.difference(t, u) print d print d == set([2])
[ [ 14, 0, 0.05, 0.05, 0, 0.66, 0, 553, 3, 1, 0, 0, 21, 10, 1 ], [ 14, 0, 0.1, 0.05, 0, 0.66, 0.0714, 15, 3, 1, 0, 0, 21, 10, 1 ], [ 14, 0, 0.15, 0.05, 0, 0.66, 0...
[ "s = set([2,3,4])", "t = set([3,4,5])", "u = set([1,3,5])", "a = s.difference(t)", "b = u.difference(s)", "c = u.difference(t)", "print(a)", "print(b)", "print(c)", "print(a == set([2]))", "print(b == set([1,5]))", "print(c == set([1]))", "d = s.difference(t, u)", "print(d)", "print(d ==...
print "%s:%r:%d:%x" % ("dog", "cat", 23456, 999999999999L)
[]
[]
x=1 if x == 1: print "yes"
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 190, 1, 0, 0, 0, 0, 1, 0 ], [ 4, 0, 0.8333, 0.6667, 0, 0.66, 1, 0, 0, 0, 0, 0, 0, 0, 1 ], [ 8, 1, 1, 0.3333, 1, 0.09, 0, ...
[ "x=1", "if x == 1:\n print(\"yes\")", " print(\"yes\")" ]
print 'Hello'; print "stuff"; print "things"
[]
[]
for i in (i*2 for i in range(3)): print i
[ [ 6, 0, 0.75, 1, 0, 0.66, 0, 826, 5, 0, 0, 0, 0, 0, 2 ], [ 8, 1, 1, 0.5, 1, 0.02, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "for i in (i*2 for i in range(3)):\n print(i)", " print(i)" ]
print len("\\0")
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print(len(\"\\\\0\"))" ]
x = [] x.append(x) print x<x
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 243, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1...
[ "x = []", "x.append(x)", "print(x<x)" ]
print str((1,2,3)) print str([1,2,3]) print str({1:'ok', 2:'stuff'}) print str("weewaa")
[ [ 8, 0, 0.25, 0.25, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 8, 0, 0.5, 0.25, 0, 0.66, 0.3333, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 0.6667,...
[ "print(str((1,2,3)))", "print(str([1,2,3]))", "print(str({1:'ok', 2:'stuff'}))", "print(str(\"weewaa\"))" ]
a = range(30) print a[-10::5] print a[-10::-6] a = tuple(range(30)) print a[-10::5] print a[-10::-6]
[ [ 14, 0, 0.1667, 0.1667, 0, 0.66, 0, 475, 3, 1, 0, 0, 816, 10, 1 ], [ 8, 0, 0.3333, 0.1667, 0, 0.66, 0.2, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.5, 0.1667, 0, 0.66, ...
[ "a = range(30)", "print(a[-10::5])", "print(a[-10::-6])", "a = tuple(range(30))", "print(a[-10::5])", "print(a[-10::-6])" ]
print {1:'stuff', 'ok':4}
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print({1:'stuff', 'ok':4})" ]
def f(a, b, **c): sortc = [(x,y) for x,y in c.items()] sortc.sort() print a, b, sortc f(1, 2, d=4, e=5) f(1, b=4, e=5) f(a=1, b=4, e=5, f=6, g=7)
[ [ 2, 0, 0.3125, 0.5, 0, 0.66, 0, 899, 0, 3, 0, 0, 0, 0, 3 ], [ 14, 1, 0.25, 0.125, 1, 0.82, 0, 934, 5, 0, 0, 0, 0, 0, 1 ], [ 8, 1, 0.375, 0.125, 1, 0.82, 0.5, ...
[ "def f(a, b, **c):\n sortc = [(x,y) for x,y in c.items()]\n sortc.sort()\n print(a, b, sortc)", " sortc = [(x,y) for x,y in c.items()]", " sortc.sort()", " print(a, b, sortc)", "f(1, 2, d=4, e=5)", "f(1, b=4, e=5)", "f(a=1, b=4, e=5, f=6, g=7)" ]
a,b = "OK" print a+b
[ [ 14, 0, 0.5, 0.5, 0, 0.66, 0, 127, 1, 0, 0, 0, 0, 3, 0 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "a,b = \"OK\"", "print(a+b)" ]
print " hello ".partition("x") print " hello ".rpartition("x")
[ [ 8, 0, 0.5, 0.5, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print(\" hello \".partition(\"x\"))", "print(\" hello \".rpartition(\"x\"))" ]
print "".join(["O"]+["K"])
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print(\"\".join([\"O\"]+[\"K\"]))" ]
print slice(1)
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print(slice(1))" ]
print len([1,2,3])
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print(len([1,2,3]))" ]
x = [v*v for v in range(0,5)] print x[3]
[ [ 14, 0, 0.5, 0.5, 0, 0.66, 0, 190, 5, 0, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "x = [v*v for v in range(0,5)]", "print(x[3])" ]
class X: pass print type(X) x = X() print type(x) print x class Y(object): pass print type(Y) y = Y() print type(y) print y
[ [ 3, 0, 0.1, 0.1, 0, 0.66, 0, 783, 0, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 0.2, 0.1, 0, 0.66, 0.1111, 535, 3, 1, 0, 0, 0, 0, 2 ], [ 14, 0, 0.3, 0.1, 0, 0.66, 0.2222, ...
[ "class X: pass", "print(type(X))", "x = X()", "print(type(x))", "print(x)", "class Y(object): pass", "print(type(Y))", "y = Y()", "print(type(y))", "print(y)" ]
print "a"*15 print "dog"*19 print 40*"weee"
[ [ 8, 0, 0.3333, 0.3333, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1,...
[ "print(\"a\"*15)", "print(\"dog\"*19)", "print(40*\"weee\")" ]
def wee(waa, woo=True, wii=False): print waa, woo, wii wee("OK")
[ [ 2, 0, 0.5, 0.6667, 0, 0.66, 0, 48, 0, 3, 0, 0, 0, 0, 1 ], [ 8, 1, 0.6667, 0.3333, 1, 0.37, 0, 535, 3, 3, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1, 4...
[ "def wee(waa, woo=True, wii=False):\n print(waa, woo, wii)", " print(waa, woo, wii)", "wee(\"OK\")" ]
print "aa..bbb...ccc".replace("..", "X")
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print(\"aa..bbb...ccc\".replace(\"..\", \"X\"))" ]
x = {} x['y'] = "test" print x['y']
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 190, 0, 0, 0, 0, 0, 6, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 0, 1, 0, 0, 0, 0, 3, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1,...
[ "x = {}", "x['y'] = \"test\"", "print(x['y'])" ]
def f(n): yield 1 a, b = n, n + 1 yield 2 yield a yield b a = 9999 b = 9999 for i in f(20): print i
[ [ 2, 0, 0.35, 0.6, 0, 0.66, 0, 899, 0, 1, 0, 0, 0, 0, 0 ], [ 8, 1, 0.2, 0.1, 1, 0.41, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.3, 0.1, 1, 0.41, 0.25, 127, ...
[ "def f(n):\n yield 1\n a, b = n, n + 1\n yield 2\n yield a\n yield b", " yield 1", " a, b = n, n + 1", " yield 2", " yield a", " yield b", "a = 9999", "b = 9999", "for i in f(20):\n print(i)", " print(i)" ]
x = 1 n = 0 while x < 10: x = x + 1 if n == 2: continue n = n + 1 print n
[ [ 14, 0, 0.125, 0.125, 0, 0.66, 0, 190, 1, 0, 0, 0, 0, 1, 0 ], [ 14, 0, 0.25, 0.125, 0, 0.66, 0.3333, 773, 1, 0, 0, 0, 0, 1, 0 ], [ 5, 0, 0.625, 0.625, 0, 0.66, ...
[ "x = 1", "n = 0", "while x < 10:\n x = x + 1\n if n == 2:\n continue\n n = n + 1", " x = x + 1", " if n == 2:\n continue", " n = n + 1", "print(n)" ]
def f(n): for i in range(n): yield i g = f(5) print g.next() print g.next() print g.next() print g.next()
[ [ 2, 0, 0.25, 0.375, 0, 0.66, 0, 899, 0, 1, 0, 0, 0, 0, 1 ], [ 6, 1, 0.3125, 0.25, 1, 0.45, 0, 826, 3, 0, 0, 0, 0, 0, 1 ], [ 8, 2, 0.375, 0.125, 2, 0.13, 0, ...
[ "def f(n):\n for i in range(n):\n yield i", " for i in range(n):\n yield i", " yield i", "g = f(5)", "print(g.next())", "print(g.next())", "print(g.next())", "print(g.next())" ]
print "Yes" if True else "No" print "Yes" if False else "No"
[ [ 8, 0, 0.5, 0.5, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(\"Yes\" if True else \"No\")", "print(\"Yes\" if False else \"No\")" ]
print True and True
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(True and True)" ]
xyzy = [100,101,102,103,104,105,106,107] del xyzy print xyzy
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 100, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 2, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "xyzy = [100,101,102,103,104,105,106,107]", "print(xyzy)" ]
def x(): y = lambda x,y,z: x*y+z print y(5, 10, 15) x()
[ [ 2, 0, 0.5, 0.75, 0, 0.66, 0, 190, 0, 0, 0, 0, 0, 0, 2 ], [ 14, 1, 0.5, 0.25, 1, 0.4, 0, 304, 9, 0, 0, 0, 0, 0, 0 ], [ 8, 1, 0.75, 0.25, 1, 0.4, 1, 535, ...
[ "def x():\n y = lambda x,y,z: x*y+z\n print(y(5, 10, 15))", " y = lambda x,y,z: x*y+z", " print(y(5, 10, 15))", "x()" ]
x = [] x.append(x) print({x:'OK'}[x])
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 190, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 243, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1...
[ "x = []", "x.append(x)", "print({x:'OK'}[x])" ]
# Tests the list functions. l = [1,1,2,3,5,8,13,21] print l print l.count(1) print l.reverse() print l print l.count(1) print l.count(0) print l.count(3) print l.index(5) print l.remove(5) print l.remove(1) print l.count(1) print l
[ [ 14, 0, 0.1429, 0.0714, 0, 0.66, 0, 810, 0, 0, 0, 0, 0, 5, 0 ], [ 8, 0, 0.2143, 0.0714, 0, 0.66, 0.0833, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.2857, 0.0714, 0, 0.6...
[ "l = [1,1,2,3,5,8,13,21]", "print(l)", "print(l.count(1))", "print(l.reverse())", "print(l)", "print(l.count(1))", "print(l.count(0))", "print(l.count(3))", "print(l.index(5))", "print(l.remove(5))", "print(l.remove(1))", "print(l.count(1))", "print(l)" ]
class X: pass y = X() print "OK"
[ [ 3, 0, 0.375, 0.5, 0, 0.66, 0, 783, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0.5, 304, 3, 0, 0, 0, 783, 10, 1 ], [ 8, 0, 1, 0.25, 0, 0.66, 1, 5...
[ "class X:\n pass", "y = X()", "print(\"OK\")" ]
# using obj[token] in JS doesn't work as a generic string dict # make sure to use *both* hasOwnProperty and then get it, otherwise object # builtins will return existence. def toString(): print "wee" class stuff: def toString(self): return "waa" def valueOf(self): return "stuff" toString() s = stuff() print s.toString() print s.valueOf()
[ [ 2, 0, 0.2812, 0.125, 0, 0.66, 0, 661, 0, 0, 0, 0, 0, 0, 1 ], [ 8, 1, 0.3125, 0.0625, 1, 0.58, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 3, 0, 0.5625, 0.3125, 0, 0.66, ...
[ "def toString():\n print(\"wee\")", " print(\"wee\")", "class stuff:\n def toString(self):\n return \"waa\"\n def valueOf(self):\n return \"stuff\"", " def toString(self):\n return \"waa\"", " return \"waa\"", " def valueOf(self):\n return \"stuff\"", ...
print 1 in {1:2}
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(1 in {1:2})" ]
for k in {'OK':0}: print k
[]
[]
print str(range(-4,-8,-1))[:5] print len(range(-4,-8,-1)) print range(-4,-8,-1)[0] print range(-4,-8,-1)[1] print range(-4,-8,-1)[-1]
[ [ 8, 0, 0.2, 0.2, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 3 ], [ 8, 0, 0.4, 0.2, 0, 0.66, 0.25, 535, 3, 1, 0, 0, 0, 0, 3 ], [ 8, 0, 0.6, 0.2, 0, 0.66, 0.5, 535, ...
[ "print(str(range(-4,-8,-1))[:5])", "print(len(range(-4,-8,-1)))", "print(range(-4,-8,-1)[0])", "print(range(-4,-8,-1)[1])", "print(range(-4,-8,-1)[-1])" ]
def test(): pass x = 1 print test()
[ [ 2, 0, 0.3333, 0.3333, 0, 0.66, 0, 224, 0, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 190, 1, 0, 0, 0, 0, 1, 0 ], [ 8, 0, 1, 0.3333, 0, 0.66, 1...
[ "def test(): pass", "x = 1", "print(test())" ]
x = 444 def f(arg): return "OK: " + arg + ", " + str(x)
[ [ 14, 0, 0.3333, 0.3333, 0, 0.66, 0, 190, 1, 0, 0, 0, 0, 1, 0 ], [ 2, 0, 0.8333, 0.6667, 0, 0.66, 1, 899, 0, 1, 1, 0, 0, 0, 1 ], [ 13, 1, 1, 0.3333, 1, 0.31, 0,...
[ "x = 444", "def f(arg):\n return \"OK: \" + arg + \", \" + str(x)", " return \"OK: \" + arg + \", \" + str(x)" ]
x = [10] * 5 x[:3] += 100,100 print x
[ [ 14, 0, 0.2, 0.2, 0, 0.66, 0, 190, 4, 0, 0, 0, 0, 0, 0 ], [ 8, 0, 1, 0.2, 0, 0.66, 2, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "x = [10] * 5", "print(x)" ]
print [x*x for x in range(20) if x > 10 if x % 2 == 0]
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 2 ] ]
[ "print([x*x for x in range(20) if x > 10 if x % 2 == 0])" ]
a = [1,2,3,4,5,6] b = [9,9,9] a[2] = b print a
[ [ 14, 0, 0.25, 0.25, 0, 0.66, 0, 475, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.5, 0.25, 0, 0.66, 0.3333, 756, 0, 0, 0, 0, 0, 5, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0.66...
[ "a = [1,2,3,4,5,6]", "b = [9,9,9]", "a[2] = b", "print(a)" ]
class C: def __init__(self, data): self.data = data def pr(self): print self.data C("OK").pr()
[ [ 3, 0, 0.5, 0.8333, 0, 0.66, 0, 619, 0, 2, 0, 0, 0, 0, 1 ], [ 2, 1, 0.4167, 0.3333, 1, 0.36, 0, 555, 0, 2, 0, 0, 0, 0, 0 ], [ 14, 2, 0.5, 0.1667, 2, 0.02, 0, ...
[ "class C:\n def __init__(self, data):\n self.data = data\n def pr(self):\n print(self.data)", " def __init__(self, data):\n self.data = data", " self.data = data", " def pr(self):\n print(self.data)", " print(self.data)", "C(\"OK\").pr()" ]
big = 012345670123456701234567012345670L # 32 octal digits print "'%o'" % big print "'%o'" % -big print "'%5o'" % -big print "'%33o'" % -big print "'%34o'" % -big print "'%-34o'" % -big print "'%034o'" % -big print "'%-034o'" % -big print "'%036o'" % -big print "'%036o'" % big print "'%0+36o'" % big print "'%+36o'" % big print "'%36o'" % big print "'%.2o'" % big print "'%.32o'" % big print "'%.33o'" % big print "'%34.33o'" % big print "'%-34.33o'" % big print "'%o'" % big print "'%#o'" % big print "'%#o'" % -big print "'%#.34o'" % -big print "'%#+.34o'" % big print "'%# .34o'" % big print "'%#+.34o'" % big print "'%#-+.34o'" % big print "'%#-+37.34o'" % big print "'%#+37.34o'" % big # next one gets one leading zero from precision print "'%.33o'" % big # base marker shouldn't change that print "'%#.33o'" % big # but reduce precision print "'%#.32o'" % big # one leading zero from precision print "'%034.33o'" % big # base marker shouldn't change that print "'%0#34.33o'" % big
[ [ 8, 0, 0.0256, 0.0256, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.0513, 0.0256, 0, 0.66, 0.0312, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.0769, 0.0256, 0, 0.66...
[ "print(\"'%o'\" % big)", "print(\"'%o'\" % -big)", "print(\"'%5o'\" % -big)", "print(\"'%33o'\" % -big)", "print(\"'%34o'\" % -big)", "print(\"'%-34o'\" % -big)", "print(\"'%034o'\" % -big)", "print(\"'%-034o'\" % -big)", "print(\"'%036o'\" % -big)", "print(\"'%036o'\" % big)", "print(\"'%0+36o'...
print "OKx"[:-1]
[ [ 8, 0, 1, 1, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ] ]
[ "print(\"OKx\"[:-1])" ]