__id__
int64
3.09k
19,722B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
256
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
3 values
repo_name
stringlengths
5
109
repo_url
stringlengths
24
128
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
6.65k
581M
star_events_count
int64
0
1.17k
fork_events_count
int64
0
154
gha_license_id
stringclasses
16 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
5.76M
gha_stargazers_count
int32
0
407
gha_forks_count
int32
0
119
gha_open_issues_count
int32
0
640
gha_language
stringlengths
1
16
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
9
4.53M
src_encoding
stringclasses
18 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
year
int64
1.97k
2.01k
919,123,033,131
e87c2936bf9f3d445effee579804efbcf518191b
cb74b1319dc6d0efcb570d042f0db62fa5493f56
/hypestarter/artists/urls.py
e602ffa175088e21435e37abe323fd61a8dab72f
[]
no_license
thekashifmalik/hypestarter
https://github.com/thekashifmalik/hypestarter
f32d2ff24f27136a4c81f5a3f632bde137286729
e02973ee68e5fd727cb494e22aa9cf86b45557d3
refs/heads/master
2021-05-26T17:25:54.195191
2013-04-14T04:28:13
2013-04-14T04:28:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import patterns, url urlpatterns = patterns('artists.views', url(r'^(?P<artist_id>\d+)/$', 'show', name='show_artist'), url(r'^hot/$', 'hot', name='hot_artists') )
UTF-8
Python
false
false
2,013
18,408,229,849,278
04644d44df252ecf1e5f4a8e4449fbe952f74829
c41b369041ec670d9fbbaa39f0e336f9e39be938
/fullstackweb/api/api.py
057b6f9c1c9ecbb138e06fe69adf944be3eb7832
[ "MIT" ]
permissive
rorymurphy/exercises
https://github.com/rorymurphy/exercises
d8927ca0db619719c195a6b4347f373a44f9cd72
cd64e9509755d458928e9a3659480ce61972dd44
refs/heads/master
2020-12-13T20:54:33.752704
2014-04-18T14:04:59
2014-04-18T14:04:59
18,538,624
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os.path import json import logging import tornado.escape import tornado.ioloop import tornado.web from tornado import gen from tornado.options import define, options, parse_command_line from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from models import Product, Image from . import Session, Base define("port", default=8888, help="port to run on", type=int) #just a marker to indicate this will be created by app = None class ProductListHandler(tornado.web.RequestHandler): def get(self): session = Session() models = session.query(Product).order_by(Product.id) result = [] for mod in models: result.append(mod.as_dict()) self.set_header('Content-Type', 'application/json') self.write(json.dumps(result)) def post(self): data = json.loads(self.request.body) model = Product(data) session = Session() session.add(model) session.commit() class ProductDetailsHandler(tornado.web.RequestHandler): def get(self, prod_id): #self.write(prod_id) session = Session() model = session.query(Product).filter_by(id = prod_id).first() if model == None: raise tornado.web.HTTPError(404) self.set_header('Content-Type', 'application/json') self.write(json.dumps(model.as_dict())) def update(self): self.write('Not Implemented') def start_app(): app = tornado.web.Application([ (r"/product/", ProductListHandler), (r"/product/([a-f0-9]+)/", ProductDetailsHandler), ]) app.listen(options.port) if __name__ == "__main__": parse_command_line() engine = create_engine('sqlite:///app/retailmenot/retailmenot/db.sqlite3') Session.configure(bind=engine) Base.metadata.bind = engine start_app() tornado.ioloop.IOLoop.instance().start()
UTF-8
Python
false
false
2,014
16,862,041,644,764
ec5bab34a1b79ee96b651845935f5db79eba11df
4989aaba6cd32da852d42f9fa5cf7a3fd3c5ffa3
/testDatacenter.py
3edc3f08ad9a2c7e0b971de766c421d36fc2dee9
[]
no_license
wenjiechen/dataCenter
https://github.com/wenjiechen/dataCenter
6bae86aa677abc9857c9b47742dc47697a137470
96748e71aeae919beb88b54c1c37c84cc89a3d26
refs/heads/master
2021-01-15T22:29:22.847273
2014-05-12T16:12:50
2014-05-12T16:12:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Test datacenter module and provide example of how to use datacenter module ''' import unittest import datacenter from devicemodels import Spine, Leaf, Host,Rack __author__ = 'Wenjie Chen' class TestDataCenter(unittest.TestCase): def setUp(self): '''Create standard test model ''' path = 'dcModel2.csv' self.dc = datacenter.DataCenter() self.dc.load_model_from_files(path) self.device_cmp = lambda x,y : cmp(str(x), str(y)) def test_clean_model(self): ''' remove all devices in model ''' self.dc.clean_datacenter() self.assertEqual([],self.dc.all_devices) def test_load_model_from_one_file(self): ''' ensure all edges and nodes are added ''' self.dc.clean_datacenter() self.dc.load_model_from_files('testModel2.csv') devices = self.dc.all_devices devices.sort(cmp=self.device_cmp) expected = [Spine(1),Leaf(1),Leaf(2),Host(1),Host(2),Rack(1)] expected.sort(cmp=self.device_cmp) self.assertEqual(devices,expected) def test_load_model_from_two_files(self): ''' ensure all nodes and edges in two files are added ''' self.dc.clean_datacenter() file1 = 'testModel2.csv' file2 = 'testModel3.csv' self.dc.load_model_from_files(file1,file2) devices = self.dc.all_devices devices.sort(cmp=self.device_cmp) expected = [Spine(1),Leaf(1),Leaf(2),Host(1),Host(2),Host(3),Rack(1)] expected.sort(cmp=self.device_cmp) self.assertEqual(devices,expected) def test_load_model_by_pipeline_delimiter(self): ''' change the model file's delimiter to pipeline '|' ''' self.dc.clean_datacenter() self.dc.load_model_from_files('testModelPipeline.csv',delimiter='|') devices = self.dc.all_devices devices.sort(cmp=self.device_cmp) expected = [Spine(1),Leaf(1)] expected.sort(cmp=self.device_cmp) self.assertEqual(devices,expected) def test_load_model_raise_exception(self): ''' Wrong data in model file. e.g. bad ID 's1' for Spine. Spine ID should be integer ''' with self.assertRaises(Exception): self.dc.load_model_from_files('testBadModel.csv') def test_access_device_with_string(self): '''access Spine(1) and with string. the string pattern can be 'spine1','spine-1' or 'spine_1', no matter lower or upper case ''' self.assertEqual(Spine(1),self.dc.get_device('spine1')) self.assertEqual(Spine(1),self.dc.get_device('Spine-1')) self.assertEqual(Spine(1),self.dc.get_device('Spine_1')) def test_access_device_with_wrong_string_pattern(self): '''access device using string, raise TypeError ''' with self.assertRaises(ValueError): self.dc.remove_devices('spines1') with self.assertRaises(ValueError): self.dc.remove_devices('host-s1') def test_remove_link(self): '''remove link Spine(1)-Leaf(1), check if it still exists in model. ''' self.dc.remove_link(Spine(1),Leaf(1)) is_exist = (Spine(1),Leaf(1)) in self.dc.all_links self.assertEqual(False,is_exist) def test_remove_device(self): ''' remove Host(1) links host1-leaf1,host1-leaf2 are removed, and remove from Rack1 ''' self.dc.remove_devices(Host(1)) is_exist1 = (Host(1),Leaf(1)) in self.dc.all_links is_exist2 = (Host(1),Leaf(2)) in self.dc.all_links is_exist3 = Host(1) in self.dc.get_devices_in_rack(Rack(1)) self.assertEqual(False,is_exist1) self.assertEqual(False,is_exist2) self.assertEqual(False,is_exist3) def test_remove_two_devices(self): ''' remove Host(1),Host(2) links host1-leaf1,host1-leaf2 are removed, and remove from Rack1 links host2-leaf1,host2-leaf2 are removed, and remove from Rack1 ''' self.dc.remove_devices(Host(1),Host(2)) is_exist1 = (Host(1),Leaf(1)) in self.dc.all_links is_exist2 = (Host(1),Leaf(2)) in self.dc.all_links is_exist3 = Host(1) in self.dc.get_devices_in_rack(Rack(1)) is_exist4 = (Host(2),Leaf(1)) in self.dc.all_links is_exist5 = (Host(2),Leaf(2)) in self.dc.all_links is_exist6 = Host(2) in self.dc.get_devices_in_rack(Rack(1)) self.assertEqual(False,is_exist1) self.assertEqual(False,is_exist2) self.assertEqual(False,is_exist3) self.assertEqual(False,is_exist4) self.assertEqual(False,is_exist5) self.assertEqual(False,is_exist6) def test_query_device_on_port_without_rackid(self): ''' Find device connected to port2 of host(1). Because each device is uniquely defined by its ID, host1 can be identified without rack num. ''' device = self.dc.query_device(Host(1),2) self.assertEqual(Leaf(2),device) def test_query_device_on_port_with_right_rackid(self): ''' find device connected to port2 of host(1) in rack1 ''' device = self.dc.query_device(Host(1),2,Rack(1)) self.assertEqual(Leaf(2),device) def test_query_device_on_port_with_wrong_rackid(self): ''' find device connected to port2 of host(1) in rack2 because host1 is not in rack2, return None, print warning to stderr ''' device = self.dc.query_device(Host(1),2,Rack(2)) self.assertEqual(None,device) def test_query_device_on_port_with_not_exist_rackid(self): ''' find device connected to port2 of host(1) in rack3 because rack3 is not exist, return None, print warning to stderr ''' device = self.dc.query_device(Host(1),2,Rack(3)) self.assertEqual(None,device) def test_query_connected_one_port_without_rackid(self): ''' port1 of leaf1 connects to spine1. leaf1 and spine1 can be identified by their id without rack id ''' ports = self.dc.query_ports(Leaf(1),Spine(1)) self.assertEqual([1],ports) def test_query_connected_two_ports_without_rackid(self): ''' port1 and port100 of leaf1 connects to spine1 ''' self.dc.load_model_from_files('testModelMultiLink.csv') ports = self.dc.query_ports(Leaf(1),Spine(1)) self.assertEqual([1,100],sorted(ports)) def path_cmp(self,x,y): '''path comparator Compare based on string of nodes in paths ''' if len(x) != len(y): raise Exception("lengths of two paths are not equal.") for xi,yi in zip(x,y): ret = cmp(str(xi),str(yi)) if ret > 0: return 1 elif ret < 0: return -1 return 0 def test_query_all_paths(self): ''' find all paths from leaf-1 to host-12 ''' paths = self.dc.query_all_paths(Leaf(1),Host(12)) paths = sorted(paths,cmp = lambda x,y: self.path_cmp(x,y)) expected=[[Leaf(1), Spine(1), Leaf(3), Host(12)], [Leaf(1), Spine(2), Leaf(3), Host(12)], [Leaf(1), Spine(1), Leaf(4), Host(12)], [Leaf(1), Spine(2), Leaf(4), Host(12)]] expected = sorted(expected,cmp = lambda x,y: self.path_cmp(x,y)) self.assertEqual(expected,paths) def test_link_check(self): '''break link leaf1-host1 and leaf1-spine1, then find the broken links ''' self.dc.break_link(Leaf(1),Host(1)) self.dc.break_link(Leaf(1),Spine(1)) self.dc.break_link(Leaf(3),Spine(2)) self.dc.break_link(Leaf(3),Host(12)) broken_links = self.dc.check_link() broken_links = sorted(broken_links,cmp = lambda x,y: self.path_cmp(x,y)) expected = [(Leaf(1),Host(1)),(Leaf(1),Spine(1)),(Leaf(3),Spine(2)),(Leaf(3),Host(12))] expected = sorted(expected,cmp = lambda x,y: self.path_cmp(x,y)) self.assertEqual(expected,broken_links) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
2,869,038,193,637
162fa0ff45c3668472d1c286ad27faab670ccfbd
615392d01a49303644e188add7f22468fa4d9147
/book/oop/object-pursuit.py
054d82f90e90732ae33c9f0de82c6ad849a6b9f6
[]
no_license
apawlik/assets
https://github.com/apawlik/assets
ab99e80699a6b80ffb7c78bbe8c8cbd6903817f6
b73430a67fe2513cdda51fd565e2522f82a761ba
refs/heads/master
2017-11-14T10:00:30.583463
2014-01-29T20:55:30
2014-01-29T20:55:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from turtle import Turtle, mainloop class Raptor(object): def __init__(self, distance, color, speed): self.turtle = Turtle() self.speed = speed self.turtle.pencolor(color) self.turtle.penup() self.turtle.forward(distance) self.turtle.pendown() def move(self, target): angle = self.turtle.towards(target) self.turtle.setheading(angle) self.turtle.forward(self.speed) class Duckbill(object): def __init__(self, distance, color, speed, angle): self.turtle = Turtle() self.turtle.pencolor(color) self.speed = speed self.angle = angle self.turtle.penup() self.turtle.forward(distance) self.turtle.pendown() self.turtle.left(90) def move(self): self.turtle.forward(self.speed) self.turtle.left(self.angle) raptors = [Raptor(-200, "red", 5), Raptor(-200, "orange", 7), Raptor(-200, "yellow", 9)] duckbill = Duckbill(200, "green", 8, 6) for i in range(240): for r in raptors: r.move(duckbill.turtle.pos()) duckbill.move() mainloop()
UTF-8
Python
false
false
2,014
13,262,859,044,002
555a0d7b0587d3cde2a109c8cd522625d7c1f2e7
b84b5e19c18732b146f384a43efbf557d74fac1b
/ETL/q2/2col.py
bbdaf7d8e037bd9a6eeb5181275edc24638da3b8
[]
no_license
rainyyang5/Twitter-Analytics-Web-Service
https://github.com/rainyyang5/Twitter-Analytics-Web-Service
58dfee77fd30c22e6db319e51f44c231c5563524
c6afd79fc46e1a6dfbe90d8ef84448cd12d6d267
refs/heads/master
2015-08-18T03:13:19
2014-12-15T08:33:36
2014-12-15T08:33:36
28,027,238
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python # -- coding: utf-8 -- import sys import re #preUser = None #preTime = None #preContent = None f = open('col2','w') for line in sys.stdin: line = line.strip() if line == '': continue fields = line.split('\t') if len(fields) < 3: continue user_id = fields[0] time = fields[1] content = fields[2].strip() #if user_id == preUser: # if time == preTime: # content = preContent + ‘;’ + content #utf_text = content.decode('unicode-escape','Ignore') #enc_text = utf_text.encode('utf8') f.write(user_id + '+' + time + '\t' + content + ';' +'\n') #printf user_id + ‘+’ + time + '\t' + content + ';' +'\n' f.close()
UTF-8
Python
false
false
2,014
14,989,435,905,789
c307bbaa88958bfa8c7d7bf464a36f499a840900
6cb4f434b708653603c48b1e7a6238a09e136763
/websocket_client.py
236e49aeaff7466910e1611f9370736be271bf30
[]
no_license
astralhpi/websocket_test
https://github.com/astralhpi/websocket_test
dc98a390f2bb4b707be51198f9d172f35a41a33f
467dca2ca51a3adf29e6cbb7c82c88cdd4478fe2
refs/heads/master
2021-01-19T17:14:32.838935
2014-04-13T14:05:34
2014-04-13T14:05:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import gevent from gevent import monkey monkey.patch_all() from websocket import create_connection import random import time spawn_count = 1000 def random_hash(): return "%032x" % random.getrandbits(128) count = 0 error = 0 start_time = time.time() def echo(): global count global error try: ws = create_connection('ws://182.162.143.241:8000/echo') except: time.sleep(1) ws = create_connection('ws://182.162.143.241:8000/echo') start_time = time.time() cur_time = time.time() while cur_time - start_time < 10.0: value = random_hash() ws.send(value) result = ws.recv() count += 1 if result != value: error += 1 cur_time = time.time() time.sleep(1) ws.close() gevent.joinall( [gevent.spawn(echo) for i in xrange(0, spawn_count)], timeout=10.0 ) print "echo: %i, error: %i, echo per sec: %f" % ( count, error, count/(time.time()-start_time))
UTF-8
Python
false
false
2,014
4,956,392,276,133
b378908a721b90abfbdb011a278a44308dee341b
d9bd7d314531f9a2a85e285b70438486b441e39a
/nightlyserver/server/db_info.py
3ed9a76d05f9d38acfb69153e881518c6e8c62ba
[]
no_license
QPC-WORLDWIDE/chitools
https://github.com/QPC-WORLDWIDE/chitools
47607eca86fb063ef08a5729a2d81a5dcf7b10d2
ca7ae27645ffa63147c2550386468cdae304b4d5
refs/heads/master
2021-12-02T21:00:35.142316
2012-11-01T22:13:33
2012-11-01T22:13:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This info is needed in multiple places COLLECTION_CASE_INDEX = 'CaseIndex' COLLECTION_CASES = 'Cases' COLLECTION_ORPHANS = 'OrphanCases' COLLECTION_SERVICES = 'Services' COLLECTION_API_KEYS = 'APIKeys' COLLECTION_OUTCOMES = 'Outcomes'
UTF-8
Python
false
false
2,012
858,993,479,763
f0b4c293118abf90fb50f9343f7f0499fe8d7107
e61fff918c231f69b4a8526729c2f7e12a35fee9
/convo/models.py
759f6dd303a43b88569f1ff12a5c07e37d5289c2
[ "MIT" ]
permissive
manfredmacx/django-convo
https://github.com/manfredmacx/django-convo
6fead3e906f6abbca0fa1786f6007656c0b08be4
5176ada8fafa4e601794c39de2eee8b64b40595c
refs/heads/master
2021-01-19T12:58:55.326987
2011-11-22T02:14:53
2011-11-22T02:14:53
551,895
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models from django.contrib.auth.models import User from django.db.models import Max class EntryManager(models.Manager): def get_convo(self, entry): """ return this object and all children """ return self.filter(models.Q(original=entry) | models.Q(pk=entry.id)) def get_convo_last_modified(self, entry): return self.get_convo(entry).order_by('date_modified').reverse()[0] class Entry(models.Model): original = models.ForeignKey('self', null=True, related_name="original_entry") parent = models.ForeignKey('self', null=True, related_name="parent_entry") title = models.CharField(max_length = 150) slug = models.SlugField(max_length=250, db_index=True, editable=False, unique=True) body = models.TextField(max_length = 4000) owner = models.ForeignKey(User, null=True) owner_if_anonymous = models.CharField(max_length = 150, null=True) url_if_anonymous = models.URLField(max_length = 1000, null=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) level = models.IntegerField() type = models.CharField(max_length=50, default="ALL") published = models.BooleanField(default=True) objects = EntryManager() def __unicode__(self): return self.title def isOriginal(self): return self.original is None def getOriginal(self): if self.isOriginal(): return self else: return self.original def userCanEdit(self, user): orig = self.getOriginal() own = self.owner or None return (own == user or orig.owner == user or own is None) def _child_count(self): return Entry.objects.filter(models.Q(original=self) | models.Q(pk=self.id)).count() - 1 def save(self, *args, **kwargs): self.level = self.parent.level + 1 if self.parent is not None else 1 i = 2 while True: try: from django.template.defaultfilters import slugify from django.db import IntegrityError if not self.id: self.slug = slugify(self.title) super(Entry, self).save(*args, **kwargs) except IntegrityError: self.slug = slugify("-".join((self.title,str(i),))) try: super(Entry, self).save(*args, **kwargs) except IntegrityError: i += 1 else: break else: break #TODO - needs to be generic def get_absolute_url(self): if self.type == "BLOG": return "/blog/{0}/{1}/{2}/{3}".format(self.date_created.year, self.date_created.month, self.date_created.day, self.slug) if self.type == "PAGE": return "/info/{0}".format(self.slug,) return "/social/{0}/convo".format(self.id) def _convo_last_mod_date(self): return self.objects.get_convo_last_modified(self).date_modified def __cmp__(self, other): return cmp(self.date_modified, other.date_modified) convo_last_mod_date = property(_convo_last_mod_date) child_count = property(_child_count) class Edit(models.Model): edit_by = models.ForeignKey(User) entry = models.ForeignKey(Entry) date_created = models.DateField(auto_now_add=True)
UTF-8
Python
false
false
2,011
16,887,811,446,280
d74d6845b9de1aaf945b38e7475b8e2ea79c21b4
157a236e788326900ffce68436f4bb1b2b2b9d0f
/tests/test_address.py
97d616cae50c93bac8a92ccde442fe5510393da9
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
ingydotnet/peglite-py
https://github.com/ingydotnet/peglite-py
2109b222b62e74418ac226b4fd1471806deee367
971cfde00c3c6a10d24ed8f8cd960a70c0aeb999
refs/heads/master
2023-06-19T03:00:38.438518
2013-01-05T00:39:38
2013-01-05T00:39:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This PegLite test shows an address grammar parsing a street address. # We parse it 3 different ways, to get different desired results. from package.unittest import * from peglite import * import yaml import sys # A sample street address address = """\ John Doe 123 Main St Los Angeles, CA 90009 """ # Expected result tree for default/plain parsing parse_plain = """\ - John Doe - 123 Main St - - Los Angeles - CA - '90009' """ # Expected result tree using the 'wrap' option parse_wrap = """\ address: - - name: - John Doe - street: - 123 Main St - place: - - city: - Los Angeles - state: - CA - zip: - '90009' """ # Expected result tree from our Custom parser extension parse_custom = """\ name: John Doe street: 123 Main St city: Los Angeles state: CA zipcode: '90008' """ # Run 3 tests class TestAddressParser(TestCase): # Parse address to an array of arrays def test_plain(self): parser = AddressParser() result = parser.parse(address) self.assertEqual(yaml.dump(result), parse_plain, "Plain parse works") # Turn on 'wrap' to add rule name to each result def test_wrap(self): parser = AddressParser(wrap=True) result = parser.parse(address) self.assertEqual(yaml.dump(result), parse_wrap, "Wrapping parse works") # Return a custom AST def test_custom(self): parser = AddressParserCustom() result = parser.parse(address) self.assertEqual(yaml.dump(result), parse_custom, "Custom parse works") # This class defines a complete address parser using PegLite class AddressParser(PegLite): rule('address', 'name street place') rule('name', r'/(.*?)/') rule('street', r'/(.*?)\n/') rule('place', 'city COMMA _ state __ zip NL') rule('city', r'/(\w+(?: \w+)?)/') rule('state', r'/(WA|OR|CA)/') # Left Coast Rulez rule('zip', r'/(\d{5})/') # Extend AddressParser class AddressParserCustom(AddressParser): def address(self): got = match if not got: return name, street, place = got[0] city, state, zip = place # Make the final AST from the parts collected. self.got = { 'name': name, 'street': street, 'city': city, 'state': state, # Show as 'zipcode' instead of 'zip' 'zipcode': zip, } return True # Subtract 1 from the zipcode for fun def zip(self): got = match if not got: return return (got[0].to_i - 1).to_s if __name__ == '__main__': main()
UTF-8
Python
false
false
2,013
3,702,261,857,540
9f60cfea355aa638dc0ee08e38316b1a4b025085
d53f89d18cb899ba54177180b4e7f6a9d3f1abee
/app.py
a745ef885c7e0713629d4f1d0a4b4cc9ad12fcf6
[ "MIT" ]
permissive
longhillroad/PersonalPasswordManager
https://github.com/longhillroad/PersonalPasswordManager
243ec079c3497f477bcb676ca31ee372f5cea203
9b6a95b90a24ff6e34685dbaeba9e0c1114636b9
refs/heads/master
2021-01-16T18:14:51.668035
2012-10-09T05:42:23
2012-10-09T05:42:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python from google.appengine.ext.webapp.util import run_wsgi_app from config import ROOT_DIRECTORY import os, sys sys.path.append(os.path.join(ROOT_DIRECTORY,"packages")) sys.path.append(os.path.join(ROOT_DIRECTORY,"packages","Flask")) from application import app run_wsgi_app(app)
UTF-8
Python
false
false
2,012
12,515,534,749,215
bc8193d710a46ca9cb2fdb41c6962663ffa350fc
29aecc6035d2ad345f041cf91ca5d657c8b71c3e
/recoverBinarySearchTree.py
f98099de656ce6278950ee6adb43393a72b2921f
[]
no_license
CiyoMa/leetcode
https://github.com/CiyoMa/leetcode
e85b58fbfd99cffc3c29d9bb21ad37dc9f4cb532
2f1b3de9801183d5822011639cce881d8f1acb70
refs/heads/master
2020-04-06T04:09:14.661162
2014-10-26T03:15:20
2014-10-26T03:15:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? """ # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a tree node def recoverTree(self, root): order = self.inOrder(root) #print [n.val for n in self.inOrder(root)] i = 0 bigger, smaller = None, None while i < len(order): if i == 0 and order[0].val > order[1].val: # and len(order) > 1 bigger = order[0] elif i == len(order) - 1 and order[i].val < order[i - 1].val: smaller = order[i] elif i > 0 and i < len(order) - 1: if order[i].val > order[i+1].val and bigger is None: bigger = order[i] elif order[i].val < order[i-1].val: smaller = order[i] i += 1 #print bigger.val, smaller.val #beware of the chain effect of the smaller one!! bigger.val, smaller.val = smaller.val, bigger.val #print [n.val for n in self.inOrder(root)] return root def inOrder(self, root): if root is None: return [] left = self.inOrder(root.left) right = self.inOrder(root.right) return left + [root] + right # t1 = TreeNode(2) # t2 = TreeNode(3) # t3 = TreeNode(1) # t1.left = t2 # t1.right = t3 t1 = TreeNode(2) t2 = TreeNode(3) t3 = TreeNode(1) t1.left = t2 t1.right = t3 s = Solution() print s.recoverTree(t1)
UTF-8
Python
false
false
2,014
11,312,943,894,257
b0bdaed7f3ba02dcfd15e12e8329ccc8ddeb1a56
f57284c47477a24b923ca211e03d3f26a4c835f7
/webpages/upload/post.py
869c1bbe80f55e128862bf8249cacdcd0092bf37
[]
no_license
hkg36/websockframework
https://github.com/hkg36/websockframework
e927e368e4ed8cb33ba2e757582b8c85c8d42e79
f7595ee286e95a788b45ee321782452f93dbf01e
refs/heads/master
2021-01-15T19:28:30.048323
2014-12-24T08:16:19
2014-12-24T08:16:19
14,298,020
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding:utf-8 from tools.helper import AutoFitJson __author__ = 'amen' import WebSiteBasePage import web import dbconfig import datamodel.post import website_config from webpages.MainPage import pusher import urllib import json import tools.crypt_session def post_token(uid): return dbconfig.qiniuAuth.upload_token(dbconfig.qiniuSpace,policy={"callbackUrl":'http://%s/upload/PostDone'%website_config.hostname, "callbackBody":'{"name":"$(fname)","hash":"$(etag)","width":"$(imageInfo.width)","height":"$(imageInfo.height)",' +\ '"gid":"$(x:gid)","content":"$(x:content)","length":"$(x:length)","uid":%d,"filetype":"$(x:filetype)"}'%uid}) class Post(WebSiteBasePage.AutoPage): def GET(self): params=web.input(usepage='0') sessionid=params.get('sessionid',None) if sessionid is None: return "No Session id" data=tools.crypt_session.DecodeCryptSession(sessionid) if data is None: data=dbconfig.redisdb.get(str('session:%s'%sessionid)) if data: data=json.loads(data) if data is None: return {"errno":1,"error":"session not found","result":{}} uptoken = post_token(data['uid']) if int(params['usepage'])==0: web.header("Content-type","application/json") return json.dumps({'token':uptoken}) tpl=WebSiteBasePage.jinja2_env.get_template('upload/Post.html') return tpl.render(token=uptoken) def POST(self): pass class PostDone(WebSiteBasePage.AutoPage): def POST(self): imgdata=json.loads(web.data()) with dbconfig.Session() as session: newpost=datamodel.post.Post() newpost.uid=imgdata['uid'] newpost.group_id=imgdata['gid'] content_data=imgdata.get('content') if content_data: newpost.content=urllib.unquote_plus(content_data.encode('ascii')).decode('utf-8') fileurl=dbconfig.qiniuDownLoadLinkHead+imgdata['hash'] filetype=int(imgdata['filetype']) if filetype==1: newpost.picture=fileurl newpost.width=imgdata['width'] newpost.height=imgdata['height'] elif filetype==2: newpost.voice=fileurl newpost.length=imgdata['length'] elif filetype==3: newpost.video=fileurl newpost.length=imgdata['length'] newpost=session.merge(newpost) session.commit() try: json_post=json.dumps(newpost.toJson(),cls=AutoFitJson) pusher.rawPush(routing_key='sys.post_to_notify',headers={},body=json_post) except Exception,e: return json.dumps({'errno':5,'error':str(e)}) return json.dumps({"errno":0,"error":"Success","result":{"url":fileurl,'postid':newpost.postid}},cls=AutoFitJson) def postex_token(postid): policy = qiniu.rs.PutPolicy(dbconfig.qiniuSpace) policy.callbackUrl='http://%s/upload/PostExDone'%website_config.hostname policy.callbackBody='{"name":"$(fname)","hash":"$(etag)","width":"$(imageInfo.width)","height":"$(imageInfo.height)",' +\ '"length":"$(x:length)","postid":%d,"filetype":"$(x:filetype)"}'%postid return policy.token() class PostEx(WebSiteBasePage.AutoPage): def GET(self): params=web.input(usepage='0') sessionid=params.get('sessionid',None) postid=params.get('postid',None) if sessionid is None: return "No Session id" if postid is None: return "No Post id" data=tools.crypt_session.DecodeCryptSession(sessionid) if data is None: data=dbconfig.redisdb.get(str('session:%s'%sessionid)) if data: data=json.loads(data) if data is None: return {"errno":1,"error":"session not found","result":{}} with dbconfig.Session() as session: oldpost=session.query(datamodel.post.Post).filter(datamodel.post.Post.postid==postid).first() if oldpost is None or oldpost.uid!=data['uid']: return "post not exists or not yours" uptoken = postex_token(int(postid)) if int(params['usepage'])==0: web.header("Content-type","application/json") return json.dumps({'token':uptoken}) tpl=WebSiteBasePage.jinja2_env.get_template('upload/PostEx.html') return tpl.render(token=uptoken) class PostExDone(WebSiteBasePage.AutoPage): def POST(self): imgdata=json.loads(web.data()) with dbconfig.Session() as session: newpostex=datamodel.post.PostExData() newpostex.postid=imgdata['postid'] fileurl=dbconfig.qiniuDownLoadLinkHead+imgdata['hash'] filetype=int(imgdata['filetype']) if filetype==1: newpostex.picture=fileurl newpostex.width=imgdata['width'] newpostex.height=imgdata['height'] elif filetype==2: newpostex.voice=fileurl newpostex.length=imgdata['length'] elif filetype==3: newpostex.video=fileurl newpostex.length=imgdata['length'] newpostex=session.merge(newpostex) session.query(datamodel.post.Post).filter(datamodel.post.Post.postid==imgdata['postid']).\ update({datamodel.post.Post.excount:datamodel.post.Post.excount+1}) session.commit() return json.dumps({"errno":0,"error":"Success","result":{"url":fileurl,'did':newpostex.did}},cls=AutoFitJson)
UTF-8
Python
false
false
2,014
4,561,255,312,885
2693fd1a60a2b282010218a2883320cbed9ce794
8123f4341fafd71184586b534ba606b9dbd4cf5c
/bin/formatdb.py
d2546e0eaed9200a5bece607a027dd4353ca93f8
[ "GPL-3.0-only" ]
non_permissive
caseeker/web
https://github.com/caseeker/web
3614b32b9032f699b670d0daec42a9e0cbab0687
23f9801581afc2ccde70e33c13332f1d56ea3c8b
refs/heads/master
2021-01-21T01:26:07.271063
2013-02-02T01:20:03
2013-02-02T01:20:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # One document per line import json with open('../projects.json') as f: data = json.loads(f.read()) for row in data: print json.dumps(row)
UTF-8
Python
false
false
2,013
8,839,042,695,484
2e216b5f5989535d82ddcc926188fba1dc7682a5
09e4265dbff1d54ece1333cdb97be9d8badfbe74
/parse_lista.py
4b147320b9aff44b2efa62d7bae3cf0d74cbcad1
[]
no_license
teopost/plowmail
https://github.com/teopost/plowmail
4d30417a94251bac464a30d6188cab009e9b2172
0018c383719eeee6979fd7d054ea9fdcaa018b5d
refs/heads/master
2020-01-21T15:09:20.111057
2014-09-19T19:19:59
2014-09-19T19:19:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import os import sys import shutil import string import email import tempfile import smtplib #import datetime import time import subprocess from os.path import basename from datetime import datetime AppPath=os.path.realpath(os.path.dirname(sys.argv[0])) def runCmd(cmd, timeout=None): ''' Will execute a command, read the output and return it back. @param cmd: command to execute @param timeout: process timeout in seconds @return: a tuple of three: first stdout, then stderr, then exit code @raise OSError: on missing command or if a timeout was reached ''' ph_out = None # process output ph_err = None # stderr ph_ret = None # return code p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # if timeout is not set wait for process to complete if not timeout: ph_ret = p.wait() else: fin_time = time.time() + timeout while p.poll() == None and fin_time > time.time(): time.sleep(1) # if timeout reached, raise an exception if fin_time < time.time(): # starting 2.6 subprocess has a kill() method which is preferable # p.kill() os.kill(p.pid, signal.SIGKILL) raise OSError("Process timeout has been reached") ph_ret = p.returncode ph_out, ph_err = p.communicate() return (ph_out, ph_err, ph_ret) if __name__ == "__main__": # rw = open(AppPath + '/output.txt', 'w') # rw.write('') # rw.close comando='find . -print | grep ''.sh'' > ./output.txt' ph_out, ph_err, ph_ret = runCmd(comando) rr = open(AppPath + '/output.txt','r') rw = open(AppPath + '/output2.txt', 'w') for line in rr.readlines(): nomefile=os.path.basename(line) nomedir=os.path.dirname(line) out="%s,%s" % (nomedir, nomefile) rw.write(out) rr.close() rw.close()
UTF-8
Python
false
false
2,014
4,964,982,227,318
9489895edb01e93567111da937a8bb63e7d83cc2
5a43dcbd60eee1db35e84e35a58650a90cf986d5
/writers_choice/security.py
1bb0e67a5fb760094907b115bf8a0769c73d3470
[]
no_license
antoneliasson/Writers_Choice
https://github.com/antoneliasson/Writers_Choice
e69261e389cb3fe7c97ba7ac7241a1b3fda51c1f
6d915056f0ce9186a79117415fe13b1896830150
refs/heads/master
2021-01-18T14:31:30.724318
2014-01-16T16:33:44
2014-01-16T16:33:44
29,813,711
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def groupfinder(userid, request): admin_email = request.registry.settings['admin_email'] return ['group:editors'] if userid == admin_email else []
UTF-8
Python
false
false
2,014
8,598,524,527,749
476ba0c1cd32e3473638c0ce13b6c6fc33af963e
1db4f25f6cd4003615a2d97a37c2110f8f27555a
/mysql/einfach/TestUserRepository.py
6ce4528aafe67ffc8cd99bef973215931027477e
[]
no_license
ww-lessons/datenhistorisierung
https://github.com/ww-lessons/datenhistorisierung
5baed6108c8f181a9004e29339bb0a270119fffa
e3d4798b096cfe57ece2352a08ec15806634ec9a
refs/heads/master
2020-04-05T23:44:24.056829
2014-12-04T16:35:42
2014-12-04T16:35:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# coding=utf-8 from UserRepository import UserRepository from datetime import datetime import time import unittest USERNAME = 'Mustermann.Max' class SimpleHistoryMySQLTestCase(unittest.TestCase): def test_create_user(self): repo = UserRepository() user = repo.create_user(USERNAME) self.assertEqual(user.username, USERNAME) def test_list_users(self): repo = UserRepository() list = repo.list_users() for item in list: print item self.assertLessEqual(1, len(list)) def test_update_user_empty(self): time.sleep(1) repo = UserRepository() user = repo.get_user_by_name(USERNAME) user.birth_date = None user.description = None user.assigned_rolename = None repo.update_user(user) user2 = repo.get_user_by_name(USERNAME) self.assertEqual(None, user2.birth_date) self.assertEqual(user.assigned_rolename, user2.assigned_rolename) self.assertEqual(user.description, user2.description) def test_update_user(self): repo = UserRepository() user = repo.get_user_by_name(USERNAME) user.birth_date = datetime.now() user.description = "Description" user.assigned_rolename = "Beispielrolle" repo.update_user(user) user2 = repo.get_user_by_name(USERNAME) self.assertNotEqual(None, user2.birth_date) self.assertEqual(user.assigned_rolename, user2.assigned_rolename) self.assertEqual(user.description, user2.description) def test_get_history(self): repo = UserRepository() user = repo.get_user_by_name(USERNAME) history = repo.get_history(USERNAME) print "History for User {0}:{1}:".format(user.username, user.valid_until) for version in history: print " Version {0}:{1}:{2}:{3}".format(version.username, version.valid_until, version.description, version.assigned_rolename) def test_xdelete_user(self): repo = UserRepository() repo.delete_user(USERNAME) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
10,368,051,088,876
9471961c2469e058752bb7d248ee9cc521cc28b6
af40842a7f272d313c21adbf53de812c82faec11
/wader/gtk/models/preferences.py
851816aaf65f1a54ef5dcffd53f47b5663010993
[ "GPL-2.0-only", "CC-BY-SA-2.5" ]
non_permissive
andrewbird/wader-gtk
https://github.com/andrewbird/wader-gtk
bafbb46bf00a1db14638c1fde9924b727cda8ad6
eef127a3dbee807020238296c2144a304493b92d
refs/heads/master
2020-04-19T06:12:27.517385
2011-02-02T17:45:15
2011-02-02T17:45:15
2,649,718
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009 Warp Networks, S.L. # Author: Jaime Soriano # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import dbus import gobject from gtkmvc import Model, ListStoreModel from wader.gtk.models.profile import ProfileModel from wader.gtk.logger import logger from wader.gtk.translate import _ from wader.gtk.profiles import manager from wader.gtk.config import config import wader.common.exceptions as ex PREF_TABS = ["PROFILES"] class ProfilesModel(ListStoreModel): def __init__(self): super(ProfilesModel, self).__init__(gobject.TYPE_BOOLEAN, gobject.TYPE_PYOBJECT) self.active_iter = None self.conf = config def has_active_profile(self): return self.active_iter is not None def get_active_profile(self): if self.active_iter is None: raise RuntimeError(_("No active profile")) return self.get_value(self.active_iter, 1) def add_profile(self, profile, default=False): if not self.has_active_profile(): default = True if not default: # just add it, do not make it default return self.append([default, profile]) # set the profile as default and set active_iter self.conf.set('profile', 'uuid', profile.uuid) self.active_iter = self.append([True, profile]) return self.active_iter def has_profile(self, profile=None, uuid=""): if profile: uuid = profile.uuid _iter = self.get_iter_first() while _iter: _profile = self.get_value(_iter, 1) if _profile.uuid == uuid: return _iter _iter = self.iter_next(_iter) return None def remove_profile(self, profile): _iter = self.has_profile(profile) if not _iter: uuid = profile.uuid raise ex.ProfileNotFoundError("Profile %s not found" % uuid) if profile.uuid == self.get_value(self.active_iter, 1).uuid: self.set(self.active_iter, False, 0) self.active_iter = None self.conf.set('profile', 'uuid', '') self.remove(_iter) profile.delete() def set_default_profile(self, uuid): _iter = self.has_profile(uuid=uuid) assert _iter is not None, "Profile %s does not exist" % uuid if self.active_iter and self.iter_is_valid(self.active_iter): self.set(self.active_iter, 0, False) self.set(_iter, 0, True) self.active_iter = _iter self.conf.set('profile', 'uuid', self.get_value(_iter, 1).uuid) class PreferencesModel(Model): current_tab = PREF_TABS[0] default_profile = None warn_limit = False transfer_limit = -1 __observables__ = ('current_tab', 'default_profile', 'warn_limit', 'transfer_limit') def __init__(self, parent, device_callable): super(PreferencesModel, self).__init__() self.bus = dbus.SystemBus() self.manager = manager self.conf = config self.parent = parent self.device_callable = device_callable self.profiles_model = ProfilesModel() def get_profiles_model(self, device_callable): uuid = self.conf.get('profile', 'uuid') for _uuid, profile in self.get_profiles(device_callable).iteritems(): if not self.profiles_model.has_profile(uuid=_uuid): default = True if uuid and uuid == _uuid else False self.profiles_model.add_profile(profile, default) return self.profiles_model def get_profiles(self, device_callable): ret = {} for profile in self.manager.get_profiles(): settings = profile.get_settings() if 'ppp' in settings: uuid = settings['connection']['uuid'] ret[uuid] = ProfileModel(self, profile=profile, device_callable=device_callable) return ret def load(self): self.warn_limit = self.conf.get('statistics', 'warn_limit', True) self.transfer_limit = self.conf.get('statistics', 'transfer_limit', 50.0) def save(self): self.conf.set('statistics', 'warn_limit', self.warn_limit) self.conf.set('statistics', 'transfer_limit', self.transfer_limit) def reset_statistics(self): logger.info('Resetting total bytes') self.parent.total_bytes = 0 self.conf.set('statistics', 'total_bytes', 0) def profile_added(self, profile): self.profiles_model.add_profile(profile)
UTF-8
Python
false
false
2,011
6,330,781,827,599
f74a7eaa72e7336508595f6964dc8ef311d9e043
b72670077d6d7d63e95c81a0cc930f2c208afb54
/scripts/modules/convert.py
b08674d95b1b94205a76b15b9b0a22da4dafc28a
[]
no_license
jamesavery/qscf-calculations
https://github.com/jamesavery/qscf-calculations
358f8cc008eb252f70db65ea463965ae31375b0f
66f21d69b156e0b688b3dfec7c1d554477d7d5cc
refs/heads/master
2021-01-01T05:34:36.063804
2011-03-07T12:21:01
2011-03-07T12:21:01
451,648
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from math import log, fabs, floor; def mathematica_repr(x,collapse=False): if type(x) == list or type(x) == tuple: return mathematica_list(x,collapse); elif type(x) == str: return '"%s"' % x.encode("string_escape").replace('"',r'\"'); elif type(x) == float: if(x==int(x)): return repr(x); elif(x==float('nan')): return "NaN"; else: e = floor(log(fabs(x))/log(10)); if e <= -5 or e > 6: m = x/(10**e); return "%f*^%d" % (m,e); else: return "%f" % x; elif type(x) == dict: return mathematica_list([(k,x[k]) for k in x.keys()]); else: return repr(x); def mathematica_list(L,collapse=False): if(collapse and len(L) == 1): return mathematica_repr(L[0],collapse); else: return "{"+(",".join([mathematica_repr(x,collapse) for x in L]))+"}";
UTF-8
Python
false
false
2,011
15,212,774,203,341
6b22f4043736e0ce3938cb0c7bb6267ca0f0af57
b9817411ea8bd7996cde2009bdd4988d568f1673
/purchase_supplier/purchase_supplier.py
d020039636a4462a0aabe3515130043dac307bab
[]
no_license
chraim/openerp-addons-6.0
https://github.com/chraim/openerp-addons-6.0
7520694c6ec901d44f0040f9e758c6e0cbff1ff6
455564667f148f85f0750f50ebbf7a24a098fd2c
refs/heads/master
2020-12-30T18:31:07.472508
2013-02-22T11:54:54
2013-02-22T11:54:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
############################################################################## # # Copyright (c) 2010 Javier Duran <[email protected]> All Rights Reserved. # Copyright (c) 2011 Acysos S.L. (http://acysos.com) All Rights Reserved. # Updated to OpenERP 6.0 # Ignacio Ibeas <[email protected] # # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from osv import fields from osv import osv class product_product(osv.osv): _name = 'product.product' _inherit = 'product.product' def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=80): ids=[] if not args: args=[] if not context: context={} if context and context.has_key('partner_id') and context['partner_id']: partner = self.pool.get('res.partner').browse(cr,user,context['partner_id']) if partner.supplier: cr.execute('SELECT p.id ' \ 'FROM product_product AS p ' \ 'INNER JOIN product_template AS t ' \ 'ON p.product_tmpl_id=t.id ' \ 'INNER JOIN product_supplierinfo AS ps ' \ 'ON ps.product_id=p.id ' \ 'WHERE ps.name = '+str(context['partner_id'])+' ' \ 'AND p.default_code = \''+str(name)+'\' ' \ 'AND t.purchase_ok = True ' \ 'ORDER BY p.id') res = cr.fetchall() ids = map(lambda x:x[0], res) if not len(ids): cr.execute('SELECT p.id ' \ 'FROM product_product AS p ' \ 'INNER JOIN product_template AS t ' \ 'ON p.product_tmpl_id=t.id ' \ 'INNER JOIN product_supplierinfo AS ps ' \ 'ON ps.product_id=p.id ' \ 'WHERE ps.name = '+str(context['partner_id'])+' ' \ 'AND p.ean13 = \''+str(name)+'\' ' \ 'AND t.purchase_ok = True ' \ 'ORDER BY p.id') res = cr.fetchall() ids = map(lambda x:x[0], res) if not len(ids): if operator in ('like', 'ilike'): name='%'+name+'%' cr.execute('SELECT p.id ' \ 'FROM product_product AS p ' \ 'INNER JOIN product_template AS t ' \ 'ON p.product_tmpl_id=t.id ' \ 'INNER JOIN product_supplierinfo AS ps ' \ 'ON ps.product_id=p.id ' \ 'WHERE ps.name = '+str(context['partner_id'])+' ' \ 'AND p.default_code '+operator+' \''+str(name)+'\' ' \ 'AND t.purchase_ok = True ' \ 'ORDER BY p.id') res = cr.fetchall() ids = map(lambda x:x[0], res) cr.execute('SELECT p.id ' \ 'FROM product_product AS p ' \ 'INNER JOIN product_template AS t ' \ 'ON p.product_tmpl_id=t.id ' \ 'INNER JOIN product_supplierinfo AS ps ' \ 'ON ps.product_id=p.id ' \ 'WHERE ps.name = '+str(context['partner_id'])+' ' \ 'AND t.name '+operator+' \''+str(name)+'\' ' \ 'AND t.purchase_ok = True ' \ 'ORDER BY p.id') res = cr.fetchall() ids += map(lambda x:x[0], res) else: if not len(ids): ids = self.search(cr, user, [('default_code','=',name)]+ args, limit=limit, context=context) if not len(ids): ids = self.search(cr, user, [('ean13','=',name)]+ args, limit=limit, context=context) if not len(ids): ids = self.search(cr, user, [('default_code',operator,name)]+ args, limit=limit, context=context) ids += self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context) else: if not len(ids): ids = self.search(cr, user, [('default_code','=',name)]+ args, limit=limit, context=context) if not len(ids): ids = self.search(cr, user, [('ean13','=',name)]+ args, limit=limit, context=context) if not len(ids): ids = self.search(cr, user, [('default_code',operator,name)]+ args, limit=limit, context=context) ids += self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context) result = self.name_get(cr, user, ids, context) return result product_product()
UTF-8
Python
false
false
2,013
15,092,515,124,904
9ab313620b4d9dc4880821a8f431b7c460650e5e
5c5cf5ef7610c9322a5a176337b6c7c0d5299c49
/player_tests.py
c902331b5f3bce625ae2b54fa11c7c2061d14258
[ "MIT" ]
permissive
tborisova/dont-get-annoyed-buddy
https://github.com/tborisova/dont-get-annoyed-buddy
1644f88e8e4be1145e8eb74235097e249e3a60a3
3e8626b6ba13d9917e1669acc1f5b846ca638d08
refs/heads/master
2020-05-30T01:00:12.810708
2014-09-03T10:34:06
2014-09-03T10:34:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from player import Player, RedPlayer, BluePlayer, GreenPlayer, YellowPlayer class PlayerTest(unittest.TestCase): def testIsPlayerMove(self): player = RedPlayer() player.move_pawn(1, 2) self.assertEqual(player._pawns[0], 31) player.move_pawn(1, 6) self.assertEqual(player._pawns[0], 37) player.move_pawn(1, 4) self.assertEqual(player._pawns[0], 1) def testPawnIsNotOnField(self): player = RedPlayer() self.assertTrue(player.pawn_is_not_in_field(1)) def testPawnIsInHouse(self): player = RedPlayer() player._pawns[0] = 56 self.assertTrue(player.pawn_is_in_house(1)) def xtestThrowDiceIsRandomNumber(self): #check how to mock pass def testAllPawnsAreInHouse(self): player = RedPlayer() player._pawns[0] = player._pawns[1] = player._pawns[2] = 55 player._pawns[3] = 56 self.assertFalse(player.all_pawns_are_in_house()) player._pawns[0] = player._pawns[1] = player._pawns[2] = 56 self.assertTrue(player.all_pawns_are_in_house()) def testCanThrowAgain(self): player = RedPlayer() player._dice = 6 self.assertTrue(player.can_throw_again()) player._dice = 3 self.assertFalse(player.can_throw_again()) def testPlayerKnowsHisAvaiablePawns(self): player = RedPlayer() self.assertEqual(player.available_pawns(3), []) self.assertEqual(player.available_pawns(6), [1]) player._pawns[0] = 1 self.assertEqual(player.available_pawns(6), [1, 2]) player._pawns[1] = 0 self.assertEqual(player.available_pawns(6), [1, 2, 3]) player._pawns[2] = 3 player._pawns[1] = -1 self.assertEqual(player.available_pawns(2), [1, 3]) def testPawnIsRemovedFromPosition(self): player = RedPlayer() player._pawns = [1, 34, 4, 5] player.remove_pawn_from_position(4) self.assertEqual(player._pawns[0], 1) self.assertEqual(player._pawns[1], 34) self.assertEqual(player._pawns[2], -1) self.assertEqual(player._pawns[3], 5) def testBluePlayerSetup(self): player = BluePlayer() self.assertEqual(player.color, 'B') self.assertEqual(player.path, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 56]) def testRedPlayerSetup(self): player = RedPlayer() self.assertEqual(player.color, 'R') self.assertEqual(player.path, [30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 52, 53, 54, 55, 56]) def testYellowPlayer(self): player = YellowPlayer() self.assertEqual(player.color, 'Y') self.assertEqual(player.path, [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 48, 49, 50, 51, 56]) def testGreenPlayer(self): player = GreenPlayer() self.assertEqual(player.color, 'G') self.assertEqual(player.path, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, 45, 46, 47, 56]) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
16,303,695,881,997
efdb7e1746f1ffb46ed3be17e0e83c020c6ffaaa
4a662dfae34afccbea2647a67c580623f3876fd2
/test.py
5fffc0946a21fd223437b71a8e067abd96ef12d5
[]
no_license
alexwforsythe/flashcard_app
https://github.com/alexwforsythe/flashcard_app
3c35ca49e5d280c718c529be02dbc7b49321098b
b2bc936d027ed9922a28403780ed04365f6900ce
refs/heads/master
2015-08-15T03:38:11.622087
2014-11-22T02:02:46
2014-11-22T02:02:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import unittest from app import app class TestApp(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_home_page(self): rv = self.app.get('/') self.assertTrue(rv.data) self.assertEqual(rv.status_code, 200) def test_hello_page(self): rv = self.app.get('/hello/') self.assertTrue(rv.data) self.assertEqual(rv.status_code, 200) def test_default_redirecting(self): rv = self.app.get('hello') self.assertEqual(rv.status_code, 301) def test_static_text_file_request(self): rv = self.app.get('/robots.txt') self.assertTrue(rv.data) self.assertEqual(rv.status_code, 200) rv.close() if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
2,014
13,116,830,123,039
9c9049035bffea8418c658dd5e9176543fc26388
647de2fb8e454c26fc72d529651bf225be29b289
/wsgi.py
7ddcae75da93c388ea8ef0c133d24a4766af58d6
[]
no_license
fajoy/py-gae
https://github.com/fajoy/py-gae
5733238795f8dd63c519d61c41cf794021dc1e17
1bc679c7df29f1493a924843756741056c1a4d88
refs/heads/master
2016-09-05T18:08:17.896254
2014-05-03T16:05:19
2014-05-03T16:05:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os,sys sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) from service import make_app application = make_app()
UTF-8
Python
false
false
2,014
4,063,039,091,339
4756f817b5cd826fb54af4a2477ecb8a1684aec7
dbe0f5c5e063f1f322b54a636dc827524bb8bd40
/pypkg/core.py
9c8f5bc8e8963157b658b31cbce86dffb6d7b34a
[ "MIT" ]
permissive
mrstu/pypkg
https://github.com/mrstu/pypkg
a29a153e909bb8f414fa3301169f31d5a00e9c0f
c094dd2459a19fdb348805601987b9d9f4ff7214
refs/heads/master
2021-01-17T07:06:50.020032
2014-08-06T07:56:08
2014-08-06T08:02:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Core functionality of the package. """ from __future__ import print_function from .utils import fancy def echo(message): """ :param message: the message to echo :returns: the given message :raises: """ return message def fancy_print(message): """ Prints the message in a fancy way. Args: message (obj): the message object to echo Returns: None Raises: """ print(fancy(message))
UTF-8
Python
false
false
2,014
6,674,379,203,349
eea1a59adc043f31ee8f712e64a8081174ef0548
2354d81dd66fc6c9b06f274269064c3429f1869c
/main.py
49a77d67c8ef0c9623e669836664e0a03c1ae8c1
[]
no_license
ryanfisher/taskit
https://github.com/ryanfisher/taskit
7c06660403a1aa22619f99e5bed6b3c1f681da1d
e5ad69950883111cbc3fc5e92c24b944a4967ef5
refs/heads/master
2021-01-01T06:55:13.139102
2011-09-13T16:23:07
2011-09-13T16:23:07
2,390,244
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import time from datetime import date, datetime from google.appengine.api import users from google.appengine.ext.webapp import template from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext import db TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), 'templates/') TASK_LIMIT = 10 MAIN_URL = '/taskit' class Task(db.Model): PRIORITY_CHOICES = ["high","medium","low"] name = db.StringProperty() date = db.DateTimeProperty(auto_now_add=True) complete_by = db.DateProperty() completed = db.BooleanProperty(default=False) completed_date = db.DateTimeProperty() notes = db.StringProperty() user = db.UserProperty(auto_current_user_add=True) priority = db.StringProperty(choices = PRIORITY_CHOICES) private = db.BooleanProperty(default=False) class Preferences(db.Model): user = db.UserProperty(required=True) expiration = db.DateProperty() date_joined = db.DateProperty(auto_now_add=True) #----------------Utility Functions------------------------------- def taskQuery(order_by = [], filters = [], limit = 10): ''' Queries the Task model and returns a rendered task-list. Orders list by Task properties specified in order_by list. Filters list by Task properties specified as tuples in filters list. Each tuple will be a property, value pair (property, value). ''' user = users.get_current_user() query = Task.all() query.filter('user =', user) for order in order_by: query.order(order) for filter in filters: query.filter(filter[0], filter[1]) tasks = query.fetch(limit) for task in tasks: task.id = task.key() template_path = TEMPLATES_PATH + 'task-list.html' output = template.render(template_path, {'tasks': tasks}) return output def putTask(): pass #---------------------------------------------------------------- class MainHandler(webapp.RequestHandler): def get(self): user = users.get_current_user() template_values = {} if user: # Gets task information for valid user template_values['nickname'] = user.nickname() template_values['logout_url'] = users.create_logout_url(MAIN_URL) query = Task.all() query.filter('user =', user) query.order('date') tasks = query.fetch(10) for task in tasks: task.id = task.key() template_values['tasks'] = tasks else: template_values['login_url'] = users.create_login_url(MAIN_URL) template_path = TEMPLATES_PATH + 'index.html' template_values.update({}) output = template.render(template_path, template_values) self.response.out.write(output) def post(self): ''' Only called when ajax calls not working. ''' u = users.get_current_user() query = Task.all() query.filter("user =", u) tasks = query.fetch(TASK_LIMIT + 1) if u and len(tasks) < TASK_LIMIT: n = self.request.get('notes') d = self.request.get('complete-by') if d == "": d = date.today() else: d = datetime.strptime(d,"%m/%d/%Y").date() if n == "": n = None t = Task( name = self.request.get('task'), notes = n, complete_by = d, ) t.put() self.redirect(MAIN_URL) class TaskHandler(webapp.RequestHandler): ''' Handles completing and deleting tasks when ajax calls are not working. ''' def get(self, command, id): user = users.get_current_user() if command == "complete": task = db.get(id) task.completed = True if task.user == user: task.put() self.redirect(MAIN_URL) elif command == "delete": task = db.get(id) if task.user == user: task.delete() self.redirect(MAIN_URL) class AjaxHandler(webapp.RequestHandler): def post(self, command): user = users.get_current_user() if not user: self.redirect(MAIN_URL) return False query = Task.all() query.filter('user =', user) if command == 'delete': task = db.get(self.request.get('id')) if task.user == user: task.delete() elif command == 'complete': task = db.get(self.request.get('id')) task.completed = True task.complete_date = date.today() if task.user == user: task.put() elif command == 'submit-task': tasks = query.fetch(TASK_LIMIT + 1) if len(tasks) < TASK_LIMIT: n = self.request.get('notes') d = self.request.get('complete-by') if d == "": d = date.today() else: d = datetime.strptime(d,"%m/%d/%Y").date() if n == "": n = None t = Task( name = self.request.get('task'), notes = n, complete_by = d, ) t.put() key = t.key() task = db.get(key) task.id = key template_path = TEMPLATES_PATH + 'single-task.html' output = template.render(template_path, {'task': task}) self.response.out.write(output) else: # This dictionary is all that needs to be extended to add # more task list sorting or filtering functionality. command_params = { 'show-completed': {'filters': [('completed',True)]}, 'show-not-completed': {'filters': [('completed',False)]}, 'sort-completeby-date': {'order_by': ['complete_by']}, 'sort-date': {'order_by': ['date']}, 'sort-name': {'order_by': ['name']}, } try: params = command_params[command] except KeyError: self.error(303) if 'filters' in params: f = params['filters'] else: f = [] if 'order_by' in params: o = params['order_by'] else: o = [] self.response.out.write(taskQuery(filters = f, order_by = o)) class AjaxMethods(object): pass def main(): application = webapp.WSGIApplication([ ('/taskit', MainHandler), ('/taskit/ajax/(?P<command>.*)', AjaxHandler), ('/taskit/(?P<command>.*)/(?P<id>.*)', TaskHandler), ], debug=True ) util.run_wsgi_app(application) if __name__ == '__main__': main()
UTF-8
Python
false
false
2,011
2,370,821,957,070
72d11d08df74e510f749161501459e527750dbee
e2b3101bc68823f6efe538dfe8a521997b7ee248
/extra/generate_iax
dc53ba5200d5b7a65e2424e382267d5d87ec3509
[ "GPL-3.0-only" ]
non_permissive
macntouch/xivo-gallifrey
https://github.com/macntouch/xivo-gallifrey
71b53cc7e1749f74a2c859a8f9d5a38027f18524
c0883995ab86500e907ad6c958fd7e992f957811
refs/heads/master
2021-01-21T00:05:16.141877
2012-02-10T13:03:10
2012-02-10T13:03:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python __version__ = "$Revision: 5525 $ $Date: 2009-03-03 12:30:31 +0100 (Tue, 03 Mar 2009) $" __license__ = """ Copyright (C) 2006-2010 Proformatique <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ """ This script generates the IAX configuration from the XiVO database (general and peers/users configuration). It can be used in the iax.conf file with the #exec statement. """ import sys from xivo import OrderedConf from xivo import xivo_helpers cursor = xivo_helpers.db_connect().cursor() cursor.query("SELECT ${columns} FROM staticiax " "WHERE commented = 0 ", ('var_name', 'var_val')) res = cursor.fetchall() print "[general]" for r in res: if r['var_name'] not in ('allow','disallow'): print r['var_name'] + " = " + r['var_val'] if r['var_name'] == 'allow' and r['var_val'] != None: print "disallow = all" for c in r['var_val'].split(','): print "allow = " + str(c) print "\n\n" cursor.query("SELECT ${columns} FROM useriax WHERE commented = 0 ", ('name','type','username','secret','dbsecret','context','language','accountcode','amaflags','mailbox','callerid','fullname', 'cid_number','trunk','auth','encryption','maxauthreq','inkeys','outkey','adsi','transfer','codecpriority','jitterbuffer', 'sendani','qualify','qualifysmoothing','qualifyfreqok','qualifyfreqnotok','timezone','disallow','allow','mohinterpret', 'mohsuggest','deny','permit','defaultip','sourceaddress','setvar','host','port','mask','regexten','peercontext','ipaddr', 'regseconds','protocol', 'requirecalltoken')) res = cursor.fetchall() for k in res: print "\n" print "[%s]" % k['name'] for k, v in k.iteritems(): if v not in ('',None) and k not in ('regseconds','name','ipaddr','allow','disallow'): print k + " = " + str(v) if k == 'allow' and v != None: print "disallow = all" for c in v.split(','): print "allow = " + str(c)
UTF-8
Python
false
false
2,012
3,513,283,255,729
8b161c3778b5ad34a0b6deae06d593b1f7b1e7cb
177ab92e498e3fa0b1404bf783c0cbb437c0ac55
/tests/utils.py
059595287dcba8895776c976ac1976ab5d586a99
[ "LGPL-2.1-only" ]
non_permissive
GNOME/testinggtk
https://github.com/GNOME/testinggtk
af60fad3a81e31783989ed5df9919940285168cb
4d32d592d4d2322fc140ab39a64391806cb3497b
refs/heads/master
2016-08-04T19:17:06.550366
2009-07-10T14:03:27
2009-07-10T14:03:27
4,614,853
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Useful utils usable under unit testing. ''' import gtk from gtk import gdk import StringIO import sys import time class WarningChecker: def __init__(self): self.stderr = sys.stderr self.file = StringIO.StringIO() def get_warning_triplets(self): lines = self.file.getvalue().split('\n') self.file = StringIO.StringIO() return zip(lines, lines[1:], lines[2:]) def push_stderr(self): sys.stderr = self.file def pop_stderr(self): sys.stderr = self.stderr def pop_stderr_and_fail_warnings(self): sys.stderr = self.stderr for triplet in self.get_warning_triplets(): if 'Warning' in triplet[0]: raise AssertionError, '\n'.join(triplet) def pop_stderr_and_pass_warnings(self): sys.stderr = self.stderr for triplet in self.get_warning_triplets(): if 'Warning' in triplet[0]: return raise AssertionError, 'No Warning from test expecting one!' wc = WarningChecker() def pass_on_warnings(func): ''' A decorator that fails the decorated test unless atleast one Warning occured during the test run. .. python:: @utils.pass_on_warnings def test_something(): code that emits gtk warnings... :param func: test function to decorate ''' def wrapper(): wc.push_stderr() func() wc.pop_stderr_and_pass_warnings() wrapper.__module__ = func.__module__ wrapper.__name__ = func.__name__ return wrapper def fail_on_warnings(func): ''' A decorator that fails the decorated test if one or more Warnings occured during the test run. .. python:: @utils.fail_on_warnings def test_something(): code that shouldn't emit gtk warnings :param func: test function to decorate ''' def wrapper(): wc.push_stderr() func() wc.pop_stderr_and_fail_warnings() wrapper.__module__ = func.__module__ wrapper.__name__ = func.__name__ return wrapper def swallow_warnings(func): ''' A decorator that swallows any printouts on stderr. .. python:: @utils.swallow_warnings def test_blaha(): code that makes warnings... :param func: test function to decorate ''' def wrapper(): wc.push_stderr() func() wc.pop_stderr() wrapper.__module__ = func.__module__ wrapper.__name__ = func.__name__ return wrapper def gtk_process_all_pending_events(): ''' Let GTK process all events in its pending queue without blocking. ''' gtk.main_iteration(False) time.sleep(0.05) while gtk.events_pending(): gtk.main_iteration(False) time.sleep(0.05) def gtk_container_find_child(container, path): ''' Returns the widget child in the `container` found when searching for `path`. .. python:: # This example finds the page range entry in a PrintUnixDialog. dialog = gtkunixprint.PrintUnixDialog() path = 'VBox.VBox.Notebook.VBox.HBox.VBox.Alignment.Table.Entry' widget = utils.gtk_container_find_child(dialog, path.split('.')) :param container: a ``gtk.Container`` to search :param path: a list of class names which is the path to the widget. :return: the ``gtk.Widget`` found or ``None`` if there is no widget at the specified path. ''' if not path: return container for child in container.get_children(): if child.__class__.__name__ == path[0]: return gtk_container_find_child(child, path[1:]) return None def gtk_container_print_tree(widget, indent = 0): ''' Debug function that prints a containers widget hierarchy. ''' print ' ' * indent + widget.__class__.__name__ if not isinstance(widget, gtk.Container): return for child in widget.get_children(): gtk_container_print_tree(child, indent + 2) def pixbuf_count_pixels(pixbuf, rgb): ''' Returns the number of times the pixel `rgb` is present in the pixbuf. :param pixbuf: a ``gtk.gdk.Pixbuf`` :param rgb: a color specification string such as "#ff0000" :return: the number of times `rgb` appears in the pixbuf ''' # not handling transparent pixbufs yet if pixbuf.get_has_alpha(): raise ValueError('pixbuf must not have alpha') col = gdk.color_parse(rgb) col.red /= 256 col.green /= 256 col.blue /= 256 red = chr(col.red) green = chr(col.green) blue = chr(col.blue) # Abusing an iterator... count = 0 pixels = iter(pixbuf.get_pixels()) for r, g, b in zip(pixels, pixels, pixels): if r == red and g == green and b == blue: count += 1 return count def widget_get_rendering(widget): ''' Returns a ``gdk.Pixbuf`` which contains a rendering of the `widget` aquired using ``widget.get_snapshot`` :param widget: a realized ``gtk.Widget`` :return: a ``gdk.Pixbuf`` of the rendered widget ''' if not widget.window: raise ValueError('widget must be realized') width, height = widget.window.get_size() clip = gdk.Rectangle(0, 0, width, height) pixmap = widget.get_snapshot(clip) pixbuf = gdk.Pixbuf(gdk.COLORSPACE_RGB, False, 8, width, height) pixbuf.get_from_drawable(pixmap, pixmap.get_colormap(), 0, 0, 0, 0, width, height) return pixbuf
UTF-8
Python
false
false
2,009
4,037,269,261,444
9bbfec67bbca357293ebd93bd807e5ac17c8ba96
291fe11c01c756df1d484f5d22c40eb2fd71753e
/add_tax_to_map.py
a6aafe41fe9e5681f0e8904a0670d1222c5fd746
[]
no_license
bmarchenko/infographics-banks
https://github.com/bmarchenko/infographics-banks
6727eee8a6c1d28bdfde900c02dbbfcd3cde7c61
ec99dce1bccbe4903a78e8ebc47fb257578a40b4
refs/heads/master
2020-04-06T04:36:11.259311
2013-05-22T21:32:38
2013-05-22T21:32:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import csv, json f = open('credits.csv', 'r') reader = csv.reader(f) credits = [property for property in reader] f = open('names_converted.json', 'r') cities_conv = dict((v.encode('utf8'),k) for k, v in json.load(f).items()) credits_conv = dict([(cities_conv[i[0]], dict(zip([2008, 2009, 2010, 2011, 2012], i[1:]))) for i in credits if cities_conv.get(i[0])]) f = open('ua_topo.json', 'r') geo = json.load(f) cr2012 = [] for i in geo['objects']['states']['geometries']: cr = credits_conv.get(i['properties']['oblname']) if cr: i['properties']['credits'] = cr.get(2012) cr2012.append(cr.get(2012)) with open('ua_topo_with_credits.json', 'w') as outfile: json.dump(geo, outfile) print "max credit:" print max(cr2012) print "min credit:" print min(cr2012)
UTF-8
Python
false
false
2,013
12,335,146,094,568
1eeda3d9006a17c01420ba17927ada8f2a094181
721e0d2d81cdf62fe52e212084d6612d656ab718
/lec6/thread_name.py
cbdec3d4a7a05e528c696086b113d7a916c9a8b2
[]
no_license
uralbash/Python-lectures
https://github.com/uralbash/Python-lectures
823fb35c43a4cef21672c83aeb354675119c2efd
df1ab45094f00c84cb72ca9b7cf3db9cf5c00cf2
refs/heads/master
2020-06-05T09:33:28.318713
2011-04-14T16:45:09
2011-04-14T16:45:09
1,369,074
8
5
null
null
null
null
null
null
null
null
null
null
null
null
null
import threading class TestThread(threading.Thread): def run(self): print 'Hello, my name is', self.getName() cazaril = TestThread() cazaril.setName('Cazaril') cazaril.start() ista = TestThread() ista.setName('Ista') ista.start() TestThread().start() TestThread().start()
UTF-8
Python
false
false
2,011
8,306,466,787,617
20b9052f3c6a3fdf1cc5fafbd6413af42540118a
f93aa7a552a77c935cd0e2a570e504570e6f4007
/OReilly/Linkedin/Linkedin_examples.py
52491eaaee7b0b60eb8a9cb1e068b679f8bf7d0d
[]
no_license
PendletonJones/SocialWebMining
https://github.com/PendletonJones/SocialWebMining
645eda053c05817115a409f5bed120ca99701717
0fbf35c0df29cac9f694a4c7b227b0c2f9fa2eb0
refs/heads/master
2016-05-29T16:15:45.796731
2014-10-09T20:29:41
2014-10-09T20:29:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#--------------------------------------- READ ME ---------------------------------------# # 13 Examples # # 1) Using Linkedin OAuth credentials to recieve an access token suitable for development and accessing your own data # 2) Retrieving your linkedin connections and storing them to a disk # 3) Pretty-printing your linkedin connections' data # 4) Displaying job position history for your profile and connection's profile # 5) Using field sector syntax to request additional details for APIs # 6) Simple normalization of company suffixes from address book data # 7) Standardizing common job titles and comptuing their frequencies # 8) Geocoding locations with Microsoft Bing # 9) Geocoding locations of Linkedin connections with Microsoft Bing # 10) Parsing out states from Bing geocoder results using a regular expression # - Part 2: Here's how to power a Cartogram visualization with the data from the 'results' variable # 11) Using NLTK to compute bigrams # 12) Clustering job titles using a greedy heuristic # - Part 2: Incorporating random samplign can improve performance ofthe nested loops in Example 12 # - Part 3: How to export data (contained in the "clustered contacts" variable) to power faceted display as outlined in Figure 3. # - Part 4: How to export data to a power dendogram and node-link visualization as outlined in Figure 4 # - Part 5: Once you've run the code and produced the output for the dendogram and node-link tree visualizations, here's one way to serve it # 13) Clustering your Linkedin Professional Network based upon the locations of your connectison and emmiting KML output for visualization with Google Earth # #--------------------------------------- Example 1 ---------------------------------------# from linkedin import linkedin # pip install python-linkedin # Define CONSUMER_KEY, CONSUMER_SECRET, # USER_TOKEN, and USER_SECRET from the credentials # provided in your LinkedIn application CONSUMER_KEY = '' CONSUMER_SECRET = '' USER_TOKEN = '' USER_SECRET = '' RETURN_URL = '' # Not required for developer authentication # Instantiate the developer authentication class auth = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET, USER_TOKEN, USER_SECRET, RETURN_URL, permissions=linkedin.PERMISSIONS.enums.values()) # Pass it in to the app... app = linkedin.LinkedInApplication(auth) # Use the app... app.get_profile() #--------------------------------------- Example 2 ---------------------------------------# import json connections = app.get_connections() connections_data = 'resources/ch03-linkedin/linkedin_connections.json' f = open(conections_data, 'w') f.write(json.dumps(connections, indent=1)) f.close() # You can reuse the data without using the API later like this... # connections = json.loads(open(connections_data).read()) #PART 2 # Execute this cell if you need to reload data... import json connections = json.loads(open('resources/ch03-linkedin/linkedin_connections.json').read()) #--------------------------------------- Example 3 ---------------------------------------# from prettytable import PrettyTable # pip install prettytable pt = PrettyTable(field_names=['Name', 'Location']) pt.align = 'l' [ pt.add_row((c['firstName'] + ' ' + c['lastName'], c['location']['name'])) for c in connections['values'] if c.has_key('location')] print pt #--------------------------------------- Example 4 ---------------------------------------# import json # See http://developer.linkedin.com/documents/profile-fields#fullprofile # for details on additional field selectors that can be passed in for # retrieving additional profile information. # Display your own positions... my_positions = app.get_profile(selectors=['positions']) print json.dumps(my_positions, indent=1) # Display positions for someone in your network... # Get an id for a connection. We'll just pick the first one. connection_id = connections['values'][0]['id'] connection_positions = app.get_profile(member_id=connection_id, selectors=['positions']) print json.dumps(connection_positions, indent=1) #--------------------------------------- Example 5 ---------------------------------------# # See http://developer.linkedin.com/documents/understanding-field-selectors # for more information on the field selector syntax my_positions = app.get_profile(selectors=['positions:(company:(name,industry,id))']) print json.dumps(my_positions, indent=1) #--------------------------------------- Example 6 ---------------------------------------# import os import csv from collections import Counter from operator import itemgetter from prettytable import PrettyTable # XXX: Place your "Outlook CSV" formatted file of connections from # http://www.linkedin.com/people/export-settings at the following # location: resources/ch03-linkedin/my_connections.csv CSV_FILE = os.path.join("resources", "ch03-linkedin", 'my_connections.csv') # Define a set of transforms that converts the first item # to the second item. Here, we're simply handling some # commonly known abbreviations, stripping off common suffixes, # etc. transforms = [(', Inc.', ''), (', Inc', ''), (', LLC', ''), (', LLP', ''), (' LLC', ''), (' Inc.', ''), (' Inc', '')] csvReader = csv.DictReader(open(CSV_FILE), delimiter=',', quotechar='"') contacts = [row for row in csvReader] companies = [c['Company'].strip() for c in contacts if c['Company'].strip() != ''] for i, _ in enumerate(companies): for transform in transforms: companies[i] = companies[i].replace(*transform) pt = PrettyTable(field_names=['Company', 'Freq']) pt.align = 'l' c = Counter(companies) [pt.add_row([company, freq]) for (company, freq) in sorted(c.items(), key=itemgetter(1), reverse=True) if freq > 1] print pt #--------------------------------------- Example 7 ---------------------------------------# import os import csv from operator import itemgetter from collections import Counter from prettytable import PrettyTable # XXX: Place your "Outlook CSV" formatted file of connections from # http://www.linkedin.com/people/export-settings at the following # location: resources/ch03-linkedin/my_connections.csv CSV_FILE = os.path.join("resources", "ch03-linkedin", 'my_connections.csv') transforms = [ ('Sr.', 'Senior'), ('Sr', 'Senior'), ('Jr.', 'Junior'), ('Jr', 'Junior'), ('CEO', 'Chief Executive Officer'), ('COO', 'Chief Operating Officer'), ('CTO', 'Chief Technology Officer'), ('CFO', 'Chief Finance Officer'), ('VP', 'Vice President'), ] csvReader = csv.DictReader(open(CSV_FILE), delimiter=',', quotechar='"') contacts = [row for row in csvReader] # Read in a list of titles and split apart # any combined titles like "President/CEO." # Other variations could be handled as well, such # as "President & CEO", "President and CEO", etc. titles = [] for contact in contacts: titles.extend([t.strip() for t in contact['Job Title'].split('/') if contact['Job Title'].strip() != '']) # Replace common/known abbreviations for i, _ in enumerate(titles): for transform in transforms: titles[i] = titles[i].replace(*transform) # Print out a table of titles sorted by frequency pt = PrettyTable(field_names=['Title', 'Freq']) pt.align = 'l' c = Counter(titles) [pt.add_row([title, freq]) for (title, freq) in sorted(c.items(), key=itemgetter(1), reverse=True) if freq > 1] print pt # Print out a table of tokens sorted by frequency tokens = [] for title in titles: tokens.extend([t.strip(',') for t in title.split()]) pt = PrettyTable(field_names=['Token', 'Freq']) pt.align = 'l' c = Counter(tokens) [pt.add_row([token, freq]) for (token, freq) in sorted(c.items(), key=itemgetter(1), reverse=True) if freq > 1 and len(token) > 2] print pt #--------------------------------------- Example 8 ---------------------------------------# from geopy import geocoders GEO_APP_KEY = '' # XXX: Get this from https://www.bingmapsportal.com g = geocoders.Bing(GEO_APP_KEY) print g.geocode("Nashville", exactly_one=False) #--------------------------------------- Example 9 ---------------------------------------# from geopy import geocoders GEO_APP_KEY = '' # XXX: Get this from https://www.bingmapsportal.com g = geocoders.Bing(GEO_APP_KEY) transforms = [('Greater ', ''), (' Area', '')] results = {} for c in connections['values']: if not c.has_key('location'): continue transformed_location = c['location']['name'] for transform in transforms: transformed_location = transformed_location.replace(*transform) geo = g.geocode(transformed_location, exactly_one=False) if geo == []: continue results.update({ c['location']['name'] : geo }) print json.dumps(results, indent=1) #--------------------------------------- Example 10 ---------------------------------------# import re # Most results contain a response that can be parsed by # picking out the first two consecutive upper case letters # as a clue for the state pattern = re.compile('.*([A-Z]{2}).*') def parseStateFromBingResult(r): result = pattern.search(r[0][0]) if result == None: print "Unresolved match:", r return "???" elif len(result.groups()) == 1: print result.groups() return result.groups()[0] else: print "Unresolved match:", result.groups() return "???" transforms = [('Greater ', ''), (' Area', '')] results = {} for c in connections['values']: if not c.has_key('location'): continue if not c['location']['country']['code'] == 'us': continue transformed_location = c['location']['name'] for transform in transforms: transformed_location = transformed_location.replace(*transform) geo = g.geocode(transformed_location, exactly_one=False) if geo == []: continue parsed_state = parseStateFromBingResult(geo) if parsed_state != "???": results.update({c['location']['name'] : parsed_state}) print json.dumps(results, indent=1) #PART TWO: how to power a Cartogram visualization with the data from the 'results' variable import os import json from IPython.display import IFrame from IPython.core.display import display # Load in a data structure mapping state names to codes. # e.g. West Virginia is WV codes = json.loads(open('resources/ch03-linkedin/viz/states-codes.json').read()) from collections import Counter c = Counter([r[1] for r in results.items()]) states_freqs = { codes[k] : v for (k,v) in c.items() } # Lace in all of the other states and provide a minimum value for each of them states_freqs.update({v : 0.5 for v in codes.values() if v not in states_freqs.keys() }) # Write output to file f = open('resources/ch03-linkedin/viz/states-freqs.json', 'w') f.write(json.dumps(states_freqs, indent=1)) f.close() # IPython Notebook can serve files and display them into # inline frames. Prepend the path with the 'files' prefix display(IFrame('files/resources/ch03-linkedin/viz/cartogram.html', '100%', '600px')) #--------------------------------------- Example 11 ---------------------------------------# ceo_bigrams = nltk.bigrams("Chief Executive Officer".split(), pad_right=True, pad_left=True) cto_bigrams = nltk.bigrams("Chief Technology Officer".split(), pad_right=True, pad_left=True) print ceo_bigrams print cto_bigrams print len(set(ceo_bigrams).intersection(set(cto_bigrams))) #--------------------------------------- Example 12 ---------------------------------------# import os import csv from nltk.metrics.distance import jaccard_distance # XXX: Place your "Outlook CSV" formatted file of connections from # http://www.linkedin.com/people/export-settings at the following # location: resources/ch03-linkedin/my_connections.csv CSV_FILE = os.path.join("resources", "ch03-linkedin", 'my_connections.csv') # Tweak this distance threshold and try different distance calculations # during experimentation DISTANCE_THRESHOLD = 0.5 DISTANCE = jaccard_distance def cluster_contacts_by_title(csv_file): transforms = [ ('Sr.', 'Senior'), ('Sr', 'Senior'), ('Jr.', 'Junior'), ('Jr', 'Junior'), ('CEO', 'Chief Executive Officer'), ('COO', 'Chief Operating Officer'), ('CTO', 'Chief Technology Officer'), ('CFO', 'Chief Finance Officer'), ('VP', 'Vice President'), ] separators = ['/', 'and', '&'] csvReader = csv.DictReader(open(csv_file), delimiter=',', quotechar='"') contacts = [row for row in csvReader] # Normalize and/or replace known abbreviations # and build up a list of common titles. all_titles = [] for i, _ in enumerate(contacts): if contacts[i]['Job Title'] == '': contacts[i]['Job Titles'] = [''] continue titles = [contacts[i]['Job Title']] for title in titles: for separator in separators: if title.find(separator) >= 0: titles.remove(title) titles.extend([title.strip() for title in title.split(separator) if title.strip() != '']) for transform in transforms: titles = [title.replace(*transform) for title in titles] contacts[i]['Job Titles'] = titles all_titles.extend(titles) all_titles = list(set(all_titles)) clusters = {} for title1 in all_titles: clusters[title1] = [] for title2 in all_titles: if title2 in clusters[title1] or clusters.has_key(title2) and title1 \ in clusters[title2]: continue distance = DISTANCE(set(title1.split()), set(title2.split())) if distance < DISTANCE_THRESHOLD: clusters[title1].append(title2) # Flatten out clusters clusters = [clusters[title] for title in clusters if len(clusters[title]) > 1] # Round up contacts who are in these clusters and group them together clustered_contacts = {} for cluster in clusters: clustered_contacts[tuple(cluster)] = [] for contact in contacts: for title in contact['Job Titles']: if title in cluster: clustered_contacts[tuple(cluster)].append('%s %s' % (contact['First Name'], contact['Last Name'])) return clustered_contacts clustered_contacts = cluster_contacts_by_title(CSV_FILE) print clustered_contacts for titles in clustered_contacts: common_titles_heading = 'Common Titles: ' + ', '.join(titles) descriptive_terms = set(titles[0].split()) for title in titles: descriptive_terms.intersection_update(set(title.split())) descriptive_terms_heading = 'Descriptive Terms: ' \ + ', '.join(descriptive_terms) print descriptive_terms_heading print '-' * max(len(descriptive_terms_heading), len(common_titles_heading)) print '\n'.join(clustered_contacts[titles]) #PART TWO: Incorporating random sampling can improve performance of the nested loops in Example 12 import os import csv import random from nltk.metrics.distance import jaccard_distance # XXX: Place your "Outlook CSV" formatted file of connections from # http://www.linkedin.com/people/export-settings at the following # location: resources/ch03-linkedin/my_connections.csv CSV_FILE = os.path.join("resources", "ch03-linkedin", 'my_connections.csv') # Tweak this distance threshold and try different distance calculations # during experimentation DISTANCE_THRESHOLD = 0.5 DISTANCE = jaccard_distance # Adjust sample size as needed to reduce the runtime of the # nested loop that invokes the DISTANCE function SAMPLE_SIZE = 500 def cluster_contacts_by_title(csv_file): transforms = [ ('Sr.', 'Senior'), ('Sr', 'Senior'), ('Jr.', 'Junior'), ('Jr', 'Junior'), ('CEO', 'Chief Executive Officer'), ('COO', 'Chief Operating Officer'), ('CTO', 'Chief Technology Officer'), ('CFO', 'Chief Finance Officer'), ('VP', 'Vice President'), ] separators = ['/', 'and', '&'] csvReader = csv.DictReader(open(csv_file), delimiter=',', quotechar='"') contacts = [row for row in csvReader] # Normalize and/or replace known abbreviations # and build up list of common titles all_titles = [] for i, _ in enumerate(contacts): if contacts[i]['Job Title'] == '': contacts[i]['Job Titles'] = [''] continue titles = [contacts[i]['Job Title']] for title in titles: for separator in separators: if title.find(separator) >= 0: titles.remove(title) titles.extend([title.strip() for title in title.split(separator) if title.strip() != '']) for transform in transforms: titles = [title.replace(*transform) for title in titles] contacts[i]['Job Titles'] = titles all_titles.extend(titles) all_titles = list(set(all_titles)) clusters = {} for title1 in all_titles: clusters[title1] = [] for sample in xrange(SAMPLE_SIZE): title2 = all_titles[random.randint(0, len(all_titles)-1)] if title2 in clusters[title1] or clusters.has_key(title2) and title1 \ in clusters[title2]: continue distance = DISTANCE(set(title1.split()), set(title2.split())) if distance < DISTANCE_THRESHOLD: clusters[title1].append(title2) # Flatten out clusters clusters = [clusters[title] for title in clusters if len(clusters[title]) > 1] # Round up contacts who are in these clusters and group them together clustered_contacts = {} for cluster in clusters: clustered_contacts[tuple(cluster)] = [] for contact in contacts: for title in contact['Job Titles']: if title in cluster: clustered_contacts[tuple(cluster)].append('%s %s' % (contact['First Name'], contact['Last Name'])) return clustered_contacts clustered_contacts = cluster_contacts_by_title(CSV_FILE) print clustered_contacts for titles in clustered_contacts: common_titles_heading = 'Common Titles: ' + ', '.join(titles) descriptive_terms = set(titles[0].split()) for title in titles: descriptive_terms.intersection_update(set(title.split())) descriptive_terms_heading = 'Descriptive Terms: ' \ + ', '.join(descriptive_terms) print descriptive_terms_heading print '-' * max(len(descriptive_terms_heading), len(common_titles_heading)) print '\n'.join(clustered_contacts[titles]) print #PART 3: How to export data (contained in the clusered contact variable) to power faceted display as outlined in figure 3 import json import os from IPython.display import IFrame from IPython.core.display import display data = {"label" : "name", "temp_items" : {}, "items" : []} for titles in clustered_contacts: descriptive_terms = set(titles[0].split()) for title in titles: descriptive_terms.intersection_update(set(title.split())) descriptive_terms = ', '.join(descriptive_terms) if data['temp_items'].has_key(descriptive_terms): data['temp_items'][descriptive_terms].extend([{'name' : cc } for cc in clustered_contacts[titles]]) else: data['temp_items'][descriptive_terms] = [{'name' : cc } for cc in clustered_contacts[titles]] for descriptive_terms in data['temp_items']: data['items'].append({"name" : "%s (%s)" % (descriptive_terms, len(data['temp_items'][descriptive_terms]),), "children" : [i for i in data['temp_items'][descriptive_terms]]}) del data['temp_items'] # Open the template and substitute the data TEMPLATE = 'resources/ch03-linkedin/viz/dojo_tree.html.template' OUT = 'resources/ch03-linkedin/viz/dojo_tree.html' viz_file = 'files/resources/ch03-linkedin/viz/dojo_tree.html' t = open(TEMPLATE).read() f = open(OUT, 'w') f.write(t % json.dumps(data, indent=4)) f.close() # IPython Notebook can serve files and display them into # inline frames. Prepend the path with the 'files' prefix display(IFrame(viz_file, '400px', '600px')) #PART 3: How to export data to power a dendogram and node-link tree visualization as outlined in Figure 4. import os import csv import random from nltk.metrics.distance import jaccard_distance from cluster import HierarchicalClustering # XXX: Place your "Outlook CSV" formatted file of connections from # http://www.linkedin.com/people/export-settings at the following # location: resources/ch03-linkedin/my_connections.csv CSV_FILE = os.path.join("resources", "ch03-linkedin", 'my_connections.csv') OUT_FILE = 'resources/ch03-linkedin/viz/d3-data.json' # Tweak this distance threshold and try different distance calculations # during experimentation DISTANCE_THRESHOLD = 0.5 DISTANCE = jaccard_distance # Adjust sample size as needed to reduce the runtime of the # nested loop that invokes the DISTANCE function SAMPLE_SIZE = 500 def cluster_contacts_by_title(csv_file): transforms = [ ('Sr.', 'Senior'), ('Sr', 'Senior'), ('Jr.', 'Junior'), ('Jr', 'Junior'), ('CEO', 'Chief Executive Officer'), ('COO', 'Chief Operating Officer'), ('CTO', 'Chief Technology Officer'), ('CFO', 'Chief Finance Officer'), ('VP', 'Vice President'), ] separators = ['/', 'and', '&'] csvReader = csv.DictReader(open(csv_file), delimiter=',', quotechar='"') contacts = [row for row in csvReader] # Normalize and/or replace known abbreviations # and build up list of common titles all_titles = [] for i, _ in enumerate(contacts): if contacts[i]['Job Title'] == '': contacts[i]['Job Titles'] = [''] continue titles = [contacts[i]['Job Title']] for title in titles: for separator in separators: if title.find(separator) >= 0: titles.remove(title) titles.extend([title.strip() for title in title.split(separator) if title.strip() != '']) for transform in transforms: titles = [title.replace(*transform) for title in titles] contacts[i]['Job Titles'] = titles all_titles.extend(titles) all_titles = list(set(all_titles)) # Define a scoring function def score(title1, title2): return DISTANCE(set(title1.split()), set(title2.split())) # Feed the class your data and the scoring function hc = HierarchicalClustering(all_titles, score) # Cluster the data according to a distance threshold clusters = hc.getlevel(DISTANCE_THRESHOLD) # Remove singleton clusters clusters = [c for c in clusters if len(c) > 1] # Round up contacts who are in these clusters and group them together clustered_contacts = {} for cluster in clusters: clustered_contacts[tuple(cluster)] = [] for contact in contacts: for title in contact['Job Titles']: if title in cluster: clustered_contacts[tuple(cluster)].append('%s %s' % (contact['First Name'], contact['Last Name'])) return clustered_contacts def display_output(clustered_contacts): for titles in clustered_contacts: common_titles_heading = 'Common Titles: ' + ', '.join(titles) descriptive_terms = set(titles[0].split()) for title in titles: descriptive_terms.intersection_update(set(title.split())) descriptive_terms_heading = 'Descriptive Terms: ' \ + ', '.join(descriptive_terms) print descriptive_terms_heading print '-' * max(len(descriptive_terms_heading), len(common_titles_heading)) print '\n'.join(clustered_contacts[titles]) print def write_d3_json_output(clustered_contacts): json_output = {'name' : 'My LinkedIn', 'children' : []} for titles in clustered_contacts: descriptive_terms = set(titles[0].split()) for title in titles: descriptive_terms.intersection_update(set(title.split())) json_output['children'].append({'name' : ', '.join(descriptive_terms)[:30], 'children' : [ {'name' : c.decode('utf-8', 'replace')} for c in clustered_contacts[titles] ] } ) f = open(OUT_FILE, 'w') f.write(json.dumps(json_output, indent=1)) f.close() clustered_contacts = cluster_contacts_by_title(CSV_FILE) display_output(clustered_contacts) write_d3_json_output(clustered_contacts) #PART 4: Once you've run the code adn produced the output for the dendogram and node-link tree visualizations, here's one way to serve it import os from IPython.display import IFrame from IPython.core.display import display # IPython Notebook can serve files and display them into # inline frames. Prepend the path with the 'files' prefix viz_file = 'files/resources/ch03-linkedin/viz/node_link_tree.html' # XXX: Another visualization you could try: #viz_file = 'files/resources/ch03-linkedin/viz/dendogram.html' display(IFrame(viz_file, '100%', '600px')) #--------------------------------------- Example 13 ---------------------------------------# import os import sys import json from urllib2 import HTTPError from geopy import geocoders from cluster import KMeansClustering, centroid # A helper function to munge data and build up an XML tree. # It references some code tucked away in another directory, so we have to # add that directory to the PYTHONPATH for it to be picked up. sys.path.append(os.path.join(os.getcwd(), "resources", "ch03-linkedin")) from linkedin__kml_utility import createKML # XXX: Try different values for K to see the difference in clusters that emerge K = 3 # XXX: Get an API key and pass it in here. See https://www.bingmapsportal.com. GEO_API_KEY = '' g = geocoders.Bing(GEO_API_KEY) # Load this data from where you've previously stored it CONNECTIONS_DATA = 'resources/ch03-linkedin/linkedin_connections.json' OUT_FILE = "resources/ch03-linkedin/viz/linkedin_clusters_kmeans.kml" # Open up your saved connections with extended profile information # or fetch them again from LinkedIn if you prefer connections = json.loads(open(CONNECTIONS_DATA).read())['values'] locations = [c['location']['name'] for c in connections if c.has_key('location')] # Some basic transforms may be necessary for geocoding services to function properly # Here are a couple that seem to help. transforms = [('Greater ', ''), (' Area', '')] # Step 1 - Tally the frequency of each location coords_freqs = {} for location in locations: if not c.has_key('location'): continue # Avoid unnecessary I/O and geo requests by building up a cache if coords_freqs.has_key(location): coords_freqs[location][1] += 1 continue transformed_location = location for transform in transforms: transformed_location = transformed_location.replace(*transform) # Handle potential I/O errors with a retry pattern... while True: num_errors = 0 try: results = g.geocode(transformed_location, exactly_one=False) break except HTTPError, e: num_errors += 1 if num_errors >= 3: sys.exit() print >> sys.stderr, e print >> sys.stderr, 'Encountered an urllib2 error. Trying again...' for result in results: # Each result is of the form ("Description", (X,Y)) coords_freqs[location] = [result[1], 1] break # Disambiguation strategy is "pick first" # Step 2 - Build up data structure for converting locations to KML # Here, you could optionally segment locations by continent or country # so as to avoid potentially finding a mean in the middle of the ocean. # The k-means algorithm will expect distinct points for each contact, so # build out an expanded list to pass it. expanded_coords = [] for label in coords_freqs: # Flip lat/lon for Google Earth ((lat, lon), f) = coords_freqs[label] expanded_coords.append((label, [(lon, lat)] * f)) # No need to clutter the map with unnecessary placemarks... kml_items = [{'label': label, 'coords': '%s,%s' % coords[0]} for (label, coords) in expanded_coords] # It would also be helpful to include names of your contacts on the map for item in kml_items: item['contacts'] = '\n'.join(['%s %s.' % (c['firstName'], c['lastName']) for c in connections if c.has_key('location') and c['location']['name'] == item['label']]) # Step 3 - Cluster locations and extend the KML data structure with centroids cl = KMeansClustering([coords for (label, coords_list) in expanded_coords for coords in coords_list]) centroids = [{'label': 'CENTROID', 'coords': '%s,%s' % centroid(c)} for c in cl.getclusters(K)] kml_items.extend(centroids) # Step 4 - Create the final KML output and write it to a file kml = createKML(kml_items) f = open(OUT_FILE, 'w') f.write(kml) f.close() print 'Data written to ' + OUT
UTF-8
Python
false
false
2,014
12,524,124,682,390
879cf3f181457d589877eabaab1f94d3d1f72dee
1929eac9dedf629b924c6a0d8e59b090d9c82335
/loq/urls.py
f2015ef7abd28cc37a406b90bd7632c4ad9c981f
[]
no_license
alvinwt/loq
https://github.com/alvinwt/loq
dc5fffd1786b85e90b9251dbb96ad3f24c4c557b
b92ffb2eb63edc81af802377332e35926c95ef91
refs/heads/master
2016-09-11T04:42:40.219161
2014-03-18T14:31:37
2014-03-18T14:31:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib import admin from rest_framework import routers from all_data_view import align, view, align_filter from home_view import IntervalList, int_filter from detail_view import AlignDetailView from interval_detail_view import IntervalDetailView from search_view import AlignViewSet, IntervalViewSet from graph_view import Graph_Form from django.conf.urls.static import static from django.contrib.auth.decorators import login_required, permission_required from views import AlignListAPIView,LibraryListView, IntView,coordinate,showStaticImage, AlignListView from django_filters.views import FilterView from loq.models import Library, Interval from user_detail import UserDetailView admin.autodiscover() router = routers.DefaultRouter() router.register(r'alignview', AlignViewSet) router.register(r'intview',IntervalViewSet) urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'^id/$',LibraryListView.as_view(),name='library_list'), url(r'^align/$',align,name="all_data"), # url(r'^(?P<pk>\d+)/align/graph<pk>.png$',plotResults,name='graph'), url(r'^(?P<pk>\d+)/align/$', AlignDetailView.as_view(), name='AlignDetailView'), url(r'^api/$', AlignListAPIView.as_view(), name='list'), url(r'^interval/$',login_required(IntervalList.as_view()),name='interval'), url(r'^(?P<pk>[0-9A-Za-z-_.//:]+)/interval/$', IntervalDetailView.as_view(), name='IntervalDetailView', ), # url(r'^(?P<pk>[0-9A-Za-z-_.//:]+)/interval/dist.png$', IntervalDetailView.get_dist, name='IntervalDetailViewDist', ), url(r'^interval/search/$',int_filter,name='int_filter'), url(r'^align/search/$',align_filter,name='align_filter'), url(r'^login/$', 'django.contrib.auth.views.login',{'template_name':'loq/login.html'}, name='login'), url('^logout/$', 'django.contrib.auth.views.logout_then_login',name='logout'), url(r'^',include(router.urls)), url(r'^favit/', include('favit.urls')), url(r'^', include('rest_framework.urls', namespace='rest_framework')), url(r'^comments/', include('django.contrib.comments.urls')), url(r'^(?P<pk>\d+)/user/$', UserDetailView.as_view(), name='user', ), url(r'^graph/$',Graph_Form, name='graph_form') ) urlpatterns += patterns('django.contrib.flatpages.views', url(r'^about-us/$', 'flatpage', {'url': '/about-us/'}, name='about'), url(r'^license/$', 'flatpage', {'url': '/license/'}, name='license'), url(r'^help/$', 'flatpage', {'url': '/help/'}, name='help'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^debug/$','debug'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^mysite/', include('mysite.foo.urls')), # # patterns can be added tgt '+=' v useful for diff patterns # urlpatterns += patterns('', # url(r'^admin/', include(admin.site.urls)), # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # (r'^lalign/$',AlignListView.as_view()),) # (r'^staticImage.png$', showStaticImage), # url(r'^balign/$',plotResults),
UTF-8
Python
false
false
2,014
1,743,756,772,577
c1a27ad4779b6fc53ccbbbd47d0e03416898f145
87965df0fb8d7b0c4a83a1d2ffd7000fe1f99d48
/project_euler/pjt_euler_pbm_10.py
5192817ca704ceca53897a87adae0f1839b7d2d5
[]
no_license
Anoopsmohan/Project-Euler-solutions-in-Python
https://github.com/Anoopsmohan/Project-Euler-solutions-in-Python
cd53e94acb27dec02c33b06d048a960a1393dc11
1f6d2d42ff263bcfe477aeb50f97da583018ac9d
refs/heads/master
2020-05-29T15:37:24.781366
2012-01-06T23:15:14
2012-01-06T23:15:14
3,121,768
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.''' def primes_list(num): primes, number = [2], 3 while number < num: isPrime = True for prime in primes: if number % prime ==0: isPrime = False break if (prime * prime > number): break if isPrime: primes.append(number) number += 2 return primes #print sum(primes_list(2000000)) primes = primes_list(2000000) print sum(primes)
UTF-8
Python
false
false
2,012
11,003,706,218,988
f480c186cc8667f9a967dcfc0d9cd13c7a398de9
8760f182049d4caf554c02b935684f56f6a0b39a
/boar/editorial_board/models.py
eb17c00d854a3063f76806db4c265d0b55de41e9
[ "BSD-3-Clause" ]
permissive
boar/boar
https://github.com/boar/boar
c674bc65623ee361af31c7569dd16c6eb8da3b03
6772ad31ee5bb910e56e650cc201a476adf216bc
refs/heads/master
2020-06-09T06:59:31.658154
2012-02-28T19:28:58
2012-02-28T19:28:58
1,734,103
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import datetime from django.contrib.auth.models import User from django.db import models from ordered_model.models import OrderedModel class Position(OrderedModel): email = models.EmailField(blank=True, null=True) def get_name(self): return self.positionname_set.latest() def get_members(self): return self.positionmember_set.filter( start_date__lte=datetime.date.today(), end_date__gte=datetime.date.today(), ) def __unicode__(self): return self.get_name().name class Meta(OrderedModel.Meta): pass class PositionName(models.Model): position = models.ForeignKey(Position) name = models.CharField(max_length=100) slug = models.SlugField() start_date = models.DateField(default=datetime.date.today, unique=True) class Meta: get_latest_by = 'start_date' class PositionMember(models.Model): position = models.ForeignKey(Position) user = models.ForeignKey(User) start_date = models.DateField(default=datetime.date.today) end_date = models.DateField(null=True, blank=True)
UTF-8
Python
false
false
2,012
6,605,659,735,124
03652398ba2a2a512347e14ca9733b1e8231ec9f
08b321dae00f79853cf9d24603a957969d745a71
/Problem79.py
7e88722585cf230ec4866b81a7cddb349340a316
[]
no_license
firefly2442/ProjectEuler-python
https://github.com/firefly2442/ProjectEuler-python
976371973ec24ae32f322c51504467f9509291be
c3953a70b752b3d047e1c37dd08d8ece6ce0d2b6
refs/heads/master
2016-09-06T19:38:11.158512
2014-11-06T16:05:03
2014-11-06T16:05:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Problem79.py import re keylog = """319 680 180 690 129 620 762 689 762 318 368 710 720 710 629 168 160 689 716 731 736 729 316 729 729 710 769 290 719 680 318 389 162 289 162 718 729 319 790 680 890 362 319 760 316 729 380 319 728 716""" numbers_test = keylog.split("\n") found = False password = 100 while not found: gauntlet = True for num in numbers_test: regex = r".*"+re.escape(num[0])+r".*"+re.escape(num[1])+r".*"+re.escape(num[2])+r".*" if not re.search(regex, str(password)): gauntlet = False break if gauntlet: print password found = True password += 1
UTF-8
Python
false
false
2,014
8,967,891,722,878
1f117e611c0cd40f8ae80d899a0d3db8f4ba2a3a
18f66ce22d4866e1a816750eb6aa5abb554d98a3
/main/views/internalViews.py
21eeb0a701c9cdc2bdbf0580305de0a13cd1c71a
[]
no_license
AlphaWang/VirtualFittingRoom
https://github.com/AlphaWang/VirtualFittingRoom
b9635c2d512bc59d3a32f766d32de1c6da4a4b93
7e38e6a780b8a2ca16f4bdb226b87fb3db0e55ce
refs/heads/master
2021-01-21T06:06:11.739076
2014-05-05T21:04:21
2014-05-05T21:04:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# don't change! from main.models import User, Category, Product, WishList, FitList, Comment, TempProduct, Added from django.http import HttpResponse from django.utils import timezone from django.contrib.auth.models import User as AUser def setUpDb(request): User.objects.all().delete() Category.objects.all().delete() Product.objects.all().delete() WishList.objects.all().delete() FitList.objects.all().delete() Comment.objects.all().delete() Added.objects.all().delete() TempProduct.objects.all().delete() glasses = Category(name='glasses') hats = Category(name='hats') headphones = Category(name='headphones') glasses.save() hats.save() headphones.save() rayban = Product(category = glasses, name='rayban glasses', brand = 'rayban',url='www.rayban.com', price = 129.9, description='stylish rayban', overlay='raybanol.png', photo='rayban.jpg') nike = Product(category = glasses, name='nike glasses', brand = 'nike', url='www.nike.com', photo='nike.jpg',overlay='nikeol.png', price = 99.9, description = 'sporty nike') adidas = Product(category = hats, name='adidas cap', brand = 'adidas', url='www.adidas.com', photo='addidas.jpg', overlay='addidasol.png', price = 56.9, description ='adidas cap!', yoffset = -0.58) levis = Product(category = hats, name='levis hat', brand = 'levis', url='www.levis.com', photo='levis.jpg', overlay='levisol.png', price = 67.9, description ='levis hat!', yoffset = -0.58) beats = Product(category = headphones, name='beats headphones', brand = 'beats', url='www.beats.com', photo='beats.jpg', overlay='beatsol.png', price = 256.9, description='stylish headphones!', yoffset = -0.15) sony = Product(category = headphones, name='sony headphones', brand = 'sony', url='www.sony.com', photo='sony.jpg', overlay="sonyol.png", price = 399.9, description='high quality headphones!', yoffset = -0.15) rayban.save() nike.save() adidas.save() levis.save() beats.save() sony.save() comment = Comment(product = rayban, owner = AUser.objects.get(pk=1), time=timezone.now(), content="Very nice glasses!") comment.save() wish = WishList(owner=AUser.objects.get(pk=1), product=rayban) wish.save() fit = FitList(owner=AUser.objects.get(pk=1), product=adidas) fit.save() return HttpResponse("Success!")
UTF-8
Python
false
false
2,014
10,488,310,144,112
60dce0e0aaf25379cbe0d3201be51b33d5a8a7f1
c586e3a92e0e98a4ec8455441c1385ae7fe99199
/pblog/core/orm.py
6aa5d542552cf526a97c7a10fac8fb192aa4455f
[ "GPL-2.0-only" ]
non_permissive
wenjunxiao/pblog
https://github.com/wenjunxiao/pblog
ea3e6a970b66b934dab4188747d12f0c5610e761
dd8deda3b4edcc1aec9f429284506eb4d001241b
refs/heads/master
2021-01-02T09:33:18.431899
2014-11-23T04:49:34
2014-11-23T04:49:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging, functools import db from utils import Dict class Field(object): _counter = 0 def __init__(self, name=None, max_length=None, default=None, primary_key=False, nullable=False, updatable=True, insertable=True): self.name = name self.max_length = max_length self._default = default self.primary_key = primary_key self.nullable = nullable self.updatable = updatable self.insertable = insertable self._order, Field._counter = Field._counter, Field._counter + 1 @property def default(self): d = self._default return d() if callable(d) else d def __str__(self): s = ['<%s:%s,default(%s),' % (self.__class__.__name__, self.name, self._default)] self.nullable and s.append('N') self.updatable and s.append('U') self.insertable and s.append('I') s.append('>') return ''.join(s) __repr__ = __str__ class AutoField(Field): def __init__(self, *args, **kwargs): kwargs['updatable'] = False kwargs['nullable'] = False kwargs['primary_key'] = True super(AutoField, self).__init__(*args, **kwargs) class StringField(Field): def __init__(self, max_length=255, default='', **kwargs): super(StringField, self).__init__(max_length=max_length, default=default, **kwargs) class IntegerField(Field): def __init__(self, default=0, **kwargs): super(IntegerField, self).__init__(default=default, **kwargs) class BigIntegerField(IntegerField): pass class FloatField(Field): def __init__(self, default=0.0, **kwargs): super(FloatField, self).__init__(default=default, **kwargs) class BooleanField(Field): def __init__(self, default=False, **kwargs): super(BooleanField, self).__init__(default=default, **kwargs) class TextField(Field): def __init__(self, default='', **kwargs): super(TextField, self).__init__(default=default, **kwargs) class BlobField(Field): def __init__(self, default='', **kwargs): super(BlobField, self).__init__(default=default, **kwargs) class VersionField(Field): def __init__(self, name=None): super(VersionField, self).__init__(name=name, default=0) _triggers = frozenset(['pre_insert', 'pre_update', 'pre_delete']) class ModelMetaclass(type): def __new__(cls, name, bases, attrs): # skip base model class parents = [b for b in bases if isinstance(b, ModelMetaclass)] if not parents: return super(ModelMetaclass, cls).__new__(cls, name, bases, attrs) logging.info("Scan ORMapping %s..." % name) fields = dict() primary_key = None for k, v in attrs.iteritems(): if isinstance(v, Field): if not v.name: v.name = k if v.primary_key: if v.updatable: logging.warning('NOTE: change primary key %s(in %s) to non-updatable.', v.name, name) v.updatable = False if v.nullable: logging.warning('NOTE: change primary key %s(in %s) to non-nullable.', v.name, name) v.nullable = False primary_key = v fields[k] = v if not primary_key: raise TypeError('primary key not defined in class: %s' % name) for k in fields.iterkeys(): attrs.pop(k) if not '__table__' in attrs: attrs['__table__'] = name.lower() attrs['__fields__'] = fields attrs['__primary_key__'] = primary_key for trigger in _triggers: if not trigger in attrs: attrs[trigger] = None return super(ModelMetaclass, cls).__new__(cls, name, bases, attrs) def _model_init(func): @functools.wraps(func) def _wrapper(self, *args, **kwargs): for k, v in self.__fields__.iteritems(): setattr(self, k, v.default) func(self, *args, **kwargs) return _wrapper class Model(Dict): r""" Base class for ORM. >>> import time >>> class User(Model): ... id = IntegerField(primary_key=True) ... name = StringField() ... email = StringField(updatable=False) ... passwd = StringField(default=lambda: '******') ... last_modified = FloatField() ... def pre_insert(self): ... self.last_modified = time.time() >>> u = User(id=10190, name='Michael', email='[email protected]') >>> r = u.insert() >>> u.email '[email protected]' >>> u.passwd '******' >>> u.last_modified > (time.time() - 2) True >>> f = User.get(10190) >>> f.name u'Michael' >>> f.email u'[email protected]' >>> f.email = '[email protected]' >>> r = f.update() # change email but email is non-updatable! >>> len(User.find_all()) 1 >>> g = User.get(10190) >>> g.email u'[email protected]' >>> r = g.delete() >>> len(db.where('user',id=10190)) 0 >>> print User.sql_create_table() CREATE TABLE user (id integer not null, name varchar(255) not null, email varchar(255) not null, passwd varchar(255) not null, last_modified double precision not null, primary key(id)) """ __metaclass__ = ModelMetaclass @_model_init def __init__(self, **kw): super(Model, self).__init__(**kw) @classmethod def get(cls, pk): d = db.select_one(cls.__table__, **{cls.__primary_key__.name: pk}) return cls(**d) if d else None @classmethod def find_first(cls, order=None, group=None, limit=None, offset=None, **kwargs): d = db.select_one(cls.__table__, order=order, group=group, limit=limit, offset=offset, **kwargs) return cls(**d) if d else None @classmethod def find_all(cls, order=None): l = db.select(cls.__table__, order=order) return [cls(**d) for d in l] @classmethod def find_by(cls, what='*', order=None, group=None, limit=None, offset=None, **kwargs): l = db.select(cls.__table__, what=what, where=kwargs, order=order, group=group, limit=limit, offset=offset) return [cls(**d) for d in l] @classmethod def count_all(cls): return db.select_int(cls.__table__, what='count(%s)' % cls.__primary_key__.name) @classmethod def count_by(cls, order=None, group=None, limit=None, offset=None, **kwargs): return db.select_int(cls.__table__, what='count(%s)' % cls.__primary_key__.name, where=kwargs, order=order, group=group, limit=limit, offset=offset) def update(self): self.pre_update and self.pre_update() pk = self.__primary_key__.name db.update(self.__table__, where=[(self.__primary_key__.name, getattr(self, pk))], **dict([(f.name, getattr(self, f.name)) for f in self.__fields__.itervalues() if f.updatable])) return self def delete(self): self.pre_delete and self.pre_delete() pk = self.__primary_key__.name db.delete(self.__table__, where=[(self.__primary_key__.name, getattr(self, pk))]) return self def insert(self): self.pre_insert and self.pre_insert() db.insert(self.__table__,**dict([(f.name, getattr(self, f.name)) for f in self.__fields__.itervalues() if f.insertable])) return self @classmethod def sql_create_table(cls): schema = db.schema_create_table() L = [] pk = None for field in sorted(cls.__fields__.values(),lambda a, b: cmp(a._order, b._order)): if field.primary_key: pk = field data_type = db.data_type(field.__class__.__name__) % field.__dict__ L.append('%s %s%s' % (field.name, data_type, '' if field.nullable else ' not null')) L.append('primary key(%s)' % pk.name) return schema % {'table':cls.__table__, 'definition':',\n '.join(L)} if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) db.create_engine(engine='db.mysql', user='root', password='root', database='test') db.execute('drop table if exists user') db.execute('create table user (id int primary key, name text, email text, passwd text, last_modified real)') import doctest doctest.testmod()
UTF-8
Python
false
false
2,014
14,534,169,362,015
12d72d5a1b4bea5a37753256e65dad112e03c7e3
985b3d5c9842e79c79b1fbdff37b43bd8f981b46
/stats/static_define.py
952d8a8b0b684950d34d47be300c96850ee95b1f
[]
no_license
aasa11/pstock
https://github.com/aasa11/pstock
93af3c8d9f94b01093c612103b3f21770464e310
905ba55b410fc704c2943fe06becda5445daef17
refs/heads/master
2021-01-10T21:23:49.326696
2013-12-17T09:07:24
2013-12-17T09:07:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/ #coding=gbk ''' @summary: @author: huxiufeng ''' #----------------------It is a split line-------------------------------------- G_POS_TYPE = {0 :'bfr', 1 :'aft'} G_CMP_TYPE = {0 :'equal', 1 :'bigger', 2 :'biggerorequal', 3 :'less', 4 :'lessorequal'} G_FETCH_TYPE = {0 : 'Count', 1 : 'DataandZero', 2 : 'DataandNone'} G_CALC_TYPE = {0 : 'Sum', 1 : 'Gap', 2 : 'Gap_rate'} G_MAXMIN_TYPE = {0 : 'upper', 1 : 'lower', 2 : 'median'} #----------------------It is a split line-------------------------------------- def main(): pass #----------------------It is a split line-------------------------------------- if __name__ == "__main__": main() print "It's ok"
UTF-8
Python
false
false
2,013
18,270,790,887,879
ecfe576df864eb312ffa77511f3bf659ce8ec0b0
874e9de25150cdc3013705174e2735cb82a41cfb
/scrapyd/pubsub/callbacks.py
3639aa94152da8db06a285193f6a0d701b1db89f
[ "BSD-3-Clause" ]
permissive
drankinn/scrapyd
https://github.com/drankinn/scrapyd
1b49fc17d52e0162e7388123194dc1d9d0668720
5ed7313b327e06237947e3a1c8a75389d273989b
refs/heads/master
2021-01-18T06:13:30.463508
2014-12-05T08:07:10
2014-12-05T08:07:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import pprint import uuid from scrapyd.interfaces import ISpiderScheduler, IPubSub __author__ = 'drankinn' from twisted.python import log class PubSubCallable: system = 'LogCallable' def __init__(self, app, message): self.app = app self.message = message def __call__(self): log.msg(format="%(msg)s", msg=self.message, system='PubSub:'+self.system) class LogScheduler(PubSubCallable): system = 'Scheduler' class LogLauncher(PubSubCallable): system = 'LogLauncher' class ScrapyScheduler(PubSubCallable): system = 'ScrapyScheduler' json_decoder = json.JSONDecoder() json_encoder = json.JSONEncoder() @property def scheduler(self): return self.app.getComponent(ISpiderScheduler) @property def pubsub(self): return self.app.getComponent(IPubSub) def __call__(self): print self.message try: args = self.json_decoder.decode(self.message) project = args.pop('project') spider = args.pop('spider') if args['_job'] is None: args['_job'] = uuid.uuid1().hex self.scheduler.schedule(project, spider, **args) except ValueError: pass
UTF-8
Python
false
false
2,014
14,319,421,004,592
81856a7691ff4a86dd5744915bc6a41d69e71f29
2b089a63a34d17041dfb79969283afbfa01d1bc6
/joy_mouse.py
9a8e3aea54e9700593a8115a3546349a040eb5cc
[]
no_license
prozacgod/GauntletPy
https://github.com/prozacgod/GauntletPy
fc58df32003aa14c8bca77aef08ad223d1830e42
db55600de622a2eb392e3a236aaf77055e30d015
refs/heads/master
2021-01-21T04:55:42.330661
2011-11-03T16:09:21
2011-11-03T16:09:21
2,699,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class JoyMouse(): def __init__(self, gauntlet): gauntlet_classes = [JoyMouse] if __name__ == "__main__": import gauntlet gauntlet.main(modules)
UTF-8
Python
false
false
2,011
9,869,834,882,538
1f0f45c230d60fe3c70d4c705fe0f2c2d814e0f9
850edadfff4570c55a0ecc81bc44f078b880a751
/ProjectEuler.py
ae126f976da08d6ba1a55520ef5d063a999c5063
[]
no_license
icr47/project_euler_python
https://github.com/icr47/project_euler_python
27b4072bb15897bdccbf0b139d5af7e0d4ade3da
034a8e083d52496c749898d2572282ff9eb12e1a
refs/heads/master
2016-09-06T21:45:18.253622
2013-12-24T00:04:41
2013-12-24T00:04:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class pe: def problem1(self, below, *mults): # Solved runningTotal = 0 i = 0 while i < below: totMult = 1 for mult in mults: totMult = totMult * mult if i % mult == 0: runningTotal += i if i % totMult == 0: runningTotal -= i i += 1; print(runningTotal) #prob 2 def get_next_fib(self): prevNum2 = 2 prevNum = 1 runningTotal = 2 cur_fib = 2 while cur_fib < 4000000: cur_fib = prevNum + prevNum2 prevNum = prevNum2 prevNum2 = cur_fib if cur_fib < 4000000: if cur_fib % 2 == 0: runningTotal += cur_fib else: print('fin.\n') print (runningTotal) #prob 3 def get_prime(self, max): i = max facts = [] while i > 0: if i % 2 == 0 and i != 2: # it's even, so not prime. throw away! pass; elif max % 5 == 0 and i != 5 # it's a x5, not prime. Throw away. elif max % i == 0: facts.append(i) i -= 1 print(facts) return facts #def get_prime(self, factors): # primes = [] # for fact in factors: # matches = 0 # i = fact # while i > 0: # if fact % i == 0: # matches += 1 # i -= 1 # if matches == 2: # primes.append(fact) # print(primes) def get_max_prime(self, max): # facts = self.get_fact_noneven(max) self.get_prime(max)
UTF-8
Python
false
false
2,013
16,423,954,962,995
068bb9aa22c661ad75f98c675760ae429f7d8f91
ded33675160dcac3926d131c1f8bd81c321a9e2d
/a1/q2/getscore.py
21b06a9f1f4e1ff08e9a38cf2bd59ca77611f589
[]
no_license
mattchaney/cs595-f14
https://github.com/mattchaney/cs595-f14
162c440051f7dcc8a77b62162195d4036bd38937
c23d560d4d257909612d439e1d0730990b51e3b7
refs/heads/master
2021-01-14T19:35:01.143146
2014-12-12T02:11:59
2014-12-12T02:11:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python import sys import requests import time import re from bs4 import BeautifulSoup if __name__ == "__main__": if len(sys.argv) != 4: print "Usage:\n\tpython getscore.py [school] [period] [uri]\n" sys.exit() school = sys.argv[1] try: period = float(sys.argv[2]) except ValueError: print "[period] parameter must be valid floating point number" sys.exit(1) uri = sys.argv[3] while True: try: response = requests.get(uri) except Exception as e: print e sys.exit(1) soup = BeautifulSoup(response.content) gametag = soup.find('em', text=re.compile('^'+school+'$')) if not gametag: print "Game not found" sys.exit() game = gametag.parent.parent.parent try: teams = [game.find_all('span', {'class':'team'})[0].em.text, game.find_all('span', {'class':'team'})[1].em.text] scores = [game.find('span', {'class':'away'}).text, game.find('span', {'class':'home'}).text] except: print "Game not found" sys.exit() print teams[0] + ' ' + scores[0] + ', ' + teams[1] + ' ' + scores[1] time.sleep(period)
UTF-8
Python
false
false
2,014
8,358,006,364,105
93b778feff40b33326bb94a864000abbe4315111
f7b20a5239ed86cf2050d6737964fc1bef25b996
/unicode/decode.py
2ce5a2d3c1ad82ec52bd2abe7700e0aa11d9ebaa
[]
no_license
manalhana64/Python-for-Fun-by-Chris-Meyers
https://github.com/manalhana64/Python-for-Fun-by-Chris-Meyers
9325f79eeda1865b33dd9e375667c3834979304f
d065c8a90a7d15cbee72c57fb15a3e5846f9b609
refs/heads/master
2020-08-20T22:16:30.755067
2011-05-21T13:41:57
2011-05-21T13:41:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/local/bin/python # # Decode bytes out of 32-126 range to <nn> (decimal) # import sys while 1 : lin = sys.stdin.readline() if not lin : break out = "" for c in lin[:-1] : n = ord(c) if n == 0 : out += '.' elif n > 126 : out += "-%x-" % n else : out += c print out
UTF-8
Python
false
false
2,011
6,889,127,555,164
5a1ac38b74c8c005b0c340af926308ec5c6fa729
8f255d9a43eef0cdcd9be0474f32055a63760813
/src/caldialog.py
7a5eb198cd54961657fa167ec50fb5793d285f65
[ "FSFUL", "GPL-2.0-only" ]
non_permissive
mola/jalali-calendar
https://github.com/mola/jalali-calendar
caf82d0704e3227bd6c22d363a340a95cf1637f3
8cf2998022ce28dee551a2e7af79f8b4544f8577
refs/heads/master
2016-09-06T08:45:44.331068
2014-04-28T08:22:13
2014-04-28T08:22:13
1,721,083
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # ## # # Copyright (C) 2007 Mola Pahnadayan # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## import pygtk pygtk.require('2.0') import gtk import gtk.gdk import calendar import os import os.path import utility from xml.dom.minidom import getDOMImplementation, parse from xml.parsers.expat import ExpatError from string import strip, lower DATA_DIR="/usr/share/jalali-calendar" mon_name = ["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور" ,"مهر","آبان","آذر","دی","بهمن","اسفند"] milady_monname = ["January","February","March","April","May","June","July", "August","September","October","November","December"] extrafile = "/.jcal_extra.xml" imagelist={0:"balloons-aj.png",1:"marid.png",2:"shabdar.png",3:"cday.png"} def _get_text(nodelist): rc = u"" name = nodelist.nodeName for node in nodelist.childNodes: if node.nodeType == node.TEXT_NODE: rc = rc+ node.data return name,rc.strip() def get_home(): return os.environ.get('HOME', '') def convert_to_str(num): s = str(num) uni_c = [u'\u06f0',u'\u06f1',u'\u06f2',u'\u06f3',u'\u06f4',u'\u06f5',u'\u06f6',u'\u06f7',u'\u06f8',u'\u06f9'] res = u"" if len(s)>0: for i in s: res += uni_c[int(i)] return res class wmonth: def __init__(self): self.hbox=gtk.HBox() self.arrow_left2=gtk.Button() self.arrow_left2.set_relief(2) image=gtk.image_new_from_stock(gtk.STOCK_GO_BACK,gtk.ICON_SIZE_SMALL_TOOLBAR) self.arrow_left2.set_image(image) self.hbox.pack_start(self.arrow_left2,0,0,0) self.monthname=gtk.Label(" <b></b> ") self.monthname.set_use_markup(True) self.hbox.pack_start(self.monthname,0,0,0) self.arrow_right2=gtk.Button() self.arrow_right2.set_relief(2) image=gtk.image_new_from_stock(gtk.STOCK_GO_FORWARD,gtk.ICON_SIZE_SMALL_TOOLBAR) self.arrow_right2.set_image(image) self.hbox.pack_start(self.arrow_right2,0,0,0) self.hbox.show_all() self .label=gtk.HSeparator() self.hbox.pack_start(self.label,1,1,0) self.arrow_left=gtk.Button() self.arrow_left.set_relief(2) image=gtk.image_new_from_stock(gtk.STOCK_GO_BACK,gtk.ICON_SIZE_SMALL_TOOLBAR) self.arrow_left.set_image(image) self.hbox.pack_start(self.arrow_left,0,0,0) self.yearnum=gtk.Label(" <b></b> ") self.yearnum.set_use_markup(True) self.hbox.pack_start(self.yearnum,0,0,0) self.arrow_right=gtk.Button() self.arrow_right.set_relief(2) image=gtk.image_new_from_stock(gtk.STOCK_GO_FORWARD,gtk.ICON_SIZE_SMALL_TOOLBAR) self.arrow_right.set_image(image) self.hbox.pack_start(self.arrow_right,0,0,0) class Main(gtk.Window): ww = 300 wh = 70 wh2 = 0 def change_db(self,year): calfile=DATA_DIR+"/"+str(year)+".xml" if (os.path.isfile(calfile)): tmp = parse(calfile).documentElement self.db=tmp.getElementsByTagName("day") else: self.db=None def get_dayname(self,month,day): if (self.db==None): return None find = False for record in self.db: for element in record.childNodes: if element.nodeType != element.TEXT_NODE: if element.nodeType != element.TEXT_NODE: name, data = _get_text(element) if (name=="num"): sp=data.split("/") if ( (month==int(sp[0])) and (day==int(sp[1])) ): find = True if ((name=="desc") and (find==True) ): return data return None def __init__(self,year,month,day,size): self.db = None self.db2 = None self.change_db(year) #csize = [(146,300),(180,235),(205,335),(290,435)] #self.wh,self.ww = csize[size] self.full_list = get_customday(month,day) gtk.Window.__init__(self) self.set_keep_above(True) self.set_position(gtk.WIN_POS_MOUSE) self.set_decorated(False) self.set_has_frame(False) #self.set_resizable(False) self.set_border_width(0) self.set_skip_taskbar_hint(True) self.set_default_size(self.ww,self.wh) self.box2=gtk.Viewport() self.vbox2=gtk.VBox() self.vbox2.set_spacing(1) self.box2.add(self.vbox2) self.box1=gtk.Viewport() self.box1.set_border_width(5) self.vbox2.pack_start(self.box1,0,0,0) self.hbox3=gtk.HBox() self.date_label=gtk.Label() self.date_label.set_selectable(True) self.hbox3.pack_start(self.date_label,1,1,0) self.date_labelm=gtk.Label() self.date_labelm.set_selectable(True) self.hbox3.pack_start(self.date_labelm,1,1,0) self.vbox2.pack_start(self.hbox3,0,0,0) self.dayname=gtk.TextView() self.dayname.set_wrap_mode(gtk.WRAP_WORD) self.dayname.set_editable(False) self.dayname.set_cursor_visible(False) self.dayname.set_justification(gtk.JUSTIFY_CENTER) self.dayname.set_border_width(3) self.dayname.connect("size_request",self.checkresize) self.vbox2.pack_start(self.dayname,0,0,0) self.customday = gtk.TreeView() self.customstor = gtk.ListStore(gtk.gdk.Pixbuf,str) self.customday.set_model(self.customstor) self.customday.connect("size_request",self.checkresize_c) self.customday.set_headers_visible(False) cell0 = gtk.CellRendererPixbuf() col = gtk.TreeViewColumn("",cell0,pixbuf = 0) self.customday.append_column(col) cell1 = gtk.CellRendererText() col = gtk.TreeViewColumn("Date",cell1,text=1) self.customday.append_column(col) self.vbox2.pack_start(self.customday,0,0,0) self.add(self.box2) self.connect("destroy",self.quit) self.vbox=gtk.VBox() self.vbox.set_spacing(3) self.box1.add(self.vbox) self.header=wmonth() self.vbox.pack_start(self.header.hbox,0,0,0) self.header.arrow_left2.connect("clicked",self.month_prev) self.header.arrow_right2.connect("clicked",self.month_next) self.header.arrow_left.connect("clicked",self.year_prev) self.header.arrow_right.connect("clicked",self.year_next) #self.header.hbox.show_all() self.cal=calendar.pcalendar(year,month,day,DATA_DIR,loadcustomlist(),size) self.cal.connect("month-change",self.monthchange) self.cal.connect("day-change",self.daychange) #self.cal.show() self.vbox.pack_start(self.cal ,1 ,1, 0) self.wh += self.cal.get_cal_height() self.header.yearnum.set_label("<b>"+convert_to_str(year)+"</b>") self.header.monthname.set_label(' <b>'+mon_name[month-1]+'</b> ') self.day=day self.month=month self.year=year self.box2.show_all() self.change_lable(self.day) slabel=self.get_dayname(month,day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.wh2=self.dayname.get_visible_rect()[3] self.resize(self.ww,self.wh+self.wh2) else: self.dayname.hide() self.wh2 = 0 if (self.full_list != None): self.loadcustomday(self.month, self.day) self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() def checkresize(self,obj,data=None): self.wh2=data[1]-6 self.resize(self.ww,self.wh+data[1]-6) def checkresize_c(self,obj,data=None): self.resize(self.ww,self.wh+self.wh2+data[1]-6) def monthchange(self,obj=None,month=None,year=None): self.header.yearnum.set_label("<b>"+convert_to_str(year)+"</b>") self.header.monthname.set_label(' <b>'+mon_name[month-1]+'</b> ') self.change_lable(self.day) if (self.year!=year): self.change_db(year) slabel=self.get_dayname(month,self.day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.dayname.show() else: self.dayname.hide() self.wh2=0 result = self.loadcustomday(self.month,self.day) if (result ==True): self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() if (result==False)and(slabel==None): self.resize(self.ww,self.wh) def daychange(self,obj=None,month=None,year=None,day=None): self.change_lable(day) self.day=day self.month=month self.year=year if (self.year!=year): self.change_db(year) slabel=self.get_dayname(month,day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.dayname.show() else: self.dayname.hide() self.wh2=0 result = self.loadcustomday(self.month,self.day) if (result ==True): self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() if (result==False)and(slabel==None): self.resize(self.ww,self.wh) def month_next(self,obj,data=None): self.cal.next_month() month=self.cal.get_month() self.header.monthname.set_label(' <b>'+mon_name[month-1]+'</b> ') year=self.cal.get_year() self.header.yearnum.set_label(' <b>'+convert_to_str(year)+'</b> ') self.month=month if (self.year!=year): self.change_db(year) else: self.dayname.hide() self.year=year self.change_lable(self.day) slabel=self.get_dayname(month,self.day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.dayname.show() else: self.dayname.hide() self.wh2=0 result = self.loadcustomday(self.month,self.day) if (result ==True): self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() if (result==False)and(slabel==None): self.resize(self.ww,self.wh) self.date_label.set_label(str(year)+"/"+str(month)+"/"+str(self.day)) def month_prev(self,obj,data=None): self.cal.prev_month() month=self.cal.get_month() self.header.monthname.set_label(' <b>'+mon_name[month-1]+'</b> ') year=self.cal.get_year() self.header.yearnum.set_label(' <b>'+convert_to_str(year)+'</b> ') self.month=month if (self.year!=year): self.change_db(year) self.year=year self.change_lable(self.day) slabel=self.get_dayname(month,self.day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.dayname.show() else: self.dayname.hide() self.wh2=0 result = self.loadcustomday(self.month,self.day) if (result ==True): self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() #if (result==False)and(slabel==None): self.resize(self.ww,self.wh+self.wh2) self.date_label.set_label(str(year)+"/"+str(month)+"/"+str(self.day)) def year_next(self,obj,data=None): self.cal.next_year() year=self.cal.get_year() self.header.yearnum.set_label(' <b>'+convert_to_str(year)+'</b> ') self.year=year self.change_lable(self.day) self.change_db(year) slabel=self.get_dayname(self.month,self.day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.dayname.show() else: self.dayname.hide() self.wh2=0 result = self.loadcustomday(self.month,self.day) if (result ==True): self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() if (result==False)and(slabel==None): self.resize(self.ww,self.wh) self.date_label.set_label(str(year)+"/"+str(self.month)+"/"+str(self.day)) def year_prev(self, obj, data=None): self.cal.prev_year() year=self.cal.get_year() self.header.yearnum.set_label(' <b>'+convert_to_str(year)+'</b> ') self.year=year self.change_lable(self.day) self.change_db(year) slabel=self.get_dayname(self.month,self.day) if (slabel!=None): buf = self.dayname.get_buffer() buf.set_text(slabel) self.dayname.set_buffer(buf) self.dayname.show() else: self.dayname.hide() self.wh2=0 result = self.loadcustomday(self.month,self.day) if (result ==True): self.resize(self.ww,self.wh+self.wh2+self.customday.get_visible_rect()[3]) else: self.customday.hide() if (result==False)and(slabel==None): self.resize(self.ww,self.wh) self.date_label.set_label(str(year)+"/"+str(self.month)+"/"+str(self.day)) def change_lable(self, day): year = self.cal.get_year() month=self.cal.get_month() y,m,d = utility.jalali_to_milady(year,month,day) text = "%s/%s (%s) /%s" % (y, milady_monname[m-1], m, d) self.date_labelm.set_label(text) text = "%s/%s/%s" % (year, month, day) self.date_label.set_label(text) def loadcustomday(self,mm,dd): find = False alllist=get_customday(mm,dd) if alllist!=None: find = True self.customstor.clear() for element in alllist: try: pix = gtk.Image() file = DATA_DIR+"/"+imagelist.get(int(element[2])) pix.set_from_file(file) p=pix.get_pixbuf() except: p=None self.customstor.append([p,element[3]]) self.customday.show() return find def quit(self,obj): self.destroy() def getcustomfile(): calfile=get_home()+extrafile if (os.path.isfile(calfile)): tmp = parse(calfile).documentElement return tmp.getElementsByTagName("day") else: return None def loadcustomlist(): customdb = getcustomfile() if customdb==None: return None full_list = [] for record in customdb: list = [] for element in record.childNodes: if element.nodeType != element.TEXT_NODE: if element.nodeType != element.TEXT_NODE: name, data = _get_text(element) if (name=="num"): sp=data.split("/") list.append(int(sp[0])) list.append(int(sp[1])) if (name=="kind"): list.append(int(data)) if (name=="desc"): list.append(data) full_list.append(list) return full_list def get_customday(mm,dd,fill=False): customdb = getcustomfile() if customdb==None: return None alllist = [] for record in customdb: list = [] find = False for element in record.childNodes: if element.nodeType != element.TEXT_NODE: if element.nodeType != element.TEXT_NODE: name, data = _get_text(element) if (name=="num"): sp=data.split("/") if ( (int(sp[0])==mm)and(int(sp[1])==dd) ): find = True list.append(sp[0]) list.append(sp[1]) if (find==True)and(name=="kind"): list.append(data) if (find==True)and(name=="desc"): list.append(data) if list!=[]: alllist.append(list) if alllist!=[]: return alllist else: return None
UTF-8
Python
false
false
2,014
14,516,989,483,381
be337b1abe60ea9ee9d7e847d715b70a9681018a
08703b748fc7d7182f007d5e394681781f1a5d9a
/tests.py
a065867ba322a4fa0aa6171142bf532cf98043b4
[]
no_license
diogoosorio/henrique
https://github.com/diogoosorio/henrique
750250f417e8c2e2158af6a9b6c23291b010a1a6
aa80a5717051fa8af6e5c10359e2889463ec2065
refs/heads/master
2018-03-26T16:46:50.049767
2014-05-04T20:09:23
2014-05-04T20:09:23
19,168,768
0
1
null
false
2018-05-03T18:01:24
2014-04-26T04:29:08
2014-05-04T20:09:47
2017-10-09T17:58:07
228
0
1
0
Python
false
null
#!/usr/bin/env python # -*- coding: utf-8 -*- if __name__ == "__main__": from henrique.tests import TestSuite testsuite = TestSuite() testsuite.run()
UTF-8
Python
false
false
2,014
14,542,759,266,564
5c6b159e40363a0774a1bb13e8ce8b8a9f45329a
39bb97cbe520f05d4d1739c74552aab51ff0379b
/Generator/Emitter/EmitCode.py
8533d351bfb206c7f6be8afdcf13583788fe9f9b
[ "MIT" ]
permissive
pombredanne/poodle-lex
https://github.com/pombredanne/poodle-lex
ec482c881792d9523631a3f7bebcb840175ff895
eb6fea4826229077246bbaef031dabc239498b90
refs/heads/master
2020-04-06T04:10:50.535000
2014-11-09T04:19:02
2014-11-09T04:19:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (C) 2014 Parker Michaels # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. class CodeEmitter(object): """ A helper class for writing indented lines to a file. @ivar indent_size: integer representing the current indentation @ivar stream: Python file object to which lines should be written """ class Block(object): """ Object which hides some boilerplate code for writing indented blocks behind python's "with" statement """ def __init__(self, emitter, opening_line, closing_line): self.emitter = emitter self.opening_line = opening_line self.closing_line = closing_line def __enter__(self): if self.opening_line != "": self.emitter.line(self.opening_line) self.emitter.indent() def __exit__(self, type, value, traceback): self.emitter.dedent() if self.closing_line != "": self.emitter.line(self.closing_line) def __init__(self, stream=None, initial_indent=0, indent_spaces=4): """ @param stream: Python file object to which lines should be written. """ self.indent_size = initial_indent self.indent_spaces = indent_spaces self.stream = stream def indent(self): """ Increases the current indentation """ self.indent_size += self.indent_spaces def dedent(self): """ Decreases the current indentation """ self.indent_size -= self.indent_spaces def open_line(self): """ Start a new, indented line. """ self.write(' '*self.indent_size) def close_line(self): """ End an indented line. """ self.write('\n') def write(self, text): """ Write text to the stream @param text: string containg the text to write to the stream """ self.stream.write(text) def line(self, text=""): """ Write a single indented line at once. @param text: string containing the contents of the line. """ lines = text.split("\n") for line in lines: self.open_line() self.write(line) self.close_line() def block(self, opening_line="", closing_line=""): """ Returns an object for use with Python's "with" statement. Code printed inside the with statement will be indented and wrapped in opening and closing lines. Omitting opening_line and closing_line will indent, but not print any lines (useful for printing single-line blocks without braces in C-like languages) @param opening_line: The text at the head of the block (such as "do" or "if") @param closing_line: The text at the tail of the block (such as "loop" or "end if") """ return CodeEmitter.Block(self, opening_line, closing_line) def continue_block(self, *lines): """ For use inside "with code.block()" sections, this method ends the current block body and starts another. Useful, for instance, with "if, then else" statements with multiple bodies. @param line: Lines of text to divide the two sections """ self.dedent() for line_of_code in lines: self.line(line_of_code) self.indent() def inherit(self, parent): """ Start using the stream from another CodeEmitter object @param parent: another CodeEmitter object from which to inherit. """ self.stream = parent.stream self.indent_size = parent.indent_size def emit(self, lines): """ Emit list of strings as a block of lines. @param lines: list of either strings or sub-lists """ for line in lines: # unpythonic, but distinguishes str from other iterables if hasattr(line, '__iter__'): self.indent() self.emit(line) self.dedent() else: self.line(line)
UTF-8
Python
false
false
2,014
532,575,953,792
51c7dd840d2192233cd26edf593d71ea9008336a
53766824b505a24be6627b3311104a53393a3b07
/minecraft.py
7ecafaef3593c33e1f0af71dc420a68684ef84d2
[]
no_license
YellowOnion/minecraft.py
https://github.com/YellowOnion/minecraft.py
8d9fe19cfc8b41fe9e16264e18bcccca601d80ee
0c4db226a8a35f4880528b1e98936b280de42ec6
refs/heads/master
2016-09-06T21:25:27.271245
2011-05-31T16:04:09
2011-05-31T16:04:09
1,814,116
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
print 'importing twisted' from twisted.application import internet, service from twisted.internet import reactor, protocol, defer, utils from twisted.protocols import basic from twisted.python import components from zope.interface import Interface, implements print 'importing os' import os, re, random as r, shlex, time class LineEventer(basic.LineReceiver): delimiter = '\n' service = None cmd_deffered = None def connectionMade(self): self.ops = [ x[:-1].lower() for x in open(os.path.join(run_dir, 'ops.txt'))\ .readlines() ] print self.ops self.re_strip = re.compile(r'^\d{4}-\d{2}-\d{2} ' + \ '\d{2}:\d{2}:\d{2} \[INFO\]' +\ ' (.+)$') self.re_event = re.compile(r'^(\w+):? (.+)$') self.re_events = [ (re.compile(r'issued server command: (.+)'), self.cmd), # (re.compile(r'Forcing save\.\.'), self.forcing_save), (re.compile(r'Save complete\.'), self.save_complete), (re.compile(r'lost connection: disconnect\.(.+)'), self.player_disconnect), (re.compile(r'.+logged in.+'), self.player_connect), ] def lineReceived(self, line): print line stripped = self.re_strip.search(line) if stripped: print 'stripped', stripped event = self.re_event.search(stripped.group(1)) if event: print 'event', event for re, func in self.re_events: match = re.search(event.group(2)) if match: print 'match', match def error(err): err.printTraceback() d = defer.Deferred() d.addCallback(func, event.group(1).lower()) d.addErrback(error) d.callback(match) break def player_connect(self, match, player): self.service.player_connect(player) def player_disconnect(self, match, player): reason = match.group(1) self.service.player_disconnect(player, reason) def save_complete(self, match, player): self.service.save_complete() def cmd(self, match, player): if match: cmd_args = match.group(1)[:-1].split(' ', 1) try: cmd, args = cmd_args except ValueError: cmd, args = cmd_args[0], None c = getattr(self, 'cmd_' + cmd, None) if not c: builtins = ['say', 'kick', 'ban', 'pardon', 'ban-ip', 'pardon-ip', 'op', 'deop', 'tp', 'give', 'tell', 'stop', 'save-all', 'save-off', 'save-on', 'list', 'time'] if cmd not in builtins: self.minecraft.tell(player, cmd + ' not found') else: d = c(player, args) def cmd_echo(self, player, args): if args: return defer.succeed( self.minecraft.say( player + ': ' + args)) else: return defer.succeed(self.minecraft.say( 'well what do you want to echo?')) def cmd_backup(self, player, args): self.minecraft.say(player + ' issued command to backup') if player in self.ops: self.service.backup() class DummyTransport: disconnecting = 0 transport = DummyTransport() class MinecraftProtocol(protocol.ProcessProtocol): service = None empty = 1 def connectionMade(self): self.output = LineEventer() self.output.minecraft = self self.output.service = self.service self.output.makeConnection(transport) def outReceived(self, data): self.output.dataReceived(data) self.empty = data[-1] == '\n' errReceived = outReceived def processEnded(self, reason): if not self.empty: self.output.dataReceived('\n') self.service.connectionLost() def say(self, *args): for msgs in args: for msg in msgs.split('\n'): self.transport.write('say ' + msg + '\n') def kick(self, player): self.transport.write('kick ' + player + '\n') def ban(self, player): self.transport.write('ban ' + player + '\n') def pardon(self, player): self.transport.write('pardon ' + player + '\n') def ban_ip(self, ip): self.transport.write('ban-ip ' + ip + '\n') def pardon_ip(self, ip): self.transport.write('pardon-ip ' + ip + '\n') def op(self, player): self.transport.write('op ' + player + '\n') def deop(self, player): self.transport.write('deop ' + player + '\n') def tp(self, player_from, player_to): self.transport.write('tp ' + player_from + ' ' + player_to + '\n') def give(self, player, id , num=None): if num: self.transport.write('give ' + player + ' ' + str(id) + ' ' + \ str(num) + '\n') else: self.transport.write('give ' + player + ' ' + str(id) + '\n') def tell(self, player, *args): for msgs in args: for msg in msgs.split('\n'): self.transport.write('tell ' + player + ' ' + msg + '\n') def stop(self): self.transport.write('stop\n') def save_all(self): self.transport.write('save-all\n') def save_off(self): self.transport.write('save-off\n') def save_on(self): self.transport.write('save-on\n') def list(self): self.transport.write('list\n') def time(self, action, amount): self.transport.write('time ' + action + ' ' + str(amount) + '\n') class MinecraftService(service.Service): fatal_time = 1 active = 0 eventer = None time_started = 0 threshold = 1 # secounds minecraft = None stopping_deferred = None saving = None backingup = None playing = {} def __init__(self, run_dir): self.run_dir = run_dir def startService(self): service.Service.startService(self) self.active = 1 reactor.callLater(0, self.start_minecraft) def stopService(self): service.Service.stopService(self) self.active = 0 self.minecraft.stop() d = self.stopping_deferred = defer.Deferred() return d def start_minecraft(self): p = self.minecraft = MinecraftProtocol() p.service = self self.time_started = time.time() reactor.spawnProcess(p, '/usr/bin/minecraft-server', args=['minecraft-server', 'nogui'], env=os.environ, path=self.run_dir, usePTY=True) def connectionLost(self): if self.active: if time.time() - self.time_started < self.threshold: print 'Minecraft died too quickly, giving up!' else: reactor.callLater(0, self.start_minecraft) else: print 'service stopping not restarting Minecraft' self.stopping_deferred.callback(None) def backup(self): try: world = self.world except AttributeError: props_file = open(os.path.join(self.run_dir, 'server.properties')) for line in props_file.readlines(): if line.startswith('level-name'): world = self.world = line.split('=')[1].strip() backup_dir = os.path.join(self.run_dir, 'backups') if not os.path.exists(backup_dir): os.mkdir(backup_dir) bu_dir_pre = os.path.join(backup_dir, 'minecraft_') self.saving = defer.Deferred() self.minecraft.save_off() self.minecraft.save_all() def finished(ignore): print 'tar exited with code', ignore self.saving = None self.backingup = None self.minecraft.say('backup complete') self.minecraft.save_on() def backup(ignore): if not self.backingup: print 'spawning tar' d = self.backingup = \ utils.getProcessOutputAndValue('/bin/tar', args=['-cjf', bu_dir_pre + \ time.strftime('%F.%T%z') + \ '.tar.bz2', world], env=os.environ, path=self.run_dir) d.addCallbacks(finished, failed_backup) else: self.minecraft.say('already backing up!') def failed_backup(err): self.minecraft.say('backup failed') err.printTraceback() return self.saving.addCallbacks(backup, failed_backup) def save_complete(self): print 'function save_complete called' if self.saving: print 'saving deferred' self.saving.callback('done') else: print 'saving deferred missing OH NO!' def player_disconnect(self, player, reason): print 'player disconnected:', player, reason self.playing[player].callback(reason) del self.playing[player] if not self.playing: self.backup() def player_connect(self, player): print 'player connected:', player self.playing[player] = defer.Deferred() run_dir = os.path.dirname(__file__) application = service.Application('minecraft') minecraft = MinecraftService(run_dir) minecraft.setServiceParent(application)
UTF-8
Python
false
false
2,011
2,680,059,641,323
1fde6947d794b08eb7dd21927e6ee00f1ac79181
deb3698464043c3187c8fec78d6f1fcf81d0534c
/demos/diff_obj_id.py
9bf65a9ffc4c9f20f06933ca3b0a1f25dfe1a540
[ "BSD-3-Clause" ]
permissive
justinabrahms/dictshield
https://github.com/justinabrahms/dictshield
9250031d3b4b72ab9fe94699501fdeb2dc26e684
1d0a930e96417a2c7ed60b3108e9c6df07a4b45c
refs/heads/master
2021-01-16T20:03:26.357285
2012-02-13T02:20:09
2012-02-13T02:20:09
3,426,452
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """SimpleDoc: {'_types': ['SimpleDoc'], 'title': u'simple doc', 'num': 1998, '_cls': 'SimpleDoc', '_id': ObjectId('4ee41cdc0f43833917000000')} Validating SimpleDoc instance Validation passed ComplexDoc: {'_types': ['SimpleDoc', 'SimpleDoc.ComplexDoc'], 'title': u'complex title', 'num': 1996, '_cls': 'SimpleDoc.ComplexDoc', '_id': ObjectId('4ee41cdc0f43833917000001')} ComplexDoc JSON: {"_types": ["SimpleDoc", "SimpleDoc.ComplexDoc"], "title": "complex title", "num": 1996, "_cls": "SimpleDoc.ComplexDoc", "_id": "4ee41cdc0f43833917000001"} ComplexDoc ownersafe: {'num': 1996, 'title': 'complex title'} ComplexDoc publicsafe: {'id': ObjectId('4ee41cdc0f43833917000001')} Validating ComplexDoc instance Validation passed """ from dictshield.document import diff_id_field from dictshield.document import Document from dictshield.fields import StringField, IntField from dictshield.fields.mongo import ObjectIdField from bson.objectid import ObjectId ### ### Decorate a Document instance with diff_id_field to swap UUIDField for ### ObjectIdField. ### @diff_id_field(ObjectIdField, ['id']) class SimpleDoc(Document): title = StringField(max_length=40) num = IntField() sd = SimpleDoc() sd.title = 'simple doc' sd.num = 1998 sd.id = ObjectId() print 'SimpleDoc:\n\n %s\n' % (sd.to_python()) print 'Validating SimpleDoc instance' sd.validate() print 'Validation passed\n' ### ### Subclass decorated object to show inheritance works fine ### class ComplexDoc(SimpleDoc): body = StringField() cd = ComplexDoc() cd.title = 'complex title' cd.num = 1996 cd.id = ObjectId() print 'ComplexDoc:\n\n %s\n' % (cd.to_python()) print 'ComplexDoc JSON:\n\n %s\n' % (cd.to_json()) print 'ComplexDoc ownersafe:\n\n %s\n' % (ComplexDoc.make_ownersafe(cd)) print 'ComplexDoc publicsafe:\n\n %s\n' % (ComplexDoc.make_publicsafe(cd)) print 'Validating ComplexDoc instance' cd.validate() print 'Validation passed\n'
UTF-8
Python
false
false
2,012
1,614,907,710,174
2a521ad37632e9207645d854ee2a54a31667b8b6
87c9983636fee505b6ec1cdc73b0b71970b58a41
/makeblog/makeblog.py
0f58fe04e0242d6cd91882591eb3c7778d4d980c
[ "BSD-2-Clause" ]
permissive
fyhuang/makeblog
https://github.com/fyhuang/makeblog
48328b35e5b211763a595c6671975c71d5cc2fde
216e9e62803c703c5d60b95be9690c50935e027a
refs/heads/master
2016-08-04T04:00:48.859071
2012-07-27T22:09:37
2012-07-27T22:09:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import argparse from datetime import datetime import compileblog import server import config as cf import utils def main(): parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('command_arg') args = parser.parse_args() if args.command == 'compile': config = cf.load_config(args.command_arg) compileblog.compile_all(config) elif args.command == 'wpimport': import wpimport wpimport.main(args.command_arg) elif args.command == 'refresh': config = cf.load_config(args.command_arg) import twitter twitter.refresh_tweets(config) elif args.command == 'newpost': title = args.command_arg slug = utils.title_to_slug(title) now = datetime.utcnow() fname = 'drafts/{}-{}.md'.format(now.strftime('%Y-%m-%d-%H-%M'), slug) with open(fname, 'w') as f: f.write('---\ntitle: "') f.write(title) f.write('"\n---\n') import subprocess subprocess.call(['open', fname]) elif args.command == 'edit' or args.command == 'editpost': # TODO pass elif args.command == 'publish': # TODO pass elif args.command == 'serve': config = cf.load_config(args.command_arg) config.is_dynamic = True server.serve(config) else: print("Unknown command " + args.command) sys.exit(1) if __name__ == "__main__": main()
UTF-8
Python
false
false
2,012
10,943,576,700,061
b72008edd68a3c845796b5a4c17385eaf79dbd7b
6e92491f8bbf699f0af7d3c2a5b72bbd8d13b257
/tcmty.py
d7f6f7c91d7006e4c9b24e7d5696fc52ea9872c6
[]
no_license
yilaguan/pcd
https://github.com/yilaguan/pcd
bac07687df9014f6fe4849c6cd85f714bbe44aff
09a22a3efe43fa6aa1e9782b24ad2ca955ce639c
refs/heads/master
2021-01-17T09:59:06.824211
2014-11-17T13:18:20
2014-11-17T13:18:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Temporal communities """ from . import cmty class TemporalCommunities(object): def __init__(self, tcmtys): self._tcmtys = tcmtys # Basic operatoins def __iter__(self): for t in sorted(self._tcmtys): yield t def __getitem__(self, t): return self._tcmtys[t] def iteritems(self): for t in self: yield t, self[t] # Modification def add_time(self, t, cmtys): assert t not in self._tcmtys self._tcmtys[t] = cmtys # Input @classmethod def from_tcommlist(cls, fname, time_type=float, node_type=str, cmty_type=str): tcmtys = { } f = open(fname) for line in f: line = line.strip() if line.startswith('#'): continue t, n, c = line.split() t = time_type(t) n = time_type(n) c = time_type(c) if t not in tcmtys: cmtys = tcmtys[t] = { } else: cmtys = tcmtys[t] if c not in cmtys: nodeset = cmtys[c] = set() else: nodeset = cmtys[c] nodeset.add(n) self = cls(dict((t, cmty.Communities(cmtynodes)) for t, cmtynodes in tcmtys.iteritems())) return self # Output def write_tcommlist(self, fname): f = open(fname, 'w') for t, cmtys in self.iteritems(): for c, nodes in cmtys.iteritems(): for n in nodes: print >> f, t, n, c
UTF-8
Python
false
false
2,014
1,176,821,046,134
426873253ba3935a6d83b9f17fbaed8db99684f0
38fbd66fe52f6d726d602118e97b796afe7ab4c8
/construct_report.py
5283f566a0da1d7ee4484d3a39abf18be0ca81ba
[]
no_license
fsr/adam
https://github.com/fsr/adam
6be862c0c68c961bdfd577415544595b343bcf2d
1ebcdb3b572eb91c52c7880afffa9ed0e81af86f
refs/heads/master
2021-01-23T22:37:29.923395
2014-08-14T17:00:36
2014-08-14T17:00:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python3 import json import argparse import get_result import create_coding # Constructs a report from a report definition JSON, # a question form definition JSON and an answer database. # Currently reports can only be generated for one specific course. def construct_report(reportdef, questionsdef, answersdef, dbname, coursename): report = [] for definition in reportdef: if definition["type"] != "simple": raise Exception("You need an ifsr gold account to access this feature.") # Type: simple questionname = definition["question"] question = list(filter(lambda q: q["name"] == questionname, questionsdef))[0] questiontype = question["type"] if questiontype == "?": choices = question["answers"] # Retrieve singleresult[1] for questionname_i (i>=1) from DB i = 1 answersums = [] for answer in choices: singleresult = get_result.get_question(dbname, coursename, "{}_{}".format(questionname, i), definition["filter"], 1) answersums.append(singleresult[1]) i += 1 na_answer = 0 else: if questiontype[-1] == "+": questiontype = questiontype[:-1] na_answer = 1 else: na_answer = 0 questionanswerdef_as_list = list(filter(lambda a: a["type"] == questiontype, answersdef)) if len(questionanswerdef_as_list) == 0: raise Exception("Question type '{}' has no answers definition!".format(questiontype)) choices = questionanswerdef_as_list[0]["answers"] # Cut away the first (answer=0 in the CSV is only for meta-questions) # and last (empty answer) element of the list (add later if wanted for something...) answersums = get_result.get_question(dbname, coursename, questionname, definition["filter"], len(choices) + na_answer)[1:-1] # Build renderable from choices and answersums renderable = {"question": question["text"], "view": definition["view"], "comment": definition["comment"], "answers": []} for i in range(len(choices)): renderable["answers"].append({"text": choices[i], "number": answersums[i]}) if na_answer == 1: renderable["answers"].append({"text": "N/A", "number": answersums[-1]}) report.append(renderable) return report if __name__ == '__main__': # CLI argument parsing parser = argparse.ArgumentParser( description="Constructs a report from a report definition JSON, a question form definition JSON and an answer database.") parser.add_argument("-r", "--report", nargs=1, help="report definition JSON", required=True) parser.add_argument("-q", "--questions", nargs=1, help="question form JSON", required=True) parser.add_argument("-a", "--answers", nargs=1, help="answer types JSON", required=True) parser.add_argument("-d", "--database", nargs=1, help="database containing table with the answers...", required=True) parser.add_argument("-c", "--course", nargs=1, help="...for this course to generate the report on", required=True) parser.add_argument("-o", "--output", nargs=1, help="JSON file the report is to be stored in") args = parser.parse_args() with open(args.report[0], 'r') as f: reportdef = json.load(f) with open(args.questions[0], 'r') as f: questionsdef = json.load(f) with open(args.answers[0], 'r') as f: answersdef = json.load(f) report = construct_report(reportdef, questionsdef, answersdef, args.database[0], args.course[0]) report_json = create_coding.prettyprint_json(report) if not args.output: print(report_json) else: with open(args.output[0], 'w') as f: f.write(report_json)
UTF-8
Python
false
false
2,014
2,327,872,313,714
2be8769fb7f63dd8f665dc57735c1a4abdf202b8
ccf491f7b43d288e1ba5bfeb1e12357814832ee8
/week2/homework/A1.py
d6bd94c89b8fa0c3458256193fe07193f307154e
[]
no_license
vsilv/smag
https://github.com/vsilv/smag
4b2cbf8bf568471f1f7c8ccd82d2a025b0ecfe67
7a0449900b9ab42baa370eada02a2684921cc5c4
refs/heads/master
2021-01-15T22:01:25.656072
2014-05-11T17:58:13
2014-05-11T17:58:13
17,087,736
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import random import matplotlib.pyplot as plt import numpy as np def direct_disks_box(N, sigma): overlap = True while overlap == True: L = [(random.uniform(sigma, 1.0 - sigma), random.uniform(sigma, 1.0 - sigma))] for k in range(1, N): a = (random.uniform(sigma, 1.0 - sigma), random.uniform(sigma, 1.0 - sigma)) min_dist_sq = min(((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) for b in L) if min_dist_sq < 4.0 * sigma ** 2: overlap = True break else: overlap = False L.append(a) return L def markov_disks_box(N, sigma,delta, n_steps): overlap = True un = np.random.uniform L = np.zeros([N,2]) L+= [1.0,1.0] while overlap == True: L = np.zeros([N,2]) L+= np.array([un(sigma, 1.0 - sigma), un(sigma, 1.0 - sigma)]) for k in range(1, N): newitem = L[k-1]+np.array([un(-delta, delta), un(-delta, delta)]) #print("lets try",newitem) border = not((newitem>sigma).all() and (newitem<1.0-sigma).all()) min_dist= np.min(np.sum((L[0:k,:]-newitem)**2,1)) if (min_dist < 4.0 * sigma ** 2) or border : overlap = True #print("fail") break else: L[k,:] = newitem overlap = False #print("success") return L def markov_disks_box2(N, sigma,delta, n_steps): overlap = True un = np.random.uniform ch = lambda:np.random.randint(0,4) choices = np.random.randint(0,4,n_steps) L = np.array([[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]]) for step in range(n_steps): a = L[choices[step]] b = a + [un(-delta,delta),un(-delta,delta)] border = ((b>sigma).all() and (b<1.0-sigma).all()) min_dist= np.min(np.sum((L-b)**2,1)) if (min_dist > 4.0 * sigma ** 2) or border : L[choices[step]] = b # time return L N = 4 sigma = 0.1197 n_runs = 1000000 n_steps = 0 delta = 0.1 histo_data = np.zeros([n_runs,N,2]) for run in range(n_runs): histo_data[run,:,:] = direct_disks_box(N, sigma) #print(histo_data[run,:,:]) if run%10000==0: print("%.3f%%"%(run/n_runs*100)) def hist_data(): plt.figure() plt.hist((histo_data[:,:,0].flatten()), bins=100, normed=True) plt.xlabel(r'Position $x$') plt.ylabel(r'frequency') plt.title("Histogram of the x-Position with direct sampling") plt.grid() plt.show() hist_data()
UTF-8
Python
false
false
2,014
13,778,255,129,006
83456a23e8ee57e176ba80a0073cec4e8452f971
98fd5480125bd78ee2b4fe6fc7e29bd756e0d2df
/SLAEx64/Assignment 4/encoder.py
1c3e2764496ab94aeae4fa607bac87f31732d7ab
[]
no_license
doomedraven/SLAE
https://github.com/doomedraven/SLAE
ae93788805223d188959b8d9cdf41b3897dce3c3
11824c52e1e2a2f4d7cb9b2d259e4aca6013c40c
refs/heads/master
2016-09-05T19:08:56.771350
2014-05-27T12:28:06
2014-05-27T12:28:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python from sys import exit from random import randint """ global _start section .text _start: ;execve xor rax, rax push rax mov rbx, 0x68732f2f6e69622f ;/bin//sh in reverse push rbx mov rdi, rsp push rax mov rdx, rsp push rdi mov rsi, rsp mov al, 0x3b syscall 30 bytes unsigned char payload[] =\ "\x48\x31\xc0\x50\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x48\x89\xe7\x50\x48\x89\xe2\x57\x48\x89\xe6\xb0\x3b\x0f\x05" """ def get_random(ident): if ident == 'number': return randint(1,3) elif ident == 'char': return randint(65,122)#only [a-z[]\^_`A-Z] shellcode = ("\x48\x31\xc0\x50\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x48\x89\xe7\x50\x48\x89\xe2\x57\x48\x89\xe6\xb0\x3b\x0f\x05") encoded = "" #end = "\\xf0\\x0d" for x in bytearray(shellcode): encoded += '\\x%02x' % x random = get_random('number') encoded += '\\x%02x' % random for i in range(random-1): encoded += '\\x%02x' % get_random('char') #encoded += end #probably we will need it for correct jump print encoded print print encoded.replace("\\x", ",0x")[1:] print 'Initial len: %d, encoded len: %d' % (len(shellcode), len(encoded)/4)
UTF-8
Python
false
false
2,014
4,784,593,582,643
dc11c350b726a593c82de6673d5f2d8b6675fc54
d486f9334ed2d9c35a5088710f51632fee46135c
/src/redemo/rewho.py
b43ffbb280df293bac3d9437a9c2836e87e08276
[]
no_license
bluescorpio/PyProjs
https://github.com/bluescorpio/PyProjs
9ae1451fc6035c70c97015887fe40947fbe0b56d
7df126ec7930484b4547aaf15fa8c04f08a5ca7e
refs/heads/master
2016-08-01T13:36:51.555589
2014-05-28T14:00:56
2014-05-28T14:00:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#! /usr/bin/env python #coding=utf-8 from os import popen from re import split f = popen("dir", "r") for eachLine in f: print split("\s\s+|t", eachLine.strip()) f.close()
UTF-8
Python
false
false
2,014
9,844,065,078,326
2c260c50c636f2ce83a44c28262bd1a8f32fba73
e0ef04125a21b771f92b806da04dac7c26e61914
/AudioBox/koanSDK/koan/arrowctrl.py
65770b51158f06fef84cb4bb6c005d1519ef3c4b
[]
no_license
cashlalala/AudioBox
https://github.com/cashlalala/AudioBox
7e1c98ec4810f20948454652ddf6e35aedcb336a
a26005a93a1d95d8120cd21b5fd73f0b86b33295
refs/heads/master
2016-08-06T22:14:11.808977
2012-09-26T12:49:51
2012-09-26T12:49:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
######################################################### # # Enumerate Variable # ######################################################### import traceback DMAP = ['UP', 'DOWN', 'LEFT', 'RIGHT', 'TAB'] ######################################################### # # Object Declare # ######################################################### class ArrowControl(object): """ to control when arrow keys(up, down, left, right) pressed, how the focused child compenent change ex: ArrowControl may defined ------------------ | ----- ----- | press right to move focus from A to B | | A | | B | | press down to move focus from B to D | ----- ----- | press left to move focus from D to C | ----- ----- | press up to move focus from C to A | | C | | D | | | ----- ----- | ------------------ ArrowControl save the rules in a map that looks like: {Component1 : {'DOWN': Component2, 'UP' : Component3}, Component2 : {'DOWN': Component3, 'UP' : Component1}, Component3 : {'DOWN': Component1, 'UP' : Component2}} Event: Not Define Arrow : sent when a unhandled arrow key pressed @ivar arrowMap: the mapping rules to change focus """ def __init__(self): self.arrowMap = {} self.bind('Close', self.clearDirmap) def getFocusControl(self): """ get the component that are focused and have a mapping rule @rtype: Component """ return [x for x in self.arrowMap.keys() if x and x.isFocused()] def clearDirmap(self): """ clear arrow map @rtype: None """ self.arrowMap = {} def dirmap(self, comp, **args): """ set direction to next focused child mapping setting that if comp is the focused child, how arrow key change the focus to another child @param comp: the child compenent to set rule @param args: map from arrow key (UP,DOWN,LEFT,RIGHT) to next focused child @rtype: None """ if not comp in self.arrowMap: self.arrowMap[comp] = {} d = self.arrowMap[comp] for e in args.keys(): if e in DMAP: if isinstance(args[e], list): d[e] = args[e] else: d[e] = [args[e]] def clear(self): """ clear the map rules @rtype: None """ self.arrowMap = {} def trigger(self, focusedComps, dir): """ trigger to change focused child @param focusedComps: the component that are focused now @param dir: the arrow key pressed, one of (UP, DOWN, LEFT, RIGHT) @return: if the focused component if changed @rtype: boolean """ for c in focusedComps: if self.__trigger(c, dir): return True return False def __trigger(self, focusedComp, dir): # skip invisible components # avoid looping if not focusedComp: self.invoke('Not Define Arrow', dir) return False wont = [] focusedComps = [focusedComp] # Example: # # (0) enabled # (X) disabled # # a(O)->b(X)->d(X) # ->c(X)->e(O) # # Right from a, e is focused while True: nextComps2 = [] for focusedComp in focusedComps: try: d = self.arrowMap[focusedComp] nexts = d[dir] except KeyError: #print 'Component not define this arrow' self.invoke('Not Define Arrow', dir) return False else: for next in nexts: if next: if next in wont: # recursive circle, damm break if next.enabled and next.visible: next.setFocus(dir) return True else: nextComps2.append(next) wont.append(focusedComp) if not nextComps2: break focusedComps = nextComps2 return False def setCommandProperty(self, prop, **keyword): name = prop['name'] if name.lower() == 'dirmap': try: attrs = prop['attrs'] alias = prop['alias'] source = None if 'from' in attrs.getQNames(): fr = attrs.getValueByQName('from') try: try: source = self.getPathObject(fr.split('.'), prop['root']) except: source = alias[fr] except: print "[KXML] dirmap@from: no such control %s !!!" % fr else: print "[KXML] dirmap: expected 'from' tag !!!" parm = {} for d in attrs.getQNames(): if d.upper() in ['LEFT', 'RIGHT', 'UP', 'DOWN']: lst = attrs.getValueByQName(d).split(',') d = str(d.upper()) for x in lst: x = x.strip() tar = None try: try: target = self.getPathObject(x.split('.'), prop['root']) except: target = alias[x] except: print "[KXML] dirmap@%s: no such control %s !!!" %(d, x) if target: if d not in parm: parm[d] = [] parm[d].append(target) if source: self.dirmap(source, **parm) pass except: traceback.print_exc() print '[arrowctrl] setCommandProperty !!!'
UTF-8
Python
false
false
2,012
14,886,356,692,881
8bdf8efef2c70238017c53df1e143083190efaab
091f4299cb20801e6068118f4bfbfa9bb5d37581
/palantir/bldg_to_coords.py
b168eb64b506c4dd662679718cdd494d9ea45a74
[]
no_license
rmferrer/interviews
https://github.com/rmferrer/interviews
d4acb3076f77fd660065d8acdba96ee15dc259d0
c9e31e468811b068a7e4adc77af0d4c9e00caeb3
refs/heads/master
2019-07-12T18:36:30.244821
2012-12-05T19:59:27
2012-12-05T19:59:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys from helpers import * def write_building_coords (buildings, outfilename): coords = [] for building in buildings: bottomLeft = bottom_left_corner (building) bottomRight = bottom_right_corner (building) topLeft = top_left_corner (building) topRight = top_right_corner (building) coords.append (bottomLeft) coords.append (bottomRight) coords.append (topLeft) coords.append (topRight) coords.sort () f = open (outfilename, 'w') line0 = "0 0\n" f.write (line0) for coord in coords: line = str (coord[0]) + " " + str (coord[1]) + "\n" f.write (line) f.close () def main (args): if len (args) != 2: print "Usage: python bldgs_to_coords.py input.buildings" sys.exit () infilename = args[1] filename = infilename[:-10] outfilename = filename + ".coords" buildings = read_buildings (infilename) write_building_coords (buildings, outfilename) if __name__ == '__main__': main (sys.argv)
UTF-8
Python
false
false
2,012
11,209,864,681,191
e9d39a03281972106fbfb678abfa03be485f5f8d
b5c0a9e42760d18ae614eb67c2d8be5a70aa961b
/python/flask_tutorial/app.py
0b110ceb5916e0e64acac43a5fe5cef842f52be9
[]
no_license
junyu-w/sample-projects
https://github.com/junyu-w/sample-projects
9845b2ca9eafcb715cf1db9fd88aab4a9e8364c5
b15c96f31e270b7d268e7061a3d421419496478d
refs/heads/master
2022-12-21T23:42:24.469990
2014-03-19T07:31:23
2014-03-19T07:31:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#import Flask functions from flask import Flask, render_template from random import randint #create Flask application app = Flask(__name__) #index() will be run when '/' is requested @app.route('/') def index(): #data returned to browser return 'Yay first web app!' @app.route('/random_example') def random_example(): return render_template('random.html', random_num=randint(1, 100)) #start the Flask server which listens to requests app.run(debug=True)
UTF-8
Python
false
false
2,014
6,923,487,286,809
2d756eb1a102cc474afb62f57d517f8621df42da
63649f8f98045c5aec45e62f9fac53bf6aa3d8ff
/session.py
f8948acee3da5ec315bb9eba4e11c1d3d0af3a31
[]
no_license
sandinmyjoints/requests-review
https://github.com/sandinmyjoints/requests-review
78494b47e2fc7901071efc6d3d7060ef4ceb4cf6
5a1e9689a27006f31b0aff2c1607f39155366a67
refs/heads/master
2021-01-23T17:19:48.501040
2012-12-18T02:36:50
2012-12-18T02:36:50
6,169,062
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import json import requests from oauth_hook import OAuthHook from urlparse import parse_qs from local.goodreads import GOODREADS_KEY, GOODREADS_SECRET """ What I want to do: Retrieve an author. Write a review. """ url = GOODREADS = "http://www.goodreads.com" request_token_url = '%s/oauth/request_token' % url authorize_url = '%s/oauth/authorize/' % url access_token_url = '%s/oauth/access_token/' % url OAuthHook.consumer_key = GOODREADS_KEY OAuthHook.consumer_secret = GOODREADS_SECRET oauth_hook = OAuthHook(consumer_key=GOODREADS_KEY, consumer_secret=GOODREADS_SECRET) print "calling hook", oauth_hook.consumer_key, oauth_hook.consumer_secret response = requests.get(request_token_url, hooks={'pre_request': oauth_hook}) print "response", response, response.text qs = parse_qs(response.text) oauth_token = qs['oauth_token'][0] oauth_secret = qs['oauth_token_secret'][0] authorize_link = '%s?oauth_token=%s' % (authorize_url, oauth_token) print authorize_link accepted = 'n' while accepted.lower() == 'n': # you need to access the authorize_link via a browser, # and proceed to manually authorize the consumer accepted = raw_input('Have you authorized me? (y/n) ') def login(host, url, user): session = requests.Session() credentials = { "email": user['email'], "password": user['password'] } return session.post(host+url, data=credentials) if res.status_code == 200: log.info("Logged in.") else: log.warning("Received status %d", res.status_code) return session def get(ses, path, server=url): res = ses.get(server+path) print res return res, json.loads(res.content)
UTF-8
Python
false
false
2,012
1,812,476,229,998
66572715595be52c4417652bf87bfd9dc18e02c2
b1f2d582eb063cfd87e05b86bb612a2f630c417a
/smbus/regutils.py
db2e3ead9fc2b022dca55fa079db3088cdc696d3
[]
no_license
tcliu01/py_gpib_drivers
https://github.com/tcliu01/py_gpib_drivers
a2502e1378e10540a343c31562bb164051060b32
c8ff8d9708fe6c9360cff9c33e6869c775981097
refs/heads/master
2021-01-01T16:51:20.054104
2013-10-24T19:13:46
2013-10-24T19:13:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import re class regutils: def __init__(self, bus, slave_addr, regmap_path): self.bus = bus self.slave_addr = slave_addr self.registers = dict() self.bitfields = dict() f = open(regmap_path, 'r') lines = f.readlines() for line in lines: lst = line.split(',') addr = int(lst[4], 16) name = lst[5] if name in self.registers: print 'Error! Duplicate register name: ' + name return else: self.registers[name] = addr bits = lst[11:19] for i in range(8): match = re.match('(.+?)\[([0-9]+):([0-9]+)\]', bits[i]) if match: bitname = match.group(1) high = int(match.group(2)) low = int(match.group(3)) width = high - low + 1 self.bitfields[bitname] = (name, (7 - i) - (width - 1), width) elif len(bits[i]) > 0: self.bitfields[bits[i]] = (name, 7 - i, 1) @staticmethod def read_modify_write_byte(bus, addr, reg, offs, width, newval): val = bus.read_byte_data(addr, reg) modval = regutils.set_value(val, offs, width, newval) bus.write_byte_data(addr, reg, modval) @staticmethod def read_modify_write_byte_16b(bus, addr, reg, offs, width, newval): val = bus.read_byte_data_16b(addr, reg) modval = regutils.set_value(val, offs, width, newval) bus.write_byte_data_16b(addr, reg, modval) def read_register_16b(self, register_name): if register_name in self.registers: return bus.read_byte_data_16b(self.slave_addr, self.registers[register_name]) else: print 'Error! No register with name: ' + register_name def write_register_16b(self, register_name, value): if register_name in self.registers: return bus.write_byte_data_16b(self.slave_addr, self.registers[register_name], value) else: print 'Error! No register with name: ' + register_name def read_bitfield_16b(self, bitfield_name): if bitfield_name in self.bitfields: (name, offs, width) = self.bitfields[bitfield_name] data = self.read_register_16b(name) mask = (1 << width) - 1 data &= mask << offs data >>= offs return data else: print 'Error! No register with name: ' + register_name def read_modify_write_bitfield_16b(self, bitfield_name, value): if bitfield_name in self.bitfields: (name, offs, width) = self.bitfields[bitfield_name] regutils.read_modify_write_byte_16b(self.bus, self.slave_addr, self.registers[name], offs, width, value) else: print 'Error! No bitfield with name: ' + bitfield_name @staticmethod def set_value(val, offs, width, newval): mask = (1 << width) - 1 val &= ~(mask << offs) val |= (newval & mask) << offs return val # for Raspberry pi @staticmethod def get_i2c_bus(): f = open('/proc/cpuinfo', 'r') for l in f.readlines(): match = re.match('Revision\t:\s1?0+([0-9a-f])', l) if match: rev = int(match.group(1), 16) if rev >= 0x2 and rev <= 0x3: return 0 elif rev >= 0x4 and rev <= 0xf: return 1 else: return -1 return -1
UTF-8
Python
false
false
2,013
11,553,462,056,607
0817a4deef8f65b5de9260d5b565646563bcfbf8
29c102a66f7f626dc30a2bb5e0aa3fdef8515334
/members/urls.py
5bcefff137d1554ed26c52ac138953ffc4f0a7af
[ "MIT" ]
permissive
cseslam/msar_django
https://github.com/cseslam/msar_django
fc7a98c8df4f0b2681fd2eaed35f8be578d4fa09
476634a1b1936941395c2a12ed32965258eba657
refs/heads/master
2016-03-23T02:48:23.796773
2013-11-12T01:49:02
2013-11-12T01:49:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, url from members import views urlpatterns = patterns('', url(r'^(?P<username>[a-zA-Z0-9_])/$', views.view, name='view'), url(r'^edit/$', views.edit, name='edit'), url(r'^list/$', views.list, name='list'), url(r'^login/$', views.login, name='login'), url(r'^signup/$', views.signup, name='signup'), url(r'^logout/$', views.logout, name="logout"), )
UTF-8
Python
false
false
2,013
1,382,979,504,854
0e1bb91b89dae9f422255dcdc8024a8a3dd828bd
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_5/stpnic006/question1.py
9388d1699141f683fce001ba7a28b860dddc3495
[]
no_license
MrHamdulay/csc3-capstone
https://github.com/MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Nicholas Stephenson Bulletin Board Systems (BBS) 15 April""" print("Welcome to UCT BBS \nMENU \n(E)nter a message \n(V)iew Message \n(L)ist files \n(D)isplay file \ne(X)it") #Menue provided by I/O mes = "no message yet" #Create Variable US = input("Enter your selection:\n") #User Selelction if US == "x" or US == "X": print("Goodbye!") #Terminate BBS if x while (US != "x" and US != "X") : if US == "e" or US == "E": mes = input ("Enter the message:\n") #User Enters new Message, option E if US == "v" or US == "V": print("The message is:", mes) #Shows Mes, option V if US == "L" or US == "l": print("List of files: 42.txt, 1015.txt") #List 2 given files, option L if US == "D" or US == "d": USF = input("Enter the filename:\n") #User Selection File, D if USF == "42.txt": print("The menaing of life is blah blah blah ...") elif USF =="1015.txt": print("Computer Science class notes ... simplified \nDo all work \nPass Course \nBe happy") else: print("File not found") #Options of 42- or 1015.txt print("Welcome to UCT BBS \nMENU \n(E)nter a message \n(V)iew Message \n(L)ist files \n(D)isplay file \ne(X)it") #Menue provided by I/O US = input("Enter your selection:\n") #User Selelction if US == "x" or US == "X": print("Goodbye!") #Terminate BBS if x
UTF-8
Python
false
false
2,014
16,552,803,978,652
1797c7d9873a6127e4172d3277b2ecccf6fc19c0
285fa94da51a4703b03b86e6ba0e75ebec8430b4
/vgstation13/tools/DMITool/DMI/__init__.py
d73904ea899d4c809fd6d09b4c22ff84aab5c5ca
[ "GPL-3.0-or-later", "GPL-3.0-only" ]
non_permissive
bandw2/JLawrence_Work
https://github.com/bandw2/JLawrence_Work
61324b9ef6c416fddbcdaaee38b642a33c5eb383
f9ae3d748e3ad7c2f22e6863156f78bc98ba3306
refs/heads/master
2020-06-06T04:09:33.236046
2014-02-05T01:41:07
2014-02-05T01:41:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys, os, glob, string, traceback, fnmatch, math from PIL import Image, PngImagePlugin from .State import State from DMIH import * class DMI: version = '' states = {} iw = 32 ih = 32 filename = '' pixels = None size = () statelist = '' max_x = -1 max_y = -1 def __init__(self, file): self.filename = file self.version = '' self.states = {} self.iw = 32 self.ih = 32 self.pixels = None self.size = () self.statelist = 'LOLNONE' self.max_x = -1 self.max_y = -1 def make(self, makefile): print('>>> Compiling %s -> %s' % (makefile, self.filename)) h = DMIH() h.parse(makefile) for node in h.tokens: if type(node) is Variable: if node.name == 'height': self.ih=node.value elif node.name == 'weight': self.iw=node.value elif type(node) is directives.State: self.states[node.state.name]=node.state elif type(node) is directives.Import: if node.ftype=='dmi': dmi = DMI(node.filedef) dmi.extractTo("_tmp/"+os.path.basename(node.filedef)) for name in dmi.states: self.states[name]=dmi.states[name] def save(self,to): # Now build the manifest manifest='version = 4.0' manifest += '\r\n width = {0}'.format(self.iw) manifest += '\r\n height = {0}'.format(self.ih) frames = [] # Sort by name because I'm autistic like that. for name in sorted(self.states): manifest += self.states[name].genManifest() frames += self.states[name].icons #Next bit borrowed from DMIDE. icons_per_row = math.ceil(math.sqrt(len(frames))) rows=icons_per_row if len(frames) > icons_per_row*rows: rows+=1 map = Image.new('RGBA',(icons_per_row*self.iw,rows*self.ih)) x=0 y=0 for frame in frames: #print(frame) icon = Image.open(frame,'r') map.paste(icon,(x*self.iw,y*self.ih)) x+=1 if x > icons_per_row: y+=1 x=0 # More borrowed from DMIDE: # undocumented class meta = PngImagePlugin.PngInfo() # copy metadata into new object reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') for k,v in map.info.items(): if k in reserved: continue meta.add_text(k, v, 1) # Only need one - Rob meta.add_text(b'Description',manifest.encode('ascii'),1) # and save map.save(to, 'PNG', pnginfo=meta) print('>>> {0} states saved to {1}'.format(len(frames),to)) def getDMIH(self): o = '# DMI Header 1.0 - Generated by DMI.py' o += self.genDMIHLine('width', self.iw, -1) o += self.genDMIHLine('height', self.ih, -1) for s in sorted(self.states): o += self.states[s].genDMIH() return o def genDMIHLine(self,name,value,default): if value != default: if type(value) is list: value = ','.join(value) return '\n{0} = {1}'.format(name,value) return '' def extractTo(self, dest, suppress_post_process=False): print('>>> Extracting %s...' % self.filename) self.read(dest,suppress_post_process) def parse(self, dest=None, suppress_post_process=True): if dest is None: suppress_post_process=True img = Image.open(self.filename) self.size = img.size # print(repr(img.info)) if(b'Description' not in img.info): raise Exception("DMI Description is not in the information headers!") self.pixels = img.load() desc = img.info[b'Description'].decode('ascii') """ version = 4.0 width = 32 height = 32 state = "fire" dirs = 4 frames = 1 state = "fire2" dirs = 1 frames = 1 state = "void" dirs = 4 frames = 4 delay = 2,2,2,2 state = "void2" dirs = 1 frames = 4 delay = 2,2,2,2 """ state = None x = 0 y = 0 self.statelist = desc ii = 0 for line in desc.split("\n"): line = line.strip() if line.startswith("#"): continue if '=' in line: (key, value) = line.split(' = ') key = key.strip() value = value.strip().replace('"', '') if key == 'version': self.version = value elif key == 'width': self.iw = int(value) self.max_x = img.size[0] / self.iw elif key == 'height': self.ih = int(value) self.max_y = img.size[1] / self.ih #print(('%s: {sz: %s,h: %d, w: %d, m_x: %d, m_y: %d}'%(self.filename,repr(img.size),self.ih,self.iw,self.max_x,self.max_y))) elif key == 'state': if state != None: # print(" + %s" % (state.ToString())) if(self.iw == 0 or self.ih == 0): if(len(self.states) > 0): raise SystemError("Width and height for each cell are not available.") else: self.iw = img.size[0] self.max_x = 1 self.ih = img.size[1] self.max_y = 1 elif(self.max_x == -1 or self.max_y == -1): self.max_x = img.size[0] / self.iw self.max_y = img.size[1] / self.iw for i in range(state.numIcons()): icon = self.extractNextIcon(state, img, dest, x, y, i) state.icons += [icon] x += 1 #print('%s[%d:%d] x=%d, max_x=%d' % (self.filename,ii,i,x,self.max_x)) if(x >= self.max_x): x = 0 y += 1 self.states[state.name] = state if not suppress_post_process: self.states[state.name].postProcess() ii += 1 state = State(value) elif key == 'dirs': state.dirs = int(value) elif key == 'frames': state.frames = int(value) elif key == 'loop': state.loop = int(value) elif key == 'rewind': state.rewind = int(value) elif key == 'movement': state.movement = int(value) elif key == 'delay': state.delay = value.split(',') elif key == 'hotspot': state.hotspot = value else: print('Unknown key ' + key + ' (value=' + value + ')!') sys.exit() self.states[state.name] = state for i in range(state.numIcons()): self.states[state.name].icons += [self.extractNextIcon(state, img, dest, x, y, i)] x += 1 #print('%s[%d:%d] x=%d, max_x=%d' % (self.filename,ii,i,x,self.max_x)) if(x >= self.max_x): x = 0 y += 1 if not suppress_post_process: self.states[state.name].postProcess() if dest is not None: outfolder = os.path.join(dest, os.path.basename(self.filename)) nfn = self.filename.replace('.dmi','.dmih') valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits) nfn = ''.join(c for c in nfn if c in valid_chars) nfn = os.path.join(outfolder, nfn) with open(nfn,'w') as dmih: dmih.write(self.getDMIH()) print(' DONE! Extracted %d icon states.' % ii) def extractNextIcon(self, state, img, dest, sx, sy, i): if(self.iw == 0 or self.ih == 0): print('--STATES:--') print(self.statelist) raise SystemError("Invalid state: " + state.ToString()) # print(" X (%d,%d)"%(sx*self.iw,sy*self.ih)) if dest is None: return None icon = Image.new(img.mode, (self.iw, self.ih)) newpix = icon.load() # max_x = 0 for y in range(self.ih): for x in range(self.iw): _x = x + (sx * self.iw) _y = y + (sy * self.ih) # if(_x>=self.iw or _y>=self.ih): # continue # if(_x<0 or _y<0): # continue try: newpix[x, y] = self.pixels[_x, _y] except IndexError as e: print("!!! Received IndexError in %s <%d,%d> = <%d,%d> + (<%d,%d> * <%d,%d>), max=<%d,%d> halting." % (self.filename, _x, _y, x, y, sx, sy, self.iw, self.ih, self.max_x, self.max_y)) print('%s: {sz: %s,h: %d, w: %d, m_x: %d, m_y: %d}' % (self.filename, repr(img.size), self.ih, self.iw, self.max_x, self.max_y)) print('# of cells: %d' % len(self.states)) print('Image h/w: %s' % repr(self.size)) print('State: ' + state.ToString()) print('--STATES:--') print(self.statelist) sys.exit(1) outfolder = os.path.join(dest, os.path.basename(self.filename)) if not os.path.isdir(outfolder): print('\tMKDIR ' + outfolder) os.makedirs(outfolder) nfn = state.name + "[%d].png" % i valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits) nfn = ''.join(c for c in nfn if c in valid_chars) nfn = os.path.join(outfolder, nfn) if os.path.isfile(nfn): os.remove(nfn) try: icon.save(nfn) except SystemError as e: print("Received SystemError, halting: %s" % traceback.format_exc(e)) print('{ih=%d,iw=%d,state=%s,dest=%s,sx=%d,sy=%d,i=%d}' % (self.ih, self.iw, state.ToString(), dest, sx, sy, i)) sys.exit(1) return nfn
UTF-8
Python
false
false
2,014
1,262,720,389,877
deec513f2995e2d1c1bd01a97ecac38b972b0c9f
922e63e73c5fcd098c34be7a93f781390666d683
/posts/urls.py
b64518ed6d3e801a896a5a2b2972fab08aac805c
[]
no_license
OckhamsRazor/NM_Final_Web
https://github.com/OckhamsRazor/NM_Final_Web
3f1abf071ba6f58254d65d4016a723d65d5b470e
53e8f4ae591137a4afd83de681e68a30e4d2fe1e
refs/heads/master
2020-05-05T10:29:30.972707
2014-01-11T19:05:34
2014-01-11T19:05:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import patterns, url from posts import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^create/$', views.create, name='create'), url(r'^update/$', views.update, name='update'), url(r'^destroy/$', views.destroy, name='destroy'), #url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'), #url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'), #url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote') )
UTF-8
Python
false
false
2,014
4,148,938,451,244
7c5e6e5f22a818358cc3bb7eb4ad77cbfead1bd3
d4c0b7fd40ddd8be34cb092cb7fd173f381dba65
/ExclusiveDijetsAnalysis/test/PF2PAT_ForwardTTreeAnalysis_cfg_ak5jets.py
6a80717e96de4cbc1d1ad52f48a796a113f45ee7
[]
no_license
ForwardGroupBrazil/ForwardAnalysis
https://github.com/ForwardGroupBrazil/ForwardAnalysis
8dceaacb1707c0769296f3c7b2e37c15a4a30ff7
5572335f19d1e0d385f73945e55e42fb4ed49761
refs/heads/master
2021-01-16T01:02:02.286181
2013-09-12T20:54:02
2013-09-12T20:54:02
12,787,581
1
4
null
null
null
null
null
null
null
null
null
null
null
null
null
import FWCore.ParameterSet.Config as cms # Settings class config: pass config.verbose = True config.writeEdmOutput = False config.runOnMC = False config.globalTagNameData = 'GR_R_42_V19::All' #JECDATA config.globalTagNameMC = '' #config.outputEdmFile = 'DijetsAnalysis.root' config.outputTTreeFile = 'DijetsanalysisDATA42X_PATTTree.root' config.comEnergy = 7000.0 config.trackAnalyzerName = 'trackHistoAnalyzer' #config.trackTagName = 'selectGoodTracks' config.trackTagName = 'analysisTracks' #config.generator = 'Pythia6' config.varyAttributes = True config.runOfflineOnly = True config.runNoColl = False config.runBPTX = False config.runHCALFilter = False #----------------------------------------------------------------------------- config.UsePAT = True #------------------------------------------------------------------------------ process = cms.Process("Analysis") process.load('FWCore.MessageService.MessageLogger_cfi') process.MessageLogger.cerr.threshold = 'INFO' process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True), SkipEvent = cms.untracked.vstring('ProductNotFound') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( 'file:/storage2/sfonseca/CMSSW/Forward/CMSSW_4_2_8/src/ForwardAnalysis/Skimming/test/patTuple_PF2PAT.root' ) ) #------------------------------------------------------------------------------- # Import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('Configuration.StandardSequences.GeometryExtended_cff') process.load('Configuration.StandardSequences.MagneticField_38T_cff') process.load('Configuration.StandardSequences.Reconstruction_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.load('JetMETCorrections.Configuration.DefaultJEC_cff') #process.load("CondCore.DBCommon.CondDBCommon_cfi") process.options.wantSummary = True #-------------------------------------------------------------------------------- if config.runOnMC: process.GlobalTag.globaltag = config.globalTagNameMC else: process.GlobalTag.globaltag = config.globalTagNameData #--------------------------------------------------------------------------------- ##Jet Correction Service process.ak5CaloL1Offset.useCondDB = False process.ak5PFL1Offset.useCondDB = False process.ak5JPTL1Offset.useCondDB = False #--------------------------------------------------------------------------------- # Output process.TFileService = cms.Service("TFileService", fileName = cms.string(config.outputTTreeFile)) ################################################################### # Analysis modules #-------------------------------- from ForwardAnalysis.Utilities.countsAnalyzer_cfi import countsAnalyzer process.load("ForwardAnalysis.ForwardTTreeAnalysis.exclusiveDijetsAnalysisSequences_cff") #process.load("ForwardAnalysis.ForwardTTreeAnalysis.singleVertexFilter_cfi") process.load('ForwardAnalysis.ForwardTTreeAnalysis.exclusiveDijetsTTreeAnalysis_cfi') #process.exclusiveDijetsTTreeAnalysis.TriggerResultsTag = cms.InputTag("TriggerResults::HLT") process.exclusiveDijetsTTreeAnalysis.EBeam = config.comEnergy/2. process.exclusiveDijetsTTreeAnalysis.TrackTag = config.trackTagName process.exclusiveDijetsTTreeAnalysis.ParticleFlowTag = "pfCandidateNoiseThresholds" #process.exclusiveDijetsTTreeAnalysisPFNoiseThresholds = process.exclusiveDijetsTTreeAnalysis.clone(ParticleFlowTag = "pfCandidateNoiseThresholds") process.analysis_reco_step = cms.Path(process.analysisSequences) process.analysis_exclusiveDijetsAnalysis_step = cms.Path(process.eventSelectionHLT+ process.exclusiveDijetsTTreeAnalysis)
UTF-8
Python
false
false
2,013
11,519,102,306,397
e5bbcc0d8d711c9f05336d5ce92bbf3c1e71d88c
c4df4bf3c304280a7943a5c45976f2c85b440d89
/crear_anuncio.py
6c2f8c0e1015b68df6096f2127fa3ef4d2d56b37
[]
no_license
ShagoMD/servidorPGPY
https://github.com/ShagoMD/servidorPGPY
8e5830058befe2d0bf0cd7a1128978833acd5cf5
5db81484319295a3a7d81ff03b8df8878ab3aaa9
refs/heads/master
2021-01-15T22:41:14.649227
2013-04-20T22:54:40
2013-04-20T22:54:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/python import os os.chdir("C:/Users/Eric/Favorites/Documents/Eclipse Projects/servidorPGPY") os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from publicidadGeolocalizada.models import * from django.contrib.auth.models import User #from django.db import transaction #transaction.rollback() from django.db import connection connection._rollback() pdi = PuntoDeInteres.objects.get(id__exact=2) a1 = Anuncio() a1.anunciante = pdi a1.titulo = 'Vacunas gratis' a1.descripcion = 'Hoy ultimo día' a1.rutaImagen = '/servicioMedico/vacunas' a1.save()
ISO-8859-1
Python
false
false
2,013
16,887,811,409,672
65dc7171b5563e24193a3c2b0e684424dd46ccb4
7b15b238a99585fa7b7dad27da649d21501a270b
/dbReports/iondb/rundb/chips.py
9b527e2fb2dc9b199913f2d99549e574f3644788
[ "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
gourneau/TS
https://github.com/gourneau/TS
0686e9dc046ffa1d932565f8bf33b0ec373d1fe9
5b58de4cc5dea0179d792d69fe32d1dca0fcb192
refs/heads/master
2021-01-24T03:36:26.910996
2012-12-21T19:53:54
2012-12-21T19:53:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved import sys import os import tarfile from django import http, shortcuts, template from iondb.rundb import models import fnmatch import string import commands '''tf = tarfile.open(path) ti = tf.extract('InitLog.txt', path='/tmp/tempLog/') f.write('%s'%open('/tmp/tempLog/InitLog.txt', 'r').readlines())''' def showpage(request): site_name = models.GlobalConfig.objects.all().order_by('id')[0].site_name #TODO: search all File Servers for a "Chips" directory fileservers = models.FileServer.objects.all() files = {} locList = [] for server in fileservers: directory = os.path.join(server.filesPrefix,'Chips') if os.path.isdir(directory): files[server.name] = [] listoffiles = os.listdir(directory) listoffiles.sort() listoffiles.reverse() for file in listoffiles: if (fnmatch.fnmatch(file, "*AutoPHFail*") or fnmatch.fnmatch(file, "*AutoPHPass*")) and not fnmatch.fnmatch(file, '*.zip'): fileLoc = string.split(file, '_')[0] if not [fileLoc, server.name] in locList: locList.append([fileLoc, server.name]) tf = tarfile.open('%s/%s'%(directory, file)) ti = tf.extract('InitLog.txt', path='/tmp/tempLogChips/') logLines = [] for line in open('/tmp/tempLogChips/InitLog.txt', 'r').readlines(): logLines.append(line) output = commands.getstatusoutput('rm -rf /tmp/tempLogChips') if fnmatch.fnmatch(file, "*AutoPHFail*"): passVar = 'F' elif fnmatch.fnmatch(file, "*AutoPHPass*"): passVar = 'T' files[server.name].append([string.split(file, '.')[0], fileLoc, '%s/%s'%(directory, file), logLines, passVar]) elif fnmatch.fnmatch(file, "*AutoPHPass*") and not fnmatch.fnmatch(file, '*.zip'): #create list of files that passed. pass ctxd = { "error_state":0, "locations_list":locList, "base_site_name": site_name, "files":files, } ctx = template.RequestContext(request, ctxd) return shortcuts.render_to_response("rundb/ion_chips.html", context_instance=ctx)
UTF-8
Python
false
false
2,012
4,355,096,853,128
be43aecb3671322137cb585f8c30cb74f369dc88
b2743361fcb962b86223d53ee33c095f51862782
/lottery.py
e9d65f13afba50ce4aadd3940f44e24cce1317e5
[]
no_license
dennis2030/CSIELottery
https://github.com/dennis2030/CSIELottery
94b109451a0eb97c78c08f8fb008f83a48fc785c
172e57b4ea89f40290c5eeb0723f99c7b6adaa5b
refs/heads/master
2021-01-23T13:22:53.476373
2014-10-15T14:47:45
2014-10-15T14:47:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from random import randint def __main__(): f = open('./lottery.list') name_list = f.readlines() winnerSet = set() while( len(winnerSet) < 2): winnerSet.add(randint(0,4)) result = 'The winner is ' for index in winnerSet: result += name_list[index].strip() + ' ' print result if __name__ == '__main__': __main__()
UTF-8
Python
false
false
2,014
12,833,362,318,383
d7ef799e5de839c7a6917f671d08b36826283db7
341755c189b9834ed89d9c6b24a2c6513b17fcff
/scripts/getGitIssueText.py
d510ab617d958d95478a50ebb73e028c480e604b
[]
no_license
petertsehsun/gitAndJiraCrawler
https://github.com/petertsehsun/gitAndJiraCrawler
2c73c518b67c88d7739a0abe72faac14a85ce360
daac004f50fe494def911959c7164f09beb1addb
refs/heads/master
2021-01-23T13:31:42.303462
2014-07-25T18:41:01
2014-07-25T18:41:01
6,742,095
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys import json import subprocess import argparse #curl -s -d- -X GET -H "Content-Type: application/json" https://issues.apache.org/jira/rest/api/latest/issue/COCOON-833 query = 'curl -s -d- -X GET -H "Content-Type: application/json" https://issues.apache.org/jira/rest/api/latest/issue/%s' parser = argparse.ArgumentParser(description="Input parameters for separating the log") parser.add_argument('--out', help='output file name', type=str, required=True) parser.add_argument('--dat', help='input dormant bug file name', type=str, required=True) args = parser.parse_args() KEY = 0 DORMANT = 13 RESOLUTION = 4 def sendQuery(key): queryResult = subprocess.Popen(query % (key), stdout=subprocess.PIPE, shell=True).communicate()[0] try: jsonData = json.loads(queryResult) except ValueError: print 'error', key data = jsonData['fields'] description = "" comments = "" if 'description' in data: if data['description'] != None: description += data['description'] if 'comment' in data: commentData = data['comment'] if 'comments' in commentData: for c in commentData['comments']: comments += c['body'] #if 'body' in commentData: # print c['body'] comments = comments.replace('\n', ' ') description = description.replace('\n', ' ') return (comments, description) dormant = open(args.out+'.dormant' , 'wb') nondormant = open(args.out+'.nondormant' , 'wb') for line in open(args.dat, 'r'): line = line.strip() issueInfo = line.split(';') if issueInfo[DORMANT] == '?': continue if issueInfo[RESOLUTION] != 'Fixed': continue (comments, description) = sendQuery(issueInfo[KEY]) result = issueInfo[KEY] + "|||||" + issueInfo[DORMANT] + "|||||" + description.encode('utf-8').strip() + "|||||" + comments.encode('utf-8').strip() if issueInfo[DORMANT] == 'True': dormant.write(result+'\n') else: nondormant.write(result+'\n') #sendQuery("COCOON-883")
UTF-8
Python
false
false
2,014
6,871,947,676,409
97e62e2a4c23650da64f019d912a08f42af4d706
c52bbbaeba6b3100bbf1735a3fb946da7c8d2d95
/module/web/tornado/template_sample.py
bf4c025c10ef8717e523ef11ef24327e70d8ce38
[]
no_license
duyamin/vyplout
https://github.com/duyamin/vyplout
133e04c0ad67850c6baac16d6c4ad5f9ca211f49
28de34461d9f1dec7d0afc876ab3b288ea4a7960
refs/heads/master
2021-01-22T13:46:56.621043
2011-03-25T04:44:45
2011-03-25T04:44:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on 2011-3-24 @author: liliren ''' import tornado.httpserver import tornado.ioloop import tornado.web # define one "add" customization funcation which will be used in the assigned template file. def add(x, y): return (x+y) class MainHandler(tornado.web.RequestHandler): def get(self): items = ["item1","item2","item3"] # render the corresponding template file, and pass the "**args" to the assigned template # not only we can pass the realted parameters, but also can pass the related functions. # so extendible and powerful! :) self.render("templates/template_test.html", items=items, add=add) application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8081) tornado.ioloop.IOLoop.instance().start()
UTF-8
Python
false
false
2,011
1,417,339,235,090
16c54b0101b8c00824195f89376e2dd783e481ce
7d79f61319fe82cc9490d505354e572fb8972b0b
/code/audio/fileRetrieval.py
d0a8790fe2c045bdcfc1b7b520e42226f7a59422
[]
no_license
Horsetooth/MusicUnderstanding
https://github.com/Horsetooth/MusicUnderstanding
ab6784fff0e9ad1816e7b2394d3defbb817c1779
0aa069eb20bcb45c4b0da113632c06e94b9ba6b2
refs/heads/master
2016-08-05T12:06:35.960581
2013-07-25T17:11:25
2013-07-25T17:11:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
''' Created on Jul 5, 2013 @author: thambu ''' ## 7 July, 2013 [Karthik] ## Possible dormant bugs and optimizations: ## 1) Check for file extensions before reading the file. ## 2) While generating file path use direc instead of g.__str__(). ## 3) getSubset method could be implemented more efficiently. ## 4) In the filter method swap the two for loops for a more optimal imrpovement ## 5) Current implementation reads all the filnames in populateSet() and then slects the required ones in filter(), #### this could possibly be combined for scalability. import os class enumGenre(): BLUES=0 ROCK=1 CLASSICAL=2 COUNTRY=3 DISCO=4 HIPHOP=5 JAZZ=6 METAL=7 POP=8 REGGAE=9 def __init__(self, Type): self.value = Type def __str__(self): if self.value == enumGenre.BLUES: return 'blues' if self.value == enumGenre.CLASSICAL: return 'classical' if self.value == enumGenre.COUNTRY: return 'country' if self.value == enumGenre.DISCO: return 'disco' if self.value == enumGenre.HIPHOP: return 'hiphop' if self.value == enumGenre.JAZZ: return 'jazz' if self.value == enumGenre.METAL: return 'metal' if self.value == enumGenre.POP: return 'pop' if self.value == enumGenre.REGGAE: return 'reggae' if self.value == enumGenre.ROCK: return 'rock' @staticmethod def __enumSet__(): genreSet=[] for i in range(0,10): genreSet.append(enumGenre(i)) return genreSet def __eq__(self,y): return self.value==y.value class GenreFiles(object): def __init__(self,location,genre): self.files=[] self.basedirec=location self.genre=genre def addFile(self,fyle): self.files.append(fyle) def getFiles(self): return self.files def numFiles(self): return self.files.__len__() def getSubset(self,le): if le>self.numFiles(): raise ValueError subset=[] i=0 for l in self.files: if i< le: subset.append(l) i+=1 else: self.files=subset def __str__(self): st=self.genre.__str__()+'\n' for i in self.files: st+=('\t'+i+'\n') return st class Dataset(object): def __init__(self): self.genreFiles=[] def populateSet(self,location): genreSet=enumGenre.__enumSet__() for direc in os.listdir(location): if os.path.isdir(os.path.join(location,direc)): for g in genreSet: if direc==g.__str__(): files=GenreFiles(location,g) for fyle in os.listdir(os.path.join(location,g.__str__())): if os.path.isfile(os.path.join(location,g.__str__(),fyle)): files.addFile(fyle) if files.numFiles()>0: self.genreFiles.append(files) break def filter(self,genres=None,le=None): if genres==None and le == None: return self.genreFiles if genres==None: genres=enumGenre.__enumSet__() newSet=[] for s in self.genreFiles: match=False for g in genres: if g.__eq__(s.genre): match=True break if match: if le!=None: s.getSubset(le) newSet.append(s) self.genreFiles=newSet if __name__ == '__main__': location='../../Datasets/GTZAN' genres=[enumGenre(enumGenre.BLUES),enumGenre(enumGenre.ROCK)] dataset=Dataset() dataset.populateSet(location) dataset.filter(genres, 10) for s in dataset.genreFiles: print s
UTF-8
Python
false
false
2,013
11,742,440,606,477
7f56ef5d2b506195caed3297e539f0012cf6cb93
8acbd6cde913daad2b797639f19e14dd717727f9
/ZenPacks/community/zenHttpComponent/facades.py
abbcd86117ca5a93cd456dfb28de647b3114c408
[]
no_license
sporting-news/ZenPacks.community.zenHttpComponent
https://github.com/sporting-news/ZenPacks.community.zenHttpComponent
545126be6f808c5a5f59a1b7974f214090cc3f5e
cd31a7282b76008468b6ce7fea1e28552d202b59
refs/heads/master
2021-01-16T20:07:44.153657
2012-05-01T18:58:57
2012-05-01T18:58:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os,re import logging log = logging.getLogger('zen.zenHttpComponentfacade') from zope.interface import implements from Products.Zuul.facades import ZuulFacade from Products.Zuul.utils import ZuulMessageFactory as _t from HttpComponent import HttpComponent from .interfaces import IzenHttpComponentFacade class zenHttpComponentFacade(ZuulFacade): implements(IzenHttpComponentFacade) def addHttpComponent(self, ob, httpPort='80', httpUseSSL=False, httpUrl='/', httpAuthUser='', httpAuthPassword='', httpJsonPost='', httpFindString=''): """ Adds HTTP Component URL monitor""" id = ob.id + '_' + re.sub('[^A-Za-z0-9]+', '', httpUrl) + '_'+httpPort httpcomponent = HttpComponent(id) ob.httpComponents._setObject(httpcomponent.id, httpcomponent) httpcomponent = ob.httpComponents._getOb(httpcomponent.id) httpcomponent.httpIp = ob.manageIp httpcomponent.httpPort = httpPort httpcomponent.httpUseSSL = httpUseSSL httpcomponent.httpUrl = httpUrl httpcomponent.httpAuthUser = httpAuthUser httpcomponent.httpAuthPassword = httpAuthPassword httpcomponent.httpJsonPost = httpJsonPost httpcomponent.httpFindString = httpFindString return True, _t(" Added URL Monitor for device %s" % (ob.id))
UTF-8
Python
false
false
2,012
14,525,579,442,176
f7ac36ddcfec78f05430732f03e24729b37060f8
c6480069ec4b709ce6f3abf2e721e4e67135b0f3
/srilm/helper.py
1c41a1158d31e47e487665b061224f0ec1c7515f
[ "BSD-3-Clause" ]
permissive
tetsuok/py-srilm-interpolator
https://github.com/tetsuok/py-srilm-interpolator
2b285c53c0c2c971f9d032c54f8d058af7ef382f
063d87be16e6c7ec8f9b3b0e4f97e2616ec46b46
refs/heads/master
2016-09-06T06:59:03.220646
2012-11-16T22:32:38
2012-11-16T22:32:38
6,709,846
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright 2012 Tetsuo Kiso. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import subprocess def redirect(cmd, out_file): """Emulate redirection. $ cmd > out_file """ try: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True) except: print 'ERROR: %s' % ' '.join(cmd) raise (stdout_content, _) = process.communicate() with open(out_file, 'w') as fout: fout.write(stdout_content) return process.wait() def run_or_die(cmd, msg): try: process = subprocess.Popen(cmd) except: print '==========' print 'ERROR: {0}'.format(msg) print '==========' raise process.wait()
UTF-8
Python
false
false
2,012
18,554,258,751,134
d56a9bf658c3aeabf021fe072458a55a13657ba1
c77fb6d8bd835f82009cb73b3b6358197a9a5db0
/gasistafelice/real_rest/urls.py
5c3ce786acac0e0774b52dd0d1d9993788b7d33b
[ "AGPL-3.0-only" ]
non_permissive
DydFreeman/gasistafelice
https://github.com/DydFreeman/gasistafelice
aa52808e2678c6c00dc194d9d5f9c0d0d92b607a
0311cacc405e44fd4097324b3e180b4f9d987bfb
refs/heads/master
2021-01-24T03:48:20.634853
2014-11-11T18:43:21
2014-11-11T18:43:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls.defaults import * from django.conf import settings import views as rest_views urlpatterns = patterns('', url(r'^v1/person/$', rest_views.PersonCreateReadView.as_view(), name='api-v1-person-list'), url(r'^v1/person/(?P<pk>\d+)/$', rest_views.PersonReadUpdateDeleteView.as_view(), name='api-v1-person'), (r'^v1/gasmember/(?P<pk>\d+)/$', rest_views.GASMemberReadUpdateDeleteView.as_view()), (r'^v1/gas/(?P<pk>\d+)/$', rest_views.GASReadUpdateDeleteView.as_view()), (r'^v1/supplier/(?P<pk>\d+)/$', rest_views.SupplierReadUpdateDeleteView.as_view()), )
UTF-8
Python
false
false
2,014
11,562,052,008,137
527b4605acbaf7e9cae3e4ca213b7f7a4d23cc2b
84998c21899451bdf6afbdd39353575af71750bb
/nyaacrawler/views.py
e536f213edcba235e9773418ec3491a6a8958a0e
[]
no_license
Winxton/anitor
https://github.com/Winxton/anitor
106848ea00ce9fadfc1a338b56ea62db5112e348
5e6f646e29c09171bc934dea828055eb72803eec
refs/heads/master
2021-01-23T17:30:56.978947
2014-01-24T00:33:11
2014-01-24T00:33:11
11,886,057
1
0
null
false
2013-09-29T06:42:50
2013-08-04T22:29:45
2013-09-29T06:42:49
2013-09-29T06:42:49
4,392
null
0
3
CSS
null
null
# Create your views here. from django.shortcuts import render from django.views.decorators.http import require_http_methods from django.http import HttpResponse, HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from nyaacrawler.utils.emailSender import send_registration_confirmation_email from nyaacrawler.models import * from urllib import urlencode import sys import json import logging logger = logging.getLogger(__name__) def index(request): anime = Anime.get_active_anime_by_leechers() context = {'animeList': anime} return render(request, 'index.html', context) def get_torrents_for_anime_episode(request): anime_id = request.GET.get('id') episode = request.GET.get('episode') torrent_list = Torrent.objects.filter( episode=episode, title__anime__pk=anime_id ).order_by('fansub') anime_title = Anime.objects.get(pk=anime_id).official_title; response = [] for torrent in torrent_list: torrentObj = {} torrentObj['fansub'] = torrent.fansub torrentObj['quality'] = torrent.quality torrentObj['torrent_link'] = torrent.url params = { 'dn' : anime_title, 'xt' : 'urn:btih:%s' % torrent.infoHash, } torrentObj['magnet_link'] = "magnet:?" + urlencode(params); torrentObj['seeders'] = torrent.seeders torrentObj['leechers'] = torrent.leechers torrentObj['file_size'] = torrent.file_size response.append(torrentObj) return HttpResponse(json.dumps(response), content_type='application/json') @csrf_exempt @require_http_methods(["POST"]) def subscribe(request): """ Saves a subscription given the email and a comma delimited list of fansub groups and qualities """ results = {'success':False} subscription_request = json.loads(request.body) try: anime = Anime.objects.get(pk=subscription_request['anime_key']) already_subscribed = Subscription.objects.filter(email=subscription_request['email'], anime=subscription_request['anime_key']).exists() if already_subscribed: results['error_message'] = "You have already subscribed to this anime." else: subscription_data = { 'email' : subscription_request['email'], 'anime' : subscription_request['anime_key'], 'current_episode' : anime.current_episode(), 'qualities' : subscription_request['qualities'], 'fansubs' : subscription_request['fansub_groups'] } subscription_form = SubscriptionForm(subscription_data) if (subscription_form.is_valid()): subscription, created = Subscription.objects.get_or_create(**subscription_form.cleaned_data) #send subscription confirmation email if created: registration_parameters = {} registration_parameters['email'] = subscription.email registration_parameters['unsubscribe_key'] = subscription.unsubscribe_key registration_parameters['anime'] = subscription.anime.official_title try: send_registration_confirmation_email(registration_parameters) except: pass results['success'] = True logger.info ("Subscribed: " + subscription.email + " to " + subscription.anime.official_title) else: if 'email' in subscription_form.errors: results['error_message'] = "Invalid email." elif 'fansubs' in subscription_form.errors: results['error_message'] = "You must select a fansub." elif 'qualities' in subscription_form.errors: results['error_message'] = "You must select a quality." except: logger.error ( str(sys.exc_info()) ) json_result = json.dumps(results) return HttpResponse(json_result, content_type='application/json') def unsubscribe(request, unsubscribe_key): try: subscription = Subscription.objects.get(unsubscribe_key=unsubscribe_key) response = "unsubscribed from " + subscription.anime.official_title logger.info ( subscription.email + " " + response ) subscription.delete() #TODO: template for unsubscribe return HttpResponse( response ) except Subscription.DoesNotExist: return HttpResponseRedirect('/')
UTF-8
Python
false
false
2,014
3,255,585,230,536
05bc84b25b40c26395e262668a91a742f8aab964
ddf2677edfda56dfd6d3e59e7f0cd21cdab8f8db
/trunk/src/lino/django/apps/documents/tests.py
5b731ffada2abffffab92cb129b8d536499842ce
[ "GPL-2.0-only", "MIT" ]
non_permissive
BackupTheBerlios/lino-svn
https://github.com/BackupTheBerlios/lino-svn
13398d68b04d36dace1b44f5ec0a567064b8b1dc
93bbb22698a06ba78c84344ec6f639c93deb5ef3
refs/heads/master
2021-01-23T15:42:41.810323
2009-07-07T10:26:51
2009-07-07T10:26:51
40,806,965
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- ## Copyright 2009 Luc Saffre. ## This file is part of the Lino project. ## Lino is free software; you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## Lino is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ## or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public ## License for more details. ## You should have received a copy of the GNU General Public License ## along with Lino; if not, write to the Free Software Foundation, ## Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from django.test import TestCase from lino.django.utils.validatingmodel import TomModel, ModelValidationError from lino.django.utils.reports import Report from lino.django.utils.render import ViewReportRenderer from django.db import models from django.forms.models import modelform_factory, formset_factory from django.conf import settings from lino.django.apps.documents import models as documents class Document(documents.AbstractDocument): pass class DocumentsTest(TestCase): def test01(self): pass
UTF-8
Python
false
false
2,009
9,397,388,477,514
4968de4b9211cb01ccd615c7704b4fbc0dee1f04
afe8bcbc5dea50c9519d72c21e31e752d0a19cfc
/stats.py
fa842fb4c6cb11e8d8f8d88c87899b09e15c3d6e
[]
no_license
LazurasLong/Travian
https://github.com/LazurasLong/Travian
91f0e1fcb190202332951f91dfebdb052a639722
c309ae94f342e1ebd287783308b949e2403a17f6
refs/heads/master
2022-12-09T14:57:49.546089
2012-02-03T22:19:27
2012-02-03T22:19:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
############################################################################# # stats.py # # Mines player's population, offensive ranking, and defensive ranking # # changes at 10 minute intervals, then creates sql query and passes it # # to the agent. # # Runs with: # # no args goes through 'watching' alliance list and logs changes # # -off goes through first 300 pages of offense rankings # # -def goes through first 300 pages of defense rankings # ############################################################################# import os.path, urllib2, cookielib, urllib, re, sys, datetime from urllib2 import urlopen, Request # html stripper HTMLtag = re.compile('<.*?>') # Matches html tags HTMLcom = re.compile('<!--.*?-->') # Matches html comments def striphtml(inp): return HTMLtag.sub('', HTMLcom.sub('', inp)) watching = [71,73,85,108,143,194,196,217,224,225,248,281,386,401,450,531,615,627,774,838,867,924,1230,1348,337,130,214,284] # Watched alliances watching = [str(k) for k in watching] home = "http://s4.travian.us/" login_dict = {"w":""} txheaders = {'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} cookiefile = "cookie.lwp" cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) if os.path.isfile(cookiefile): # Cookie exists, check if it's still valid cj.load(cookiefile, ignore_discard=True, ignore_expires=True) print "Cookie loaded" handle = urlopen(Request(home+"dorf1.php", None, txheaders)) for line in handle.readlines(): if '"password"' in line: # cookie has expired; get new one print "Cookie expired, renewing..." os.remove(cookiefile) # delete old one break handle.close() if not os.path.isfile(cookiefile): # If no cookie (or expired), load login page variables handle = urlopen(home) for line in handle.readlines(): line = line.strip()[:-1] if "type=" not in line or "name=" not in line or "value=" not in line: continue # don't care about this line input = [k.replace('"','') for k in line.strip().split() if "type=" in k or "name=" in k or "value=" in k] if len(input) <3: continue if "login" in input[1] and "login" not in login_dict: # login serial login_dict["login"] = input[2].replace("value=","") elif "name=e" in input[1] and "type=text" in input[0]: # username login_dict[input[1].replace("name=","")] = "ulrezaj" elif "name=e" in input[1] and "type=password" in input[0]: #password login_dict[input[1].replace("name=","")] = "warhammer40k" elif "name=e" in input[1]: # any other e-value login_dict[input[1].replace("name=","")] = input[2].replace("value=","").replace(">","") handle.close() txdata = urllib.urlencode(login_dict) # encode login variables handle = urlopen(Request(home+"dorf1.php", txdata, txheaders)) cj.save(cookiefile, ignore_discard=True, ignore_expires=True) # collect cookie handle.close() print "Cookie saved" print datetime.datetime.now() # Collecting off/def stats sql = "" cur, count = "", 0 if "off" in sys.argv or "def" in sys.argv: type = {"off":"31", "def":"32"} for i in range(300): sys.stdout.write(".") sys.stdout.flush() handle = urlopen(home+"statistiken.php?id="+type[sys.argv[1]]+"&rang="+str(20*i+1)) for line in handle.readlines(): if "spieler.php?uid=" in line and 'ss="s7' in line: cur = [k.replace("spieler.php?uid=","") for k in line.split('"') if "spieler" in k][0] elif cur and count==0: count = 1 elif cur and count==1: count = 2 elif cur and count==2: sql += "uid="+cur+",points="+striphtml(line.strip())+",;" cur, count = "", 0 sql_dict = {'pre': 'insert ignore into s4_us_'+sys.argv[1]+' set', 'suf': 'time=timestampadd(HOUR,3,now())', 'sql': sql} txdata = urllib.urlencode(sql_dict) # stick into post variables req = Request("http://travian.ulrezaj.com/agent.php", txdata, txheaders) # give statements to agent.php handle = urlopen(req) handle.close() print print datetime.datetime.now() sys.exit() # Collecting pop players = {} # uid: pop alliances = {} # uid: aid villages = {} # karte: pop # Get each watched alliance's current pops for aid in watching: handle = urlopen(Request(home+"allianz.php?aid="+aid, None, txheaders)) for line in handle.readlines(): if "spieler.php?uid=" in line and ".</td" in line: players[[k.replace("spieler.php?uid=","") for k in line.split('"') if "spieler" in k][0]] = striphtml(line[line.rfind("<td>"):].strip()) alliances[[k.replace("spieler.php?uid=","") for k in line.split('"') if "spieler" in k][0]] = aid handle.close() # Get latest recorded pops for each alliance and prune players list handle = urlopen("http://travian.ulrezaj.com/agent.php?hget="+",".join(watching)) latest = [k.split(",") for k in handle.read().split(";") if k] for uid,pop in latest: if uid in players and players[uid]==pop: players.pop(uid) handle.close() # Get pop details for players whose pop changed sql, cur = "", "" for uid in players: sys.stdout.write(".") sys.stdout.flush() handle = urlopen(Request(home+"spieler.php?uid="+uid, None, txheaders)) for line in handle.readlines(): # Karte and pop are on adjacent lines - check for karte then immediately get pop if "karte.php?d=" in line: cur = [k.replace("karte.php?d=","") for k in line.split('"') if "karte" in k][0] sql += 'uid='+uid+',aid='+alliances[uid]+',karte="'+cur+'",' elif cur: sql += 'pop='+striphtml(line.strip())+',;' cur = "" handle.close() print print datetime.datetime.now() print len(players),"records updated" # Upload sql_dict = {'pre': 'insert ignore into s4_us_pop set', 'suf': 'time=timestampadd(HOUR,3,now())', 'sql': sql} txdata = urllib.urlencode(sql_dict) # stick into post variables req = Request("http://travian.ulrezaj.com/agent.php", txdata, txheaders) # give statements to agent.php handle = urlopen(req) print handle.read() handle.close()
UTF-8
Python
false
false
2,012
3,169,685,900,419
68e2b341c6d07572e884aead32f17ce5b272f8ba
c757e13925d511e8718c1bc65a9a3e2659a3c9fe
/Gui/Widgets/viewRunWidget.py
74f91a44b6d4753b157240c8b4f3ff8c94f67ea4
[ "GPL-2.0-only" ]
non_permissive
olga-weslowskij/olga.weslowskij
https://github.com/olga-weslowskij/olga.weslowskij
fc09bc59a7b7a95784c88b1f7cf42c51dc4be627
287d723b7878ea7fd3707254150230e6d9720a39
refs/heads/master
2021-01-23T21:35:02.566332
2014-10-02T13:08:24
2014-10-02T13:08:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (C) weslowskij # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import logging from kivy.adapters.simplelistadapter import SimpleListAdapter from kivy.uix.button import Button from kivy.uix.gridlayout import GridLayout from Gui.Screens.aViewNotesScreen import SelectNotes from Gui.Widgets.kivyNoteMap import KivyNoteMap from Gui.Widgets.listview8 import ListView8 import myglobals from mylibs.myDict import MyDict logger = logging.getLogger(__name__) hdlr = logging.FileHandler(__name__ + '.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.NOTSET) class ViewRunAdapter(SelectNotes, SimpleListAdapter): def __init__(self): self.song= None self.stream=None self.build() self.cache={} self.wcache=[] # cache all self.docache=False def build(self): SelectNotes.build(self) self.widget = GridLayout(cols=10, size_hint_y=None) self.widget.bind(minimum_height=self.widget.setter('height')) return self.widget def updateGui(self): pass #print "update ViewRunWidget\n" def clear(self,children): if not(self.docache): for c in children: #print c.__class__.__name__ try: if c.__class__.__name__ == "KivyNoteMap": self.wcache.append(c) except: pass def get_view(self, index): if len (self.data) == 0: return None if index >= len(self.data): return None #return self.buildkivyMelodyRating(index) #print self.stream[-1].prettyprint() #return self.data[index] # on demand creation (toshow,i,wi) = self.data[index] if self.docache: try: return self.cache[self.data[index]] except: pass w = self.buildKivyNoteMap(toshow,i)[wi] if self.docache: self.cache[self.data[index]]= w if self.docache: # funny politics, tabula rasa # cut memory usage if len(self.cache) > 500: self.cache = {} return w def set_view(self,index, item): while index >= len(self.data): self.data.append(None) self.data[index] = item def buildObjectButton(self, attr, p = None ,o = None): btnid = Button(text=str(attr)) if o is None: x = p.__getattribute__(attr) else: x = o #print "got ", x def callback(instance): myglobals.ScreenState.mystate.selectedobject = x myglobals.ScreenState["ConfigObjectScreen"].object = x # force rebuild s = myglobals.ScreenState["ConfigObjectScreen"] try: s.notesscroller.remove_widget(s.layout) except: pass myglobals.ScreenState.change_state("ConfigObjectScreen") btnid.bind(on_press=callback) return btnid def buildKivyNoteMap(self, toshow, i, notesandrightspeed = None): x = toshow.list[i] childs=[] if len(self.wcache) > 0: btn = self.wcache.pop() #print "btn.parent " , btn.parent , "len(self.wcache)", len(self.wcache) btn.config(toshow.list[i].getInNote(), toshow.list[i].getKnownNote()) childs=btn.children btn.clear_widgets() else: #print "btn new " btn = KivyNoteMap() btn.build(toshow.list[i].getInNote(), toshow.list[i].getKnownNote()) """ btnid = Button(text="id:" + str(id(x))) btn.add_widget(btnid) def callback(instance): myglobals.ScreenState.mystate.selectedobject = x myglobals.ScreenState["ConfigObjectScreen"].object = x myglobals.ScreenState.change_state("ConfigObjectScreen") btnid.bind(on_press=callback) """ btn.add_widget(self.buildObjectButton(str(id(x)), o=x)) """ if type(x) is list: btn.build(x) else: btn.build([x]) """ #btn.progress.value=1 btn.speed.text=str(x) btn.add_widget(btn.orgchord) btn.orgchord.bind(on_press=self.selectBtn) btn.add_widget(btn.chord) btn.chord.bind(on_press=self.selectBtn) #btn.add_widget(Label(text="id:" + str(id(x)))) #btn.myduration.text="id:" + str(id(x)) #btn.add_widget(btn.myduration) if toshow.list[i].getKnownNote(): btn.myvolume.text="("+str(toshow.list[i].getKnownNote().myoffset)+")" else: btn.myvolume.text="None" btn.add_widget(btn.myvolume) btn.add_widget(btn.myoffset) """ if x: xd = x.rspeed() if xd is None: xd = "None" else: xd ="None" btn.add_widget(self.buildObjectButton("rspeed", o=xd)) btn.add_widget(self.buildObjectButton("maxRightSpeedRunState", p=x)) btn.add_widget(self.buildObjectButton("minRightSpeedRunState", p=x)) """ if x.getCurrent2RunSpeed(): #if x.rightspeederror: if False: text='[color=ff0000]'+str(x.getCurrent2RunSpeed())[0:5] +'[/color]' btn.speed.markup=True else: text = str(x.getCurrent2RunSpeed())[0:5] btn.speed.text= text btn.speed.halign="right" #btn.add_widget(btn.speed) else: btn.speed.text="-" btn.error.text="" if hasattr(x,"errorstr"): if x.errorstr: btn.error.text ='[color=ff0000]'+str(x.errorstr) +'[/color]' btn.error.markup=True btn.add_widget(btn.error) #if x.getCurrent2RunSpeed(): #self.notesscroller.data.append(btn.speed) #self.notesscroller.widget.add_widget(btn.speed) #if x.getCurrent2RunSpeed(): if x.lastRunState and x.lastRunState.getKnownChordInNoteMap().chordfull(): #self.notesscroller.data.append(btn.speed) #self.notesscroller.widget.add_widget(btn.speed) btn.speed.height = btn.height btn.speed.size_hint_y=None return [btn, btn.speed] #btn.add_widget(btn.speed) #self.notesscroller.data.append(btn) #self.notesscroller.widget.add_widget(btn) return [btn] class ViewRunWidget(ListView8,object): def __init__(self, *args, **kwargs): super(ViewRunWidget,self).__init__(*args, **kwargs) self.donelen = 0 self.shownMelodyRun=None self.shownKivyNoteMap=[] self.shownMelodyRating=MyDict() self.shownMelodyRating.defaultNone=True self.shownpos ={} self.shownpos[0]=0 self.shownpos[1]=0 self.widget = self self.adapter = ViewRunAdapter() self.notesscroller = self.adapter self.do_scroll_x=True self.do_scroll_y=True self.toshow = None @property def run(self): return self.toshow @run.setter def run(self, value): self.toshow = value """ def updateGui(self): self.adapter.updateGui() self._trigger_reset_populate() """ def play(self): self.adapter.play() def updateGui(self): """if not(self.shownMelodyRun is None or self.shownMelodyRun != self.toshow): return """ # belongs in update, but i dont have update widget .. if self.shownMelodyRun == self.toshow: return # rest belong in updateGui toshow = self.toshow index = len(self.shownKivyNoteMap) if toshow is None: print "Show Run None" for i in xrange(index): self.shownKivyNoteMap[i] = None self.notesscroller.set_view(self.shownpos[i], None) self._trigger_reset_populate() return print self.toshow.prettyprint() newlen = len(toshow.list) #for x in self.notesscroller.stream: news = False # extend while ( len(self.shownKivyNoteMap)< newlen): self.shownKivyNoteMap.append(None) news = True """ what is with changed??? if news == False: return """ #update all changed for start in xrange(newlen-1, -1,-1): news = True if toshow.list[start] == self.shownMelodyRating[start]: #pass break #logger.info("updating " + str([start+1,newlen])) #for i in xrange(start+1, newlen): for i in xrange(start, newlen): #for i in xrange(newlen): if toshow.list[i] != self.shownMelodyRating[i] or True: #if self.shownKivyNoteMap[i]: # self.notesscroller.widget.remove_widget(self.shownKivyNoteMap[i]) # self.notesscroller.widget.remove_widget(self.shownKivyNoteMap[i].speed) #self.shownKivyNoteMap[i] = self.buildKivyNoteMap(toshow,i) x = toshow.list[i] if x.lastRunState and x.lastRunState.getKnownChordInNoteMap().chordfull(): #if len(self.shownKivyNoteMap[i]) == 2: self.shownpos[i+1]= self.shownpos[i] + 2 #self.notesscroller.set_view(self.shownpos[i]+1, self.shownKivyNoteMap[i][0]) self.notesscroller.set_view(self.shownpos[i]+1, (toshow,i,0)) #self.notesscroller.set_view(self.shownpos[i], self.shownKivyNoteMap[i][1]) self.notesscroller.set_view(self.shownpos[i], (toshow,i,1)) # else: self.shownpos[i+1]= self.shownpos[i] + 1 #self.notesscroller.set_view(self.shownpos[i], self.shownKivyNoteMap[i][0]) self.notesscroller.set_view(self.shownpos[i], (toshow,i,0)) #self.notesscroller.data[self.shownpos[i]] = self.shownKivyNoteMap[i][0] self.shownMelodyRating[i] = toshow.list[i] #logger.info("clearing " + str([newlen,len(self.shownKivyNoteMap)])) for i in xrange(newlen, len(self.shownKivyNoteMap)): self.shownKivyNoteMap[i] = None self.shownMelodyRating[i] = None self.notesscroller.set_view(self.shownpos[i], None) self.donelen = index #len(self.notesscroller.stream) #self.notesscroller.updateGui() if (news): #self.notesscroller.data = self.shownKivyNoteMap self._trigger_reset_populate() self.shownMelodyRun = toshow pass def buildKivyNoteMap(self, toshow, i, notesandrightspeed = None): x = toshow.list[i] btn = KivyNoteMap() btn.build(toshow.list[i].getInNote(), toshow.list[i].getKnownNote()) """ btnid = Button(text="id:" + str(id(x))) btn.add_widget(btnid) def callback(instance): myglobals.ScreenState.mystate.selectedobject = x myglobals.ScreenState["ConfigObjectScreen"].object = x myglobals.ScreenState.change_state("ConfigObjectScreen") btnid.bind(on_press=callback) """ btn.add_widget(self.buildObjectButton(str(id(x)), o=x)) """ if type(x) is list: btn.build(x) else: btn.build([x]) """ #btn.progress.value=1 btn.speed.text=str(x) btn.add_widget(btn.orgchord) btn.orgchord.bind(on_press=self.notesscroller.selectBtn) btn.add_widget(btn.chord) btn.chord.bind(on_press=self.notesscroller.selectBtn) #btn.add_widget(Label(text="id:" + str(id(x)))) #btn.myduration.text="id:" + str(id(x)) #btn.add_widget(btn.myduration) if toshow.list[i].getKnownNote(): btn.myvolume.text="("+str(toshow.list[i].getKnownNote().myoffset)+")" else: btn.myvolume.text="None" btn.add_widget(btn.myvolume) btn.add_widget(btn.myoffset) """ if x: xd = x.rspeed() if xd is None: xd = "None" else: xd ="None" btn.add_widget(self.buildObjectButton("rspeed", o=xd)) btn.add_widget(self.buildObjectButton("maxRightSpeedRunState", p=x)) btn.add_widget(self.buildObjectButton("minRightSpeedRunState", p=x)) """ if x.getCurrent2RunSpeed(): #if x.rightspeederror: if False: text='[color=ff0000]'+str(x.getCurrent2RunSpeed())[0:5] +'[/color]' btn.speed.markup=True else: text = str(x.getCurrent2RunSpeed())[0:5] btn.speed.text= text btn.speed.halign="right" #btn.add_widget(btn.speed) else: btn.speed.text="-" btn.error.text="" if hasattr(x,"errorstr"): if x.errorstr: btn.error.text ='[color=ff0000]'+str(x.errorstr) +'[/color]' btn.error.markup=True btn.add_widget(btn.error) #if x.getCurrent2RunSpeed(): #self.notesscroller.data.append(btn.speed) #self.notesscroller.widget.add_widget(btn.speed) #if x.getCurrent2RunSpeed(): if x.lastRunState and x.lastRunState.getKnownChordInNoteMap().chordfull(): #self.notesscroller.data.append(btn.speed) #self.notesscroller.widget.add_widget(btn.speed) btn.speed.height = btn.height btn.speed.size_hint_y=None return [btn, btn.speed] #btn.add_widget(btn.speed) #self.notesscroller.data.append(btn) #self.notesscroller.widget.add_widget(btn) return [btn] def buildObjectButton(self, attr, p = None ,o = None): btnid = Button(text=str(attr)) if o is None: x = p.__getattribute__(attr) else: x = o #print "got ", x def callback(instance): myglobals.ScreenState.mystate.selectedobject = x myglobals.ScreenState["ConfigObjectScreen"].object = x # force rebuild s = myglobals.ScreenState["ConfigObjectScreen"] try: s.notesscroller.remove_widget(s.layout) except: pass myglobals.ScreenState.change_state("ConfigObjectScreen") btnid.bind(on_press=callback) return btnid
UTF-8
Python
false
false
2,014
7,189,775,255,985
748ff38015bbf60d9444026f23abcce607732b88
5a6222b84659c443c6bbaf49c53b13f9196fd877
/site/newsite/site-geraldo/local_settings.py
f6b72149797612f318d9b33daed7846801bc8b53
[ "LGPL-3.0-or-later", "GPL-1.0-or-later" ]
non_permissive
josecesarano/geraldo
https://github.com/josecesarano/geraldo
948a7c30dd6bc785d866dec9f54d8c814582ea77
55c2a8bd99bac63ee083798f4992d6c2a7689853
refs/heads/master
2021-01-20T23:52:11.305243
2010-04-03T03:47:12
2010-04-03T03:47:12
595,877
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
LOCAL = True DEBUG = True TEMPLATE_DEBUG = DEBUG PROJECT_ROOT_URL = 'http://localhost:8000/'
UTF-8
Python
false
false
2,010
4,277,787,457,936
8c4f3950d6386d5d6deab403df2817ebc3ebc2c8
2639defef381cc5345430b98a7809ffa7539ff3d
/babysock.py
8db22ea987dfb2d5e9adddd723f8ca80622802dd
[]
no_license
blueghosties/PythonOfEviiillle
https://github.com/blueghosties/PythonOfEviiillle
598259231fd2d09ee409cf41609b8e0034034a68
3745a1e848978091bf18f9af581977e1ff134f45
refs/heads/master
2020-05-18T00:21:28.183108
2014-03-28T04:21:00
2014-03-28T04:21:00
18,200,478
0
1
null
false
2016-09-30T21:19:44
2014-03-28T03:56:00
2014-03-28T04:20:58
2016-09-30T21:19:43
140
0
1
1
null
null
null
import socket import time # This is an inspirational result from the book, Violent Python, written by - TJ OConner. # For anyone that enjoys hacking or wants to learn about hacking/programming, this is a great book. # Buy it. # This code is free to anyone who wants to modify it and use it. Remember, you are responsible # for running this code, not anyone else. Test, run, enjoy...at your own discretion and risk. # All I ask is credit for the work I've done. Creditware...pass the credit along. # I am just starting out on my journey into hacking and programming, so any constructive criticism is welcome. # Run using Python version 2.7.3 def da_connect(ip, port): try: socket.setdefaulttimeout(1) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) s.send('Hello! This is EVIILLLE calling! Anyone home?') data = s.recv(1024) print 'We hit something! Received' + str(data) print 'Logging hit on the network.' fo = open("hits.txt", "a") now = time.strftime("%c") # date and time representation print "Current date & time " + time.strftime("%c") toFoOut = "We hit " + str(ip) + ": " + str(port) + ": " + time.strftime("%c") # write to file fo.write(toFoOut + '\n') fo.close() print 'Wrote to log file.' # We want to close the connection after we opened it. # This is for logging open ports and nothing more at the moment. # Muhahahahahahaha. s.close() s.shutdown() except: return def main(): print '#######################################################' print '# Written by blueghosties 2014 #' print '# Inspired by Violent Python author TJ OConnor #' print '# Not responsible for program use or any damage #' print '# to any system as a result of running this program #' print '#######################################################' print ' -- ' print ' / 00| BOO! ' print ' / / ' print ' / \\ ' print ' \/\/\/\/ ' print 'Enter first three numbers, then press enter...\nno dot after it...next three and so on. \nExample: 192 <enter> 168 <enter> 1 <enter> 100 <enter>' # concat_ip = input('Enter in the ip range ') num1 = input('Enter first set of IP num: ') num2 = input('Enter second set of IP num: ') num3 = input('Enter third set of IP num: ') num4 = input('Enter fourth set of IP num: ') port = input('Enter in port range: <from port 0 to ?> ') int(port) # Raise less suspicion by slowing down the scan rate # Was thinking about putting in a random() number generator to # to really vary the times of hitting the ports, but thought it # was overkill. timeDelay = input('Enter a number if you want a time delay.\nOtherwise, just enter 0 \n<Example: 2 for 2 seconds between scans>') if timeDelay > 0: print 'Delay set for ' + str(timeDelay) + ' seconds.' else: print 'Delay not set...we want it to scream!' # this_num will increment after it has scanned the ip range this_num = num4 # concat the entered ip address concat_ip = str(num1) + '.' + str(num2) + '.' + str(num3) + '.' # set x as this_num ip range number for x in range(this_num, 255): # concat full ip address ip = concat_ip + str(x) print '[+] ' + str(ip) # time to count the port range to see if we find an opening for port in range(0, 1000): print 'Scanning IP:' + str(ip) + ' Port: ' + str(port) # time for sleep? time.sleep(timeDelay) banner = da_connect(ip, port) # if we connectted call da_connect() method if banner: print '[+] ' + ip + ': ' + banner if __name__ == '__main__': main()
UTF-8
Python
false
false
2,014
15,341,623,187,851
30b66e7787047614ed40f658272ce56bffe26c3e
a4a539423684f66dd54d2056dc478d6785be8d88
/ganeti/templatetags/days_since.py
6e776c7ce2b59dbee86cf214aa606823797759a8
[ "ISC" ]
permissive
cargious/ganetimgr
https://github.com/cargious/ganetimgr
bec96b4ad6d970c66b7e80eb89cb6ec083e8c55c
13eaefcd07b3f388416623a35bafa8dcc782196b
refs/heads/master
2021-01-17T20:24:05.982307
2014-02-25T12:36:36
2014-02-25T12:36:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# # -*- coding: utf-8 -*- vim:fileencoding=utf-8: # Copyright © 2010-2013 Greek Research and Technology Network (GRNET S.A.) # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. from django import template register = template.Library() import datetime @register.filter(name='days_since') def days_since(value): since = 0 try: since = (datetime.datetime.now() - value).days except: pass return since
UTF-8
Python
false
false
2,014
10,359,461,118,490
532a053ab3545e20ae829c3bf6200c3c35130010
1b4672de3ee7eb823fb2a238ea767fe0e1e11e7e
/profiles/views.py
b7cd49d53a7469c021d6720bc4c5645a4aa4b2db
[]
no_license
FriedrichK/gamecoach
https://github.com/FriedrichK/gamecoach
ce6510115e58286cc5eb56ddfbd35e7457639379
cfa0d8c686cbc7b48cfc86e1feabd30d575f3039
refs/heads/master
2016-09-06T04:08:52.746047
2014-11-03T21:20:39
2014-11-03T21:20:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#import os import json import urllib import cStringIO from io import BytesIO import base64 from PIL import Image from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.core.files.base import ContentFile from profiles.tools.mentors import get_all_mentors, get_mentor_by_id, get_mentor_by_username from profiles.tools.profile_methods import get_profile_by_username from profiles.tools.signup_form import add_profile_for_user, update_profile_for_user, get_mentor_signup_form_from_request from profiles.tools.data_uris import DataURI from profiles.models import ProfilePicture @csrf_exempt def mentor(request, mentor_id): if request.method == "POST": return mentor_create_or_update(request, mentor_id) if request.method == "GET": return mentor_read(request, mentor_id) if request.method == "DELETE": return mentor_delete(request, mentor_id) def mentor_read(request, mentor_id): if mentor_id is None: return get_filtered_mentors(request) else: mentor = get_mentor_by_id(mentor_id) if mentor is None: return HttpResponseNotFound() return HttpResponse(json.dumps(mentor.deserialize())) def mentor_create_or_update(request, mentor_id): mentor_signup_form = get_mentor_signup_form_from_request(json.loads(request.body)) if request.user is None or not request.user.is_authenticated(): return HttpResponseNotFound(json.dumps({'success': False, 'error': 'no_valid_user_found'})) if not hasattr(request.user, 'gamecoachprofile'): return mentor_create(request, mentor_signup_form) return mentor_update(request, mentor_id, mentor_signup_form) def mentor_create(request, mentor_signup_form): result = add_profile_for_user(request.user, mentor_signup_form) return HttpResponse(json.dumps({'successs': True})) def mentor_update(request, mentor_id, mentor_signup_form): result = update_profile_for_user(request.user, mentor_signup_form) return HttpResponse(json.dumps({'success': True})) def mentor_delete(request, mentor_id): if request.user is None or not request.user.is_authenticated(): return HttpResponseNotFound(json.dumps({'success': False, 'error': 'no_valid_user_found'})) if not request.user.username == mentor_id: return HttpResponseBadRequest(json.dumps({'success': False, 'error': 'access denied'})) request.user.is_active = False request.user.save() return HttpResponse(json.dumps({'success': True, 'message': 'user deactivated'})) def get_filtered_mentors(request): filters = {} filter_categories = ['roles', 'regions', 'day', 'time'] for filter_category in filter_categories: raw_filter = request.GET.get(filter_category, None) if not raw_filter is None: if filter_category == "day" or filter_category == "time": filter_value = {} filter_value[raw_filter] = True else: filter_value = json.loads(urllib.unquote(raw_filter)) filters[filter_category] = filter_value return HttpResponse(json.dumps(get_all_mentors(filters))) @csrf_exempt def profile_picture(request, user_id): if request.method == "GET": return profile_picture_display(request, user_id) if request.method == "POST": return profile_picture_upload(request) @csrf_exempt def profile_username(request): username = request.GET.get('value', None) no_username_message = json.dumps({'success': False, 'message': 'username %s does not exist' % username}) username_message = json.dumps({'success': True, 'message': 'username %s exists' % username}) if not username is None and not username == '' and not get_profile_by_username(username) is None: return HttpResponse(username_message) return HttpResponseNotFound(no_username_message) def profile_picture_display(request, username): try: user = get_mentor_by_username(username) picture = ProfilePicture.objects.get(user=user) image_path = unicode(picture.image) image_path = image_path.replace(settings.MEDIA_ROOT, '') final_path = '/upload' + image_path response = HttpResponse() del response['content-type'] response['X-Accel-Redirect'] = final_path return response except ProfilePicture.DoesNotExist: return HttpResponseNotFound() return HttpResponse(json.dumps({})) def profile_picture_upload(request): body = json.loads(request.body) uri = DataURI(body['data']) img = ContentFile(uri.data, body['meta']['name']) profile_picture, created = ProfilePicture.objects.get_or_create(user=request.user) profile_picture.image = img profile_picture.save() return HttpResponse(json.dumps({}))
UTF-8
Python
false
false
2,014
11,381,663,369,675
6147a8f5eb8a9e3fb5a862e088f9d05ab060a28c
26814c98b3d454738d27b6aa9bd5105007345705
/src/installer/plugins/PageEditor/__init__.py
9a4a7a21c2fb5b378bbde72f0445bd5f85bf432d
[ "GPL-2.0-only" ]
non_permissive
Letractively/spiff
https://github.com/Letractively/spiff
3e81dfea1878ec88f5ae9e14b07117dfd7835b84
5bb9ce03e1faf019743216671bc7c64d282ca8a1
refs/heads/master
2021-01-10T16:54:33.599586
2009-01-02T12:44:12
2009-01-02T12:44:12
45,957,800
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
__all__ = ['Controller'] from Controller import Controller
UTF-8
Python
false
false
2,009
16,020,228,033,457
73570194b478ad4b4f2b32c8d0fa8969a6f145c2
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_6/clxsip004/question3.py
203a20fc365c949dd9c5e9cb18f1fabb19fb442c
[]
no_license
MrHamdulay/csc3-capstone
https://github.com/MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Siphesihle Cele #26 April 2014 #program that simulates a voting system. #the usage of 2 array's is requireed. #append all votes onto the first list #adopt 1 element of each component onto the second array #then calculate how many times it appeared in the first array. #simple enough lol, JOKES. print("Independent Electoral Commission") print("--------------------------------") parties =[] print("Enter the names of parties (terminated by DONE):\n") poll="0" i=1 while (poll!="DONE"): poll=input() if(poll=="DONE"): break else: parties.append(poll) filter = [] for i in parties: if i in filter: i = 0 else: filter.append(i) filter.sort() print("Vote counts:") for i in filter: print("%-10s - %s" % (i, parties.count(i)))
UTF-8
Python
false
false
2,014
19,164,144,091,250
f8352bfcfb56823e6a0f97cab6627859c6cf8c5e
5fc64be56d80d2a1daaa76ee350bfd061a3b7139
/gettingthingsgnome/gtg/local_dev_stuff/GTG/plugins/bugzilla/server.py
76e238554bfc1aef7b72fff899086c02e604349b
[ "GPL-3.0-only" ]
non_permissive
dneelyep/Programming-Directory
https://github.com/dneelyep/Programming-Directory
1830d5f30cdf086aff456758fde9204d0ace7012
b4088579a96f88731444fcd62eb22f9eea6aac3b
refs/heads/master
2021-01-25T04:01:47.272374
2011-07-29T22:03:51
2011-07-29T22:03:51
2,126,355
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2009 - Guillaume Desmottes <[email protected]> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see <http://www.gnu.org/licenses/>. SERVER_TAG_PRODUCT = 1 SERVER_TAG_COMPONENT = 2 class ServersStore: def __init__(self): self.servers = {} # GNOME server = Server('bugzilla.gnome.org') server.tag = SERVER_TAG_PRODUCT self.add(server) # freedesktop.org server = Server('bugs.freedesktop.org') server.tag = SERVER_TAG_COMPONENT self.add(server) # Mozilla server = Server('bugzilla.mozilla.org') server.tag = SERVER_TAG_COMPONENT self.add(server) # Samba server = Server('bugzilla.samba.org') server.tag = SERVER_TAG_COMPONENT self.add(server) def add(self, server): self.servers[server.name] = server def get(self, name): return self.servers.get(name) class Server: def __init__(self, name): self.name = name self.tag = None def get_tag(self, bug): if self.tag is None: return None elif self.tag == SERVER_TAG_PRODUCT: return bug.get_product() elif self.tag == SERVER_TAG_COMPONENT: return bug.get_component()
UTF-8
Python
false
false
2,011
17,514,876,656,601
ca3bc47f6f23c740df8a2fc733b91f43856b8d1a
4ebd8f566d121ea914737f6d500716ef48045f0b
/horizons/gui/gui.py
7621210d17b948b469259decbd90cfcd5bab0995
[ "GPL-1.0-or-later", "GPL-2.0-or-later" ]
non_permissive
ChrisOelmueller/unknown-horizons
https://github.com/ChrisOelmueller/unknown-horizons
899015c1d9658c75e5007f49317cb5ff20382f8b
14caa678274c671e844448dc6a42dc4c1ffd5f87
refs/heads/master
2021-01-15T18:26:28.104715
2012-12-30T14:02:09
2012-12-30T14:02:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# ################################################### # Copyright (C) 2012 The Unknown Horizons Team # [email protected] # This file is part of Unknown Horizons. # # Unknown Horizons is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # ################################################### import glob import logging import random from fife.extensions import pychan import horizons.globals import horizons.main from horizons.gui.keylisteners import MainListener from horizons.gui.widgets.imagebutton import OkButton from horizons.gui.widgets.pickbeltwidget import CreditsPickbeltWidget from horizons.util.startgameoptions import StartGameOptions from horizons.messaging import GuiAction from horizons.component.ambientsoundcomponent import AmbientSoundComponent from horizons.gui.util import load_uh_widget from horizons.gui.modules.editorstartmenu import EditorStartMenu from horizons.gui.modules import (SingleplayerMenu, MultiplayerMenu, HelpDialog, SelectSavegameDialog, LoadingScreen) from horizons.gui.widgets.fpsdisplay import FPSDisplay from horizons.gui.windows import WindowManager class Gui(object): """This class handles all the out of game menu, like the main and pause menu, etc. """ log = logging.getLogger("gui") def __init__(self): self.mainlistener = MainListener(self) self.current = None # currently active window self.session = None self.windows = WindowManager() # temporary aliases for compatibility with rest of the code self.show_dialog = self.windows.show_dialog self.show_popup = self.windows.show_popup self.show_error_popup = self.windows.show_error_popup self.__pause_displayed = False self._background = pychan.Icon(image=self._get_random_background(), position_technique='center:center') self._background.show() self.subscribe() self.singleplayermenu = SingleplayerMenu(self) self.multiplayermenu = MultiplayerMenu(self) self.help_dialog = HelpDialog(self) self.selectsavegame_dialog = SelectSavegameDialog(self) self.show_select_savegame = self.selectsavegame_dialog.show_select_savegame self.loadingscreen = LoadingScreen() self.mainmenu = load_uh_widget('mainmenu.xml', 'menu') self.mainmenu.mapEvents({ 'single_button': self.singleplayermenu.show, 'single_label' : self.singleplayermenu.show, 'multi_button': self.multiplayermenu.show, 'multi_label' : self.multiplayermenu.show, 'settings_button': self.show_settings, 'settings_label' : self.show_settings, 'help_button': self.on_help, 'help_label' : self.on_help, 'quit_button': self.show_quit, 'quit_label' : self.show_quit, 'editor_button': self.show_editor_start_menu, 'editor_label' : self.show_editor_start_menu, 'credits_button': self.show_credits, 'credits_label' : self.show_credits, 'load_button': self.load_game, 'load_label' : self.load_game, 'changeBackground' : self.randomize_background }) self.fps_display = FPSDisplay() def subscribe(self): """Subscribe to the necessary messages.""" GuiAction.subscribe(self._on_gui_action) def unsubscribe(self): GuiAction.unsubscribe(self._on_gui_action) # basic menu widgets def show_main(self): """Shows the main menu """ if not self._background.isVisible(): self._background.show() self.hide() self.on_escape = self.show_quit self.current = self.mainmenu self.current.show() def load_game(self): saved_game = self.show_select_savegame(mode='load') if saved_game is None: return False # user aborted dialog self.show_loading_screen() options = StartGameOptions(saved_game) horizons.main.start_singleplayer(options) return True # what happens on button clicks def save_game(self): """Wrapper for saving for separating gui messages from save logic """ success = self.session.save() if not success: # There was a problem during the 'save game' procedure. self.show_popup(_('Error'), _('Failed to save.')) def show_settings(self): """Displays settings gui derived from the FIFE settings module.""" horizons.globals.fife.show_settings() def on_help(self): self.help_dialog.toggle() def show_quit(self): """Shows the quit dialog. Closes the game unless the dialog is cancelled.""" message = _("Are you sure you want to quit Unknown Horizons?") if self.show_popup(_("Quit Game"), message, show_cancel_button=True): horizons.main.quit() def quit_session(self, force=False): """Quits the current session. Usually returns to main menu afterwards. @param force: whether to ask for confirmation""" message = _("Are you sure you want to abort the running session?") if force or self.show_popup(_("Quit Session"), message, show_cancel_button=True): if self.current is not None: # this can be None if not called from gui (e.g. scenario finished) self.hide() self.current = None if self.session is not None: self.session.end() self.session = None self.show_main() return True else: return False def show_credits(self): """Shows the credits dialog. """ widget = CreditsPickbeltWidget().get_widget() self.show_dialog(widget, {OkButton.DEFAULT_NAME: True}) # display def on_escape(self): pass def show(self): self.log.debug("Gui: showing current: %s", self.current) if self.current is not None: self.current.show() def hide(self): self.log.debug("Gui: hiding current: %s", self.current) if self.current is not None: self.current.hide() self.windows.hide_modal_background() def hide_all(self): self.hide() self._background.hide() def is_visible(self): return self.current is not None and self.current.isVisible() def show_loading_screen(self): self.hide() self.current = self.loadingscreen self.current.show() def randomize_background(self): """Randomly select a background image to use. This function is triggered by change background button from main menu.""" self._background.image = self._get_random_background() def _get_random_background(self): """Randomly select a background image to use through out the game menu.""" available_images = glob.glob('content/gui/images/background/mainmenu/bg_*.png') #get latest background latest_background = horizons.globals.fife.get_uh_setting("LatestBackground") #if there is a latest background then remove it from available list if latest_background is not None: available_images.remove(latest_background) background_choice = random.choice(available_images) #save current background choice horizons.globals.fife.set_uh_setting("LatestBackground", background_choice) horizons.globals.fife.save_settings() return background_choice def _on_gui_action(self, msg): AmbientSoundComponent.play_special('click') def show_editor_start_menu(self, from_main_menu=True): editor_start_menu = EditorStartMenu(self, from_main_menu) self.hide() self.current = editor_start_menu self.current.show() return True
UTF-8
Python
false
false
2,012
4,647,154,647,771
4028ca7bc91bd661fc05c5361923eb4e1d90b6a9
4f1db4a7fd7e039ac071169b18807555010c6aaf
/i3situation/plugins/top.py
175c646ef7552154eb1f907c8ef281786723a12b
[ "GPL-1.0-or-later", "LGPL-2.1-or-later", "GPL-3.0-or-later", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-only" ]
non_permissive
spacelis/i3situation
https://github.com/spacelis/i3situation
beb6d703fb2499d23e2914e0638d61f975533470
c217eee7816e469a9fc5e2655d9643f78468a516
refs/heads/master
2021-01-14T13:40:17.552076
2014-06-14T10:20:58
2014-06-14T10:20:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A plugin showing available memory. File: mem.py Author: SpaceLis Email: [email protected] GitHub: http://github.com/spacelis Description: This plugin uses /proc/meminfo as the source. The free% = (MemFree + Cached + Buffers) / MemTotal * 100 """ from os import listdir from os.path import join as pjoin from collections import Counter import re from i3situation.plugins._utils import colored from i3situation.plugins._plugin import Plugin __all__ = 'TopPlugin' PID = re.compile(r'\d+') def top(prev=None): """ return the commanline of the top running process. """ pcs = [p for p in listdir('/proc/') if PID.match(p)] utimes = Counter() for p in pcs: try: with open(pjoin('/proc', p, 'stat')) as f: s = f.read().strip().split() utimes['%s %s' % (p, s[1])] = int(s[13]) except FileNotFoundError: pass if not prev: top_pc, _ = utimes.most_common(1)[0] else: top_pc, _ = (utimes - prev).most_common(1)[0] #with open(pjoin('/proc', top_pc[0], 'cmdline')) as f: #top_cmd = f.read() pid, cmd = top_pc.split() return int(pid), cmd[1:-1], utimes class TopPlugin(Plugin): """ A plugin for mem usage. """ def __init__(self, config): self.options = {'interval': 5, 'menu_command': ''} self.prev = None super(TopPlugin, self).__init__(config) def main(self): """ return the formated status. """ pid, cmd, self.prev = top(self.prev) full = 'TOP: %6d %8s' % (pid, cmd[:8]) short = 'TOP: %6d %3s' % (pid, cmd[:3]) #self.output_options['color'] = colored(p) return self.output(full, short) def on_click(self, event): if self.options['menu_command'] != '': self.display_dzen(event)
UTF-8
Python
false
false
2,014
6,906,307,413,919
3296a6861cc333822ee7c9b7ad3ad340c3dea236
2b409a23a3fa6ba70dd98c4c604237330ff77ead
/gatekeeper/mail/listeners.py
a7c6733818d67916c4f3b79ab7888364e192d79f
[]
no_license
taobluesky/gatekeeper
https://github.com/taobluesky/gatekeeper
fdcdeb352a66aa20c4676ce02f9ad0fce23d283a
eac91828b466720f24024173ec73d37572e3bd42
refs/heads/master
2021-01-23T13:30:06.594316
2013-08-13T13:01:10
2013-08-13T13:01:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- #gk imports from gatekeeper.core.signals import app_created_signal from gatekeeper.core.signals import app_signed_signal from gatekeeper.mail import utils as mail_utils def app_created_listener(sender,**kwargs): """ 監聽申請單創建動作 """ request = sender.get("request") app = sender.get("app") mail_utils.send_creted_app_mail(request,app) def app_signed_listener(sender,**kwargs): """ 監聽申請單簽核動作 """ request = sender.get("request") app = sender.get("app") mail_utils.send_signed_app_mail(request,app) app_created_signal.connect(app_created_listener) app_signed_signal.connect(app_signed_listener)
UTF-8
Python
false
false
2,013
11,304,353,963,471
99b5649da6158b3df0a383f960dae2f8f890ecb3
286fb0c7ae765f55a85c027a88214249d0b5bebe
/pyppet/server_api.py
bac0ebcdbe70638e7543f5b27f90fc97acaa2a84
[ "BSD-3-Clause" ]
permissive
antwan2000arp/pyppet
https://github.com/antwan2000arp/pyppet
e66aa87d5f87dbbbc2b927e74fa2bb9cfd97d9c4
a6a7dbe3be49d3492f85417d0b1a08ff5cadea70
refs/heads/master
2016-08-12T04:33:08.432568
2013-07-18T23:16:45
2013-07-18T23:16:45
52,249,482
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Simple Server API with Users # Copyright Brett Hartshorn 2012-2013 # License: "New" BSD import os, sys, ctypes, time, json, struct, inspect import random import bpy ## make sure we can import and load data from same directory ## SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) if SCRIPT_DIR not in sys.path: sys.path.append( SCRIPT_DIR ) import core import Server import simple_action_api import api_gen from api_gen import BlenderProxy, UserProxy, Animation, Animations from websocket import websocksimplify class UserServer( websocksimplify.WebSocketServer ): pass class BlenderServer( core.BlenderHack ): def start_server(self): self.websocket_server = s = UserServer() host = Server.HOST_NAME port = 8080 for arg in sys.argv: if arg.startswith('--port='): port = int( arg.split('=')[-1] ) if arg.startswith('--ip='): a = arg.split('=') if len(a) == 2 and a[-1]: host = a[-1] Server.set_host_and_port( host, port ) s.initialize( listen_host=host, listen_port=port, read_callback=self.on_websocket_read_update, write_callback=self.on_websocket_write_update, new_client_callback=self.on_new_client, ) lsock = s.create_listener_socket() s.start_listener_thread() def on_new_client(self, sock): addr = sock.getpeername() print('[on new client]', addr) if addr in Server.GameManager.clients: print('[websocket] RELOADING CLIENT:', addr ) raise SystemExit else: print('_'*80) print('[websocket] NEW CLIENT:', addr ) Server.GameManager.add_player( addr, websocket=sock ) def on_websocket_read_update(self, sock, frames): ''' protocol: if first byte is null, then the next 24 bytes is the camera location as packed floats, if its a single byte then its a keystroke, if it begins with "{" and ends with "}" then its a json message/request, otherwise it is part of the generated websocket api. ''' player = Server.GameManager.get_player_by_socket( sock ) if not player: return addr = player.address for frame in frames: if not frame: continue if frame[0] == 0: frame = frame[1:] if len(frame)!=24: print(frame) continue x1,y1,z1, x2,y2,z2 = struct.unpack('<ffffff', frame) #print(x1,y1,z1) if addr in Server.GameManager.clients: player = Server.GameManager.clients[ addr ] player.set_focal_point( (x2,y2,z2) ) player.set_location( (x1,y1,z1) ) # callbacks get triggered else: print('[websocket ERROR] client address not in GameManager.clients') raise RuntimeError elif len(frame) == 1: ## TODO unicode 2bytes print(frame) print( frame.decode('utf-8') ) elif len(frame) > 2 and chr(frame[0]) == '{' and chr(frame[-1]) == '}': jmsg = json.loads( frame.decode('utf-8') ) print('client sent json data', jmsg) player.on_websocket_json_message( jmsg ) else: print('doing custom action...', frame) ## action api ## code = chr( frame[0] ) action = player.new_action(code, frame[1:]) ## logic here can check action before doing it. if action: #assert action.calling_object action.do() _bps = 0 _bps_start = None _debug_kbps = True def on_websocket_write_update(self, sock): player = Server.GameManager.get_player_by_socket( sock ) msg = player.create_message_stream( bpy.context ) if msg is None: #return None return bytes(0) rawbytes = json.dumps( msg ).encode('utf-8') if self._debug_kbps: now = time.time() self._bps += len( rawbytes ) #print('frame Kbytes', len(rawbytes)/1024 ) if self._bps_start is None or now-self._bps_start > 1.0: print('kilobytes per second', self._bps/1024) self._bps_start = now self._bps = 0 return rawbytes def setup_websocket_callback_api(self, api): simple_action_api.create_callback_api( api ) class App( BlenderServer ): def __init__(self, api): print('init server app') self.setup_server(api) def setup_server(self, api): api.update( api_gen.get_decorated() ) self.setup_websocket_callback_api(api) self.setup_blender_hack( bpy.context, use_gtk=False, headless=True ) print('blender hack setup ok') Server.set_api( self ) print('custom api set') def mainloop_poll(self, now, dt): ## for subclasses to overload ## time.sleep(0.01) def mainloop(self): print('enter main') drops = 0 self._mainloop_prev_time = time.time() self.active = True while self.active: now = time.time() dt = 1.0 / 30.0 if now - self._mainloop_prev_time: dt = 1.0 / ( now - self._mainloop_prev_time ) self._mainloop_prev_time = now #print('FPS', dt) for ob in bpy.data.objects: ## this is threadsafe? #ob.update_tag( {'OBJECT', 'DATA', 'TIME'} ) ## super slow ob.update_tag( {'OBJECT'} ) api_gen.AnimationManager.tick() bpy.context.scene.update() ## required for headless mode fully_updated = self.update_blender() self.mainloop_poll(now, dt) def default_click_callback( user=UserProxy, ob=BlenderProxy ): print('select callback', user, ob) w = api_gen.get_wrapped_objects()[ ob ] view = w( user ) view['selected'] = time.time() ## allow multiple selections, the server can filter to most recent to. if 0: view['location'] = list( ob.location.to_tuple() ) #view['location'] = Animation( seconds=3.0, y=-5.0) # TODO relative and absolute view['location'] = Animations( Animation( seconds=3.0, y=-5.0), Animation( seconds=3.0, y=5.0), Animation( seconds=3.0, z=1.0), Animation( seconds=3.0, z=-1.0), ) view['rotation_euler'] = list( ob.rotation_euler ) view['rotation_euler'] = Animations( Animation( seconds=3.0, x=-5.0), Animation( seconds=3.0, x=5.0), ) view().on_click = api_gen.get_callback( 'next1') def next1( user=UserProxy, ob=BlenderProxy ): print('next click callback1') w = api_gen.get_wrapped_objects()[ ob ] view = w( user ) view['color'] = [1,1,0, 1] view().on_click = api_gen.get_callback( 'next2') def next2( user=UserProxy, ob=BlenderProxy ): print('next click callback2') w = api_gen.get_wrapped_objects()[ ob ] view = w( user ) view['color'] = [0,1,1, 1] view().on_click = api_gen.get_callback( 'next3') def next3( user=UserProxy, ob=BlenderProxy ): print('next click callback3') w = api_gen.get_wrapped_objects()[ ob ] view = w( user ) view['color'] = Animations( Animation( seconds=2.0, x=0.5, y=0.5, z=0.1), Animation( seconds=2.0, x=1.0, y=0.1, z=0.5), Animation( seconds=2.0, z=1.0), Animation( seconds=2.0, z=-1.0), ) #view[ '.modifiers["Bevel"].width' ] = 0.5 # this style is simple ## TODO mesh streaming so this can be tested, support bevel in dump_collada def default_input_callback( user=UserProxy, ob=BlenderProxy, input_string=ctypes.c_char_p ): print( 'default INPUT CALLBACK', user, ob, input_string ) #if ob.name == 'login': # if 'login.input' not in bpy.data.objects: # a = bpy.data.objects.new( # name="[data] %s"%name, # object_data= a.data # ) # bpy.context.scene.objects.link( a ) # a.parent = ob w = api_gen.get_wrapped_objects()[ ob ] view = w( user ) API = { 'default_click': default_click_callback, 'default_input' : default_input_callback, 'next1' : next1, 'next2' : next2, 'next3' : next3, } if __name__ == '__main__': app = App( API ) app.start_server() print('-----main loop------') app.mainloop()
UTF-8
Python
false
false
2,013
5,454,608,476,239
7f128cfb32134d2abf8df7c5bdf85b355345cf56
0ec046d7ad5b66bc14d5afaac178466f9f8e7073
/version.py
0469596291768746d0f03a735fb4d4bf2792517f
[]
no_license
MarsStirner/vesta
https://github.com/MarsStirner/vesta
b7e7b9da9b6028acf1ea0cd7d6088037e95fef93
891b26ddfddfaebe145cf4c4a220fdb8c9f74fe0
refs/heads/master
2020-12-03T00:34:12.420995
2014-10-01T08:21:37
2014-10-01T08:21:37
96,043,027
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from datetime import datetime version = u'0.2.25' last_change_date = datetime(year=2014, month=10, day=1, hour=12,)
UTF-8
Python
false
false
2,014
4,896,262,723,753
8b692d4a6aa9fe04b1f21e583b8f3c5f3cfb6952
9b3fd9ef0aa8a88fbe067528f0dbabe20f2c5a21
/abfgp-2.f/graphAbgp/__init__.py
ec529785280ecb365c676f2d54f4247454210562
[]
no_license
IanReid/ABFGP
https://github.com/IanReid/ABFGP
cb0d5c6e01824323bc0f6bc076d5bb1a919556fd
c6be8000c8279a5d69ece3f26a3702b8fa6b3a9d
refs/heads/master
2021-01-17T04:52:42.983716
2014-03-14T20:52:56
2014-03-14T20:52:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Copyright (c) 2008 Ate van der Burgt <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """ graph classes for Aligment Based Gene Predictions All classes inherit from graphPlus, a Plus-version of the python-graph package of Pedro Matiello class BasalSiteAlignmentFunctions class BasalPSSMObjectGraphFunctions class OrganismGraph(graphPlus.graphPlus) class CodingBlockGraph(OrganismGraph) class AlignedStopCodonGraph(OrganismGraph) class AlignedStartCodonGraph(OrganismGraph,BasalSiteAlignmentFunctions) class AlignedPSSMTSSGraph(AlignedStartCodonGraph,BasalSiteAlignmentFunctions,BasalPSSMObjectGraph) class AlignedSpliceSiteGraph(OrganismGraph,BasalSiteAlignmentFunctions,BasalPSSMObjectGraph) class AlignedDonorSiteGraph(AlignedSpliceSiteGraph) class AlignedAcceptorSiteGraph(AlignedSpliceSiteGraph) """ # Module metadata __authors__ = "Ate van der Burgt" __license__ = "MIT" # Imports from graph_organism import OrganismGraph from graph_genetree import GeneTreeGraph from graph_pacbpcollection import PacbpCollectionGraph from graph_codingblock import CodingBlockGraph from graph_inwardspointingcodingblock import InwardsPointingCodingBlockGraph from graph_lowsimilaritycodingblock import LowSimilarityRegionCodingBlockGraph from graph_genestructure import GenestructureOfCodingBlockGraphs from graph_pssmcollections import * from graph_alignedsites import * from graph_exoncollection import ExonCollectionGraph #from conversion import * ###from sitealignment import BasalSiteAlignmentFunctions ###from pssmobjects import BasalPSSMObjectGraphFunctions ###from tcodedata import GraphTcodeDataAccesFunctions ###from codingblockcollectionharvesting import * ###from codingblockprinting import * ###import codingblocksplitting
UTF-8
Python
false
false
2,014
2,147,483,665,127
bfda2de2d4949082c7bd89b75bb85ad0c7986b51
274291ea94c615163ca0c9a20534574ac26969ae
/labyrinth_par/src/rect_cl.py
990bc1593addb42bbeb68f222f280ea9484972e6
[]
no_license
alfredoivan/paradigma_laberinto
https://github.com/alfredoivan/paradigma_laberinto
9da71b180cd0f42758b5218af2973201caa7bb6b
a04370f9e8019ee8aa6ed1c51b237e85fe02482b
refs/heads/master
2020-06-07T23:36:31.040597
2014-12-13T23:21:09
2014-12-13T23:21:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- #Rectangle class: to handle areas and point contains easily and cleanly. class Rectangle: def __init__(self, xinicial = 1, xfinal = 1, yinicial=1, yfinal=1): self.__xinicial = xinicial self.__xfinal = xfinal self.__yinicial = yinicial self.__yfinal = yfinal ##Setters to float ##Getters #def get_length(self): # return self.__length #def get_width(self): # return self.__width ##Get perimeter and area def contains(self,xobj=1, yobj=1): #contains a given point if (xobj > self.__xinicial and xobj < self.__xfinal): if (yobj > self.__yinicial and yobj < self.__yfinal): return True return False #def area(self): # return self.__length * self.__width
UTF-8
Python
false
false
2,014
19,344,532,742,104
d88f1652b65ae9433498a53c974b70d1af338c04
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/template_under_construction/sandbox/$template_library$/libs/$template_library$/build/xcodeide.py
aac40c9f31b0b8ca6e73a60344f97a21a132339d
[ "BSL-1.0" ]
permissive
ttyang/sandbox
https://github.com/ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
false
2023-03-20T11:52:19
2013-10-11T03:08:51
2021-11-08T18:25:39
2017-05-18T11:25:33
703,658
1
1
0
C++
false
false
# template script if template.options.get_boolean('xcodeide', False): log.message('Processing Xcode IDE template.') template.ignore('$template_library$/libs/$template_library$/build/xcodeide/$template_library$.xcodeproj/xcode_elements.py') template.ignore('$template_library$/libs/$template_library$/build/xcodeide/$template_library$.xcodeproj/xcode_elements.pyc') else: template.ignore_subdirectory('xcodeide')
UTF-8
Python
false
false
2,013
3,015,067,048,848
f73f069fd43a26691430baea254c1775018ee5c8
de230f2156f270a8022fef2a2e2a8f6d8e9bdf10
/draw.py
1c260e5e6537105dda65f5b4ceff12e71c134d30
[]
no_license
crane-may/FlappyBirdBot
https://github.com/crane-may/FlappyBirdBot
2e35cfea1424e3a4e8c63694b9e768b4a421de27
77c33d101254ac71af4c8af207ad5c3f6ab54a9d
refs/heads/master
2016-09-06T18:33:47.569059
2014-04-05T23:43:41
2014-04-05T23:43:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import cv2 from PIL import Image, ImageTk, ImageDraw def c(color): return (color[2],color[1],color[0]) def d(p): return (int(p[0]),int(p[1])) def cvImg(img, path): if isinstance(img, ImageDraw.ImageDraw): return cv2.imread(path) else: return img def start(img): if isinstance(img, Image.Image): return ImageDraw.Draw(img) else: return img def end(img): if isinstance(img, ImageDraw.ImageDraw): del img def line(img, start, end, color=(0,0,0), width=1): if isinstance(img, ImageDraw.ImageDraw): img.line(start + end, fill=color, width=width) else: cv2.line(img, d(start), d(end), c(color), width) def point(img, pos, color=(0,0,0), r=4): if isinstance(img, ImageDraw.ImageDraw): img.ellipse((pos[0]-r, pos[1]-r, pos[0]+r, pos[1]+r), fill=color) else: cv2.circle(img,d(pos),r/2,c(color),r) def box(img, p1, p2, color=(0,0,0), width=3): if isinstance(img, ImageDraw.ImageDraw): img.rectangle(p1+p2, fill=color,width=3) else: cv2.rectangle(img,d(p1),d(p2),c(color),width)
UTF-8
Python
false
false
2,014
4,870,492,951,305
6aeaec2bc50e0fdaadb2b673f7d205405b52bbfb
c41a82fa29959c323ae24b1ab69feeb12dafd5ac
/tests/test_memory.py
2d9116ea073ef16e5b9bb5c77ed95e9e2dfac679
[ "MIT", "Apache-2.0", "LGPL-2.0-or-later", "BSD-3-Clause", "LGPL-2.1-only", "Python-2.0" ]
non_permissive
wangz10/chem-fingerprints
https://github.com/wangz10/chem-fingerprints
b071be5ed8eec2b850c357f250fe0424db641726
44b0a2e0cee9307d302b307255889e09db22184a
refs/heads/master
2016-09-09T17:40:37.271750
2013-06-05T23:33:16
2013-06-05T23:33:16
37,540,879
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This tests check for memory leaks. import unittest2 import resource import sys import array import _chemfp import chemfp def get_memory(): return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss def memory_growth(f, *args, **kwargs): x = f(*args, **kwargs) m1 = get_memory() count = 0 for i in xrange(1000): x = f(*args, **kwargs) m2 = get_memory() if m2 > m1: count += 1 m1 = m2 #print "count", count if count > 900: raise AssertionError("Memory growth in %r (%d/%d)!" % (f, count, 1000)) return x def fps_parse_id_fp(): memory_growth(_chemfp.fps_parse_id_fp, 4, "ABCD\tSpam\n") # I mistakenly used BuildValue("O") instead of BuildValue("N"). # This added an extra refcount to some of the returned strings, # which meant they would never become freed. class TestBuildValueMemoryLeaks(unittest2.TestCase): def test_make_unsorted_aligned_arena_when_aligned(self): s = "SpamAndEggs!" n1 = sys.getrefcount(s) memory_growth(_chemfp.make_unsorted_aligned_arena, s, 4) n2 = sys.getrefcount(s) if n2 > n1 + 10: raise AssertionError("Aligned growth has an extra refcount") def test_make_unsorted_aligned_arena_when_unaligned(self): SIZE = 1024*8 s = "S" * SIZE n1 = sys.getrefcount(s) memory_growth(_chemfp.make_unsorted_aligned_arena, s, SIZE) n2 = sys.getrefcount(s) if n2 > n1 + 10: raise AssertionError("Aligned growth has an extra refcount: %d, %d" % (n1, n2)) def test_align_fingerprint_same_size(self): s = "abcd" n1 = sys.getrefcount(s) memory_growth(_chemfp.align_fingerprint, s, 4, 4) n2 = sys.getrefcount(s) if n2 > n1 + 10: raise AssertionError("align_fingerprint with alignment has extra refcount: %d, %d" % (n1, n2)) def test_align_fingerprint_needs_new_string(self): x = memory_growth(_chemfp.align_fingerprint, "ab", 16, 1024) # I don't know why the above doesn't find the leak. # I can probe the count directly. i = sys.getrefcount(x[2]) if i != 2: raise AssertionError("Unexpected refcount: %d" % (i,)) def test_make_sorted_aligned_arena_trivial(self): ordering = array.array("c", "\0\0\0\0"*16) # space for a ChemFPOrderedPopcount (and extra) popcounts = array.array("c", "\0\0\0\0"*36) # num_fingerprints + 2 (and extra) arena = "BLAH" n1 = sys.getrefcount(arena) memory_growth(_chemfp.make_sorted_aligned_arena, 32, 4, arena, 0, ordering, popcounts, 4) n2 = sys.getrefcount(arena) if n1 != n2: # This one doesn't need "N" because it borrowed the input refcount. raise AssertionError("Borrowed refcount should have been okay.") def test_make_sorted_aligned_arena_already_sorted_and_aligned(self): ordering = array.array("c", "\0\0\0\0"*16) # space for a ChemFPOrderedPopcount (and extra) popcounts = array.array("c", "\0\0\0\0"*36) # num_fingerprints + 2 (and extra) arena = "BDFL" n1 = sys.getrefcount(arena) memory_growth(_chemfp.make_sorted_aligned_arena, 32, 4, arena, 1, ordering, popcounts, 4) n2 = sys.getrefcount(arena) if n1 != n2: # This one doesn't need "N" because it borrowed the input refcount. raise AssertionError("Borrowed refcount should have been okay. %d != %d" % (n1, n2)) def test_make_sorted_aligned_arena_already_sorted_but_not_aligned(self): ordering = array.array("c", "\0\0\0\0"*16) # space for a ChemFPOrderedPopcount (and extra) popcounts = array.array("c", "\0\0\0\0"*40) # num_fingerprints + 2 (and extra) arena = "QWOP" + "\0" * (4096-4) n1 = sys.getrefcount(arena) memory_growth(_chemfp.make_sorted_aligned_arena, 32, 4096, arena, 1, ordering, popcounts, 1024) n2 = sys.getrefcount(arena) if n1 != n2: # This one shouldn't touch the input arena raise AssertionError("Borrowed refcount should have been okay. %d != %d" % (n1, n2)) def test_make_sorted_aligned_arena_when_not_sorted(self): ordering = array.array("c", "\0\0\0\0"*16) # space for a ChemFPOrderedPopcount (and extra) popcounts = array.array("c", "\0\0\0\0"*40) # num_fingerprints + 2 (and extra) arena = "QWON" + "\0" * (4096-4) n1 = sys.getrefcount(arena) memory_growth(_chemfp.make_sorted_aligned_arena, 32, 4, arena, 2, ordering, popcounts, 1024) n2 = sys.getrefcount(arena) if n1 != n2: # This one shouldn't touch the input arena raise AssertionError("Borrowed refcount should have been okay. %d != %d" % (n1, n2)) def test_arena_copy(self): data = "ABCD\t0\n" * 200 from cStringIO import StringIO arena = chemfp.load_fingerprints(StringIO(data)) def make_subarena_copy(): arena[1:].copy() memory_growth(make_subarena_copy) if __name__ == "__main__": unittest2.main()
UTF-8
Python
false
false
2,013
2,207,613,236,831
bdb5897e309d5dee8c2d43da0adcf66646bdee00
44d3fad2eac0712e09075dcaf09a017206aac4e0
/cimri/system/document.py
078cae4f3a3c1b2a6d693176b5379cfaf857dcb7
[]
no_license
matcher/glacier
https://github.com/matcher/glacier
cad73af94acbe42cef77f9409cf16d2611482fb6
bc94f947e1129bcc88d6b7f84cbf2d9b6e4d0b2d
refs/heads/master
2016-09-05T11:38:04.248912
2012-08-14T03:56:35
2012-08-14T03:56:35
5,331,174
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" cimri matcher --------------------------- date: 03.14.2012 author: [email protected] description: ------------ revision history: ----------------- [email protected]: initial version """ import mongoengine from mongoengine import * import datetime import json from cimri.system.config import Config class SerialDoc(object): """ Genel mongodb ve serialization operasyonlarini desteklemesi gereken classlerin icin base class. Bu classi extend eden classlerin Cimri API object parametrelerine denk gelen fieldlari ayni isimle tanimlanmalidir. Cimri API objectlerine denk gelmeyen diger fieldlar _ ile baslamalidir. """ def todict(self): """ Class instance'i dictionary'e cevirir @rtype: dict @return: class insitance fieldlarini iceren dictionary """ obj={} for field in self._fields.keys(): t=type(self._fields[field]) if t==mongoengine.base.ObjectIdField: val=getattr(self,field) obj[field]=None if val==None else str(val) elif t in (mongoengine.fields.StringField, mongoengine.fields.EmailField): val=getattr(self,field) obj[field]=None if val==None else val elif t==mongoengine.fields.DateTimeField: val=getattr(self,field) obj[field]=None if val==None else str(val) elif t==mongoengine.fields.ListField: list=getattr(self,field) obj[field]=None if list==None else [elmt for elmt in list] else: obj[field]=getattr(self,field) return obj def tojson(self): """ Class instance'ini bir json stringe cevirir @rtype: str @return: class instance fieldlarini iceren bir json string """ return json.dumps(self.todict()) def fromjson(self,str): """ Bir json stringe dayanarak yeni bir class instance yaratir @type str: str @param str: class fieldlarini iceren bir json string @rtype: object @return: eger json parse hatasi yoksa bu classin bir instancei, varsa None """ pass @classmethod def connectdb(self): """ MongoDB databaseine baglanir """ # connect(Config.getconfig("API").get("analytics_db")) connect("cimri-matcher") def create(self): """ Objecti mongodb'de yaratir @rtype: object @return: eger operasyon basarili ise self, aksi takdirde None """ try: #connect to db SerialDoc.connectdb() #save self.save() return self except Exception as e: print e return None @classmethod def get(cls,**filters): """ Bu class turunde bir objecti mongodb'den alir @type filters: dict @param filters: mongodb querysini belirleyen parametreler @rtype: object @return: eger operasyon basarili ise bu class turunde bir object, aksi takdirde None """ try: #connect to db SerialDoc.connectdb() #find all obj=cls.objects.get(**filters) return obj except Exception as e: return None @classmethod def list(cls,**filters): """ Bu class turunde birden fazla objecti mongodb'den alir @type filters: dict @param filters: mongodb querysini belirleyen parametreler @rtype: list @return: eger operasyon basarili ise bu class turunde objectleri iceren bir liste, aksi takdirde None """ try: #connect to db SerialDoc.connectdb() #find all list=cls.objects(**filters) return list except Exception as e: return None @classmethod def list_paginated(cls,skip,limit,**filters): """ Bu class turunde birden fazla objecti mongodb'den alir @type skip: int @param skip: ilk alinacak item'in indexi @type limit: int @param limit: alinacak itemlarin sayisi @type filters: dict @param filters: mongodb querysini belirleyen parametreler @rtype: list @return: eger operasyon basarili ise bu class turunde objectleri iceren bir liste, aksi takdirde None """ try: #connect to db SerialDoc.connectdb() #find all list=cls.objects(**filters)[skip:skip+limit] return list except Exception as e: return None
UTF-8
Python
false
false
2,012
10,075,993,287,554
ac475255680a3bc97df40e0e12edef8c6079d527
cba0e811d47bf0e0424e50d5c8aa2c2ce58bc3c9
/accounts/urls.py
0df47c362751ab285faa1f9d94a7ef9f01b7c0cc
[]
no_license
Tommy2002/NtrOrgMgmtSystem
https://github.com/Tommy2002/NtrOrgMgmtSystem
3593cbb2e9ef94ca3b5b211447d847f5c69dd56f
331fb7397e71ac4954876807d7a5b8b4b0cb9436
refs/heads/master
2016-09-10T08:43:31.295861
2014-04-19T20:03:42
2014-04-19T20:03:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#encoding:utf-8 _author__ = 'thomas' from django.conf.urls import patterns, include, url urlpatterns = patterns('django.contrib.auth.views', url(r'logout/$', 'logout', {'next_page': '/'}, name='accounts_logout'), url(r'ĉhange_password/$', 'password_change', {'template_name': 'accounts/password_change_form.html'}, name='accounts_password_change'), url(r'ĉhange_password_done/$', 'password_change_done', {'template_name': 'accounts/password_change_done.hmtl'}, name='accounts_password_change_done') ) urlpatterns += patterns('', url(r'login/$', 'accounts.views.login', {'template_name': 'accounts/login.html'}, name='accounts_login'), url(r'userProfil/(?P<user_id>\d+)/(?P<form_id>\d+)/$', 'accounts.views.edit_userprofil', name='accounts_edit_userprofil'), url(r'loadMenuBar/$', 'accounts.views.load_menu_bar', name='accounts_load_menu_bar') )
UTF-8
Python
false
false
2,014
1,932,735,298,402
088bb266094b41b3dfd271d0f51549c10884d9b3
5102174f4c96a3fee8acda142adfa3c0bab39402
/SEATTLE/ip_addr.py
99796720b2f80cffc6bf94b14cc46f307a75ac75
[]
no_license
xujun10110/PcapIndex
https://github.com/xujun10110/PcapIndex
7f770812ec85e16ec127339d0affbbdb33e5ed39
eec463747f66b1442677abcbfc01b21740c1cfcb
refs/heads/master
2018-04-01T00:22:32.502504
2014-10-17T01:46:52
2014-10-17T01:46:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
S1="10.200.200.145" S2="10.200.200.161" S3="10.200.200.177" #S1 h1="10.200.200.149" h2="10.200.200.150" h3="10.200.200.155" #S2 h4="10.200.200.163" h5="10.200.200.167" h6="10.200.200.172" h7="10.200.200.175" #S3 h8="10.200.200.180" h9="10.200.200.181" h10="10.200.200.182" h11="10.200.200.183"
UTF-8
Python
false
false
2,014
1,821,066,178,053
f2b9a7f03c558bbde23809cb6068923a5beec900
0309c5199ff5ec0ddc168946a093f9621c959c31
/settings.py
cc0337c01a2842be4da53f24ca1c066b34e8f2da
[]
no_license
PSU-AVT/BaseStation
https://github.com/PSU-AVT/BaseStation
2f870dc5882a74574749d5bf2f7997dd36e75560
b26ab5e46a56dcc3235eda1c2e95b506e7c94ca1
refs/heads/master
2020-05-20T05:52:52.008831
2013-07-25T02:56:08
2013-07-25T02:56:08
2,451,888
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
class ControlGw(object): port = 8091 bind_hostname = 'localhost' command_id = { 'SetRoll': 1, 'SetPitch': 2, 'Ping': 3, 'SetY': 4, 'SetYaw': 5, 'Off': 6, 'On': 7, 'SetPGains': 8, 'SetIGains': 9, 'SetDGains': 10, 'SetAttenSetpoint': 11, 'SetLogLevel': 12, 'SetStateSendInterval': 13, 'SetSetpoint': 14, } response_id = { 'Pong': 1 } max_atten = 1.0
UTF-8
Python
false
false
2,013
19,026,705,126,573
0374f0ac23c3076668e21392ce5bfdc57ed5e23b
71828e9d0cfa2f1d7bf47558abb6f04b50b456f1
/experimental/tools/segmentmakertools/SegmentMaker.py
5fb1c7c74cae8fce8415fbb1d84bf5a16566a611
[ "GPL-3.0-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-only", "LGPL-2.1-or-later", "AGPL-3.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-unknown-license-reference" ]
non_permissive
willingc/abjad
https://github.com/willingc/abjad
46e32ac91b70ee204f4aa14e5ae7fd39d49c0ef0
a647f32ced63363ba002bddd4a58648839cfe9a2
refs/heads/master
2020-04-05T19:03:18.828092
2014-03-30T23:08:42
2014-03-30T23:08:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- encoding: utf-8 -*- import abc from abjad.tools import lilypondfiletools from abjad.tools.abctools import AbjadObject class SegmentMaker(AbjadObject): r'''Segment-maker baseclass. ''' ### CLASS VARIABLES ### __slots__ = ( '_name', '_score', ) ### INITIALIZER ### def __init__( self, name=None, ): self._name = name self._score = None ### SPECIAL METHODS ### def __call__(self): r'''Calls segment-maker. Returns LilyPond file. ''' music = self._make_music() assert isinstance(music, lilypondfiletools.LilyPondFile) return music def __eq__(self, expr): r'''Is true if `expr` is a segment-maker with equivalent properties. ''' from abjad.tools import systemtools return systemtools.StorageFormatManager.compare(self, expr) def __hash__(self): r'''Hashes segment-maker. ''' from abjad.tools import systemtools hash_values = systemtools.StorageFormatManager.get_hash_values(self) return hash(hash_values) def __illustrate__(self): r'''Illustrates segment-maker. Returns LilyPond file. ''' return self() ### PUBLIC PROPERTIES ### @property def name(self): r'''Gets segment name. Returns string. ''' return self._name @property def score(self): r'''Gets segment score. Returns score. ''' return self._score
UTF-8
Python
false
false
2,014
18,803,366,845,272
600cf6d06a923a2bc64886e6c332b6970b2fa42e
67c4361e24f264354de71ed65e558d1882d0440b
/volshell/windows/volshell.py
fe60565f90156325fa39cc7b76118bc1b1ca3729
[ "GPL-2.0-or-later" ]
non_permissive
StrategicC/volatility
https://github.com/StrategicC/volatility
6efa510f7e336a160987a4eefbc5d6441021da09
eef6c3b21524a91c91758609526e8c41b34a5cfe
refs/heads/master
2021-01-21T18:15:25.048618
2013-08-29T17:02:38
2013-08-29T17:02:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Volatility # Copyright (C) 2008 Volatile Systems # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # import volatility.win32.tasks as win32 import volatility.plugins.volshell as volshell class WinVolshell(volshell.BaseVolshell): """Shell in the (Windows) memory image""" def getPidList(self): return win32.pslist(self.addrspace) def getPid(self, proc): return proc.UniqueProcessId def getPPid(self, proc): return proc.InheritedFromUniqueProcessId.v() def getImageName(self, proc): return proc.ImageFileName def getDTB(self, proc): return proc.Pcb.DirectoryTableBase def ps(self, render=True, table_data=False, pid=None): """Print a process listing. Prints a process listing with PID, PPID, image name, and offset. """ if pid: if type(pid).__name__ == 'int': pid = str(pid) if type(pid).__name__ == 'list': if len(pid) == 0: pid = None else: pid = ",".join([ str(p) for p in pid ]) return self.pslist(render=render, table_data=table_data, pid=pid) def list_entry(self, head, objname, offset = -1, fieldname = None, forward = True): """Traverse a _LIST_ENTRY. Traverses a _LIST_ENTRY starting at virtual address head made up of objects of type objname. The value of offset should be set to the offset of the _LIST_ENTRY within the desired object. """ vm = self.proc.get_process_address_space() seen = set() if fieldname: offset = vm.profile.get_obj_offset(objname, fieldname) lst = obj.Object("_LIST_ENTRY", head, vm) seen.add(lst) if not lst.is_valid(): return while True: if forward: lst = lst.Flink else: lst = lst.Blink if not lst.is_valid(): return if lst in seen: break else: seen.add(lst) nobj = obj.Object(objname, lst.obj_offset - offset, vm) yield nobj
UTF-8
Python
false
false
2,013
2,508,260,928,838
592a9b9f3e67b55778080b9b6a09fbec53bef93d
358d2a21e325d43195f07fc769f1aac2fb0154fa
/shootingStars.py
e7787caccbb3c23c6595a312ffcd2090d5814792
[]
no_license
steviedupree14/CSCI220
https://github.com/steviedupree14/CSCI220
a4d1f75ddf0029b70f3d7075f4a75e67bd7f6292
0e10dac8c82eb15dd4c6a4fe253eefb64d00fbe5
refs/heads/master
2020-05-16T14:30:03.285681
2014-04-11T00:10:04
2014-04-11T00:10:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Name: Christopher Moore # shootingStars.py # # Problem: This program creates a greeting card displaying a house and shooting stars. # # Certification of Authenticity: # # I certify that this lab is entirely my own work. from graphics import * from time import * def main(): ## Creates window and background width = 800 height = 800 win = GraphWin("Shooting Stars",width,height) win.setBackground("green") message = Text(Point(width/2, height-10), "") message.draw(win) ## Creates blue sky (rectangle called sky) sky = Rectangle(Point(0,0), Point(800,600)) sky.draw(win) sky.setFill("blue") ## Creates white house (rectangle called house) house = Rectangle(Point(300,400), Point(500,600)) house.draw(win) house.setFill("white") ## Creates brown roof (polygon called roof) roof = Polygon(Point(300,400), Point(400,300), Point(500,400)) roof.draw(win) roof.setFill("brown") ## Creates red door (rectangle called door) door = Rectangle(Point(380,550), Point(420,600)) door.draw(win) door.setFill("red") ## Creates black window (rectangle called window1) window1 = Rectangle(Point(340,440), Point(360,460)) window1.draw(win) window1.setFill("black") ## Creates clone of window1 and shifts 100 pixels to the right (window2) window2 = window1.clone() window2.move(100,0) window2.draw(win) sleep(2) ## Short pause ## Creates star and clones (star1, star2, star3, star4, star5) star1 = Polygon(Point(10,0), Point(12.5,7.5), Point(20,10), Point(12.5,12.5), Point(10,20), Point(7.5,12.5), Point(0,10), Point(7.5,7.5)) star1.draw(win) star1.setFill("yellow") star2 = star1.clone() star3 = star1.clone() star4 = star1.clone() star5 = star1.clone() ## Animates first star for i in range(25): star1.move(20,3) sleep(0.05) star1.undraw() ## Removes star sleep(1) ## Short pause ## Draws next star clone and animates star2.move(50,0) star2.draw(win) for i in range(25): star2.move(20,6) sleep(0.03) star2.undraw() ## Removes star sleep(1) ## Short pause ## Draws next star clone and animates star3.move(100,0) star3.draw(win) for i in range(25): star3.move(20,3) sleep(0.05) star3.undraw() ## Removes star sleep(1) ## Short pause ## Draws next star clone and animates star4.move(150,0) star4.draw(win) for i in range(25): star4.move(20,9) sleep(0.02) star4.undraw() ## Removes star sleep(1) ## Short pause ## Draws next star clone and animates star5.move(200,0) star5.draw(win) for i in range(25): star5.move(20,3) sleep(0.05) star5.undraw() ## Removes star ## Prints greeting message.setSize(28) message.setFace("arial") message.setTextColor("white") message.setText("HAPPY SPRING!") sleep(3) ## Short pause ## Closing instructions message.setSize(12) message.setFace("times roman") message.setTextColor("black") message.setText("Click to Quit") win.getMouse() win.close() main()
UTF-8
Python
false
false
2,014
5,394,478,936,038
21b2825e5b4f701eddf422b1a85cf580e313a9e1
af39ebd5c22818111c117691316902e90a1a592c
/sentiment/comments/classifier/vectorization.py
d8ec66085c81461f57e0a50d36817643e3876d37
[ "BSD-3-Clause" ]
permissive
Ernesttt/sentiment-analysis
https://github.com/Ernesttt/sentiment-analysis
ae351e0662b5ce0a393eaf2ffb92a398bfabf9eb
60b8924457d35228d5a752d99dd6e786fb49ce55
refs/heads/master
2020-04-04T06:58:24.700614
2014-09-02T16:26:15
2014-09-02T16:26:15
21,505,644
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import codecs from metrics_reduced import SpanishTools from pattern.vector import Document from constants import * # See constants.py to check variables used in this file import time #globals spanish_tools = SpanishTools() class VectorQuantization: """ Creates vector of features """ def morphosyntactic_vector(self, comment): comment_tagged = spanish_tools.pos_tagging_infinitive(comment) custom_dict = {} document = None # Constructing vector for i in range(50): if len(comment_tagged) > i and len(comment_tagged) <= 50: word = spanish_tools.remove_accents(comment_tagged[i].split(':')[0]) tag = comment_tagged[i].split(':')[1] # Adjectives if tag in adjectives: if word in positive_words: custom_dict[feature_list[3*i]] = 0.99 custom_dict[feature_list[3*i + 1]] = 0.99 custom_dict[feature_list[3*i + 2]] = 0.99 elif word in negative_words: custom_dict[feature_list[3*i]] = 0.01 custom_dict[feature_list[3*i + 1]] = 0.01 custom_dict[feature_list[3*i + 2]] = 0.5 else: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.5 # Adverbs elif tag in (adverbs or determiners or conjunctions): if word in positive_words: custom_dict[feature_list[3*i]] = 0.99 custom_dict[feature_list[3*i + 1]] = 0.99 custom_dict[feature_list[3*i + 2]] = 0.5 elif word in negative_words: custom_dict[feature_list[3*i]] = 0.01 custom_dict[feature_list[3*i + 1]] = 0.01 custom_dict[feature_list[3*i + 2]] = 0.01 else: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.5 # Verbs elif tag in verbs: if word in positive_words: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.99 custom_dict[feature_list[3*i + 2]] = 0.99 elif word in negative_words: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.01 custom_dict[feature_list[3*i + 2]] = 0.01 else: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.5 # Nouns elif tag in nouns: if word in positive_words: custom_dict[feature_list[3*i]] = 0.99 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.99 elif word in negative_words: custom_dict[feature_list[3*i]] = 0.01 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.01 else: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.5 # Other categories else: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.5 # Dummy elif len(comment_tagged) <= 50: custom_dict[feature_list[3*i]] = 0.5 custom_dict[feature_list[3*i + 1]] = 0.5 custom_dict[feature_list[3*i + 2]] = 0.5 # - if len(custom_dict) > 0: document = Document(custom_dict) return document def bigram_vector(self, comment): document = None dictionary_features = dict.fromkeys(bigram_feature_list, 0) list_elements = spanish_tools.n_grams(comment, 2) for e in list_elements: if dictionary_features.has_key(e): dictionary_features[e] = dictionary_features[e] + 1 document = Document(dictionary_features) return document
UTF-8
Python
false
false
2,014