repo_name
stringclasses
400 values
branch_name
stringclasses
4 values
file_content
stringlengths
16
72.5k
language
stringclasses
1 value
num_lines
int64
1
1.66k
avg_line_length
float64
6
85
max_line_length
int64
9
949
path
stringlengths
5
103
alphanum_fraction
float64
0.29
0.89
alpha_fraction
float64
0.27
0.89
jessehylton/Podrum
refs/heads/master
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. """ from abc import ABCMeta, abstractmethod from podrum.nbt.tag.ByteArrayTag import ByteArrayTag from podrum.nbt.tag.ByteTag import ByteTag from podrum.nbt.tag.CompoundTag import CompoundTag from podrum.nbt.tag.DoubleTag import DoubleTag from podrum.nbt.tag.FloatTag import FloatTag from podrum.nbt.tag.IntArrayTag import IntArrayTag from podrum.nbt.tag.IntTag import IntTag from podrum.nbt.tag.ListTag import ListTag from podrum.nbt.tag.LongArrayTag import LongArrayTag from podrum.nbt.tag.LongTag import LongTag from podrum.nbt.tag.NamedTag import NamedTag from podrum.nbt.tag.ShortTag import ShortTag from podrum.nbt.tag.StringTag import StringTag class NBT: __metaclass__ = ABCMeta TAG_End = 0 TAG_Byte = 1 TAG_Short = 2 TAG_Int = 3 TAG_Long = 4 TAG_Float = 5 TAG_Double = 6 TAG_ByteArray = 7 TAG_String = 8 TAG_List = 9 TAG_COMPOUND = 10 TAG_IntArray = 11 TAG_LongArray = 12 @staticmethod def createTag(type: int) -> NamedTag: if type == NBT.TAG_Byte: return ByteTag() elif type == NBT.TAG_Short: return ShortTag() elif type == NBT.TAG_Int: return IntTag() elif type == NBT.TAG_Long: return LongTag() elif type == NBT.TAG_Float: return FloatTag() elif type == NBT.TAG_Double: return DoubleTag() elif type == NBT.TAG_ByteArray: return ByteArrayTag() elif type == NBT.TAG_String: return StringTag() elif type == NBT.TAG_List: return ListTag() elif type == NBT.TAG_Compound: return CompoundTag() elif type == NBT.TAG_IntArray: return IntArrayTag() elif type == NBT.TAG_LongArray: return LongArrayTag() else: raise ValueError("Unknown NBT tag type " + str(type))
Python
74
30.716217
77
/src/podrum/nbt/NBT.py
0.592295
0.585097
jessehylton/Podrum
refs/heads/master
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. """ import decimal class bcmath: @staticmethod def bcmul(num1, num2, scale=None): if scale != None: decimal.getcontext().prec = scale result = decimal.Decimal(num1) * decimal.Decimal(num2) return int(result) @staticmethod def bcdiv(num1, num2, scale=None): if scale != None: decimal.getcontext().prec = scale result = decimal.Decimal(num1) / decimal.Decimal(num2) return int(result) @staticmethod def bcadd(num1, num2, scale=None): if scale != None: decimal.getcontext().prec = scale result = decimal.Decimal(num1) + decimal.Decimal(num2) return int(result) @staticmethod def bcsub(num1, num2, scale=None): if scale != None: decimal.getcontext().prec = scale result = decimal.Decimal(num1) - decimal.Decimal(num2) return int(result) @staticmethod def bccomp(num1, num2): result = (int(num1) > int(num2)) - (int(num1) < int(num2)) return int(result) @staticmethod def bcmod(num1, num2): result = int(num1) % int(num2) return int(result) @staticmethod def bcpow(num1, num2): result = int(num1) ** int(num2) return int(result) @staticmethod def bcpowmod(num1, num2, mod): result = pow(num1, num2, mod) return int(result) @staticmethod def bcscale(scale): result = decimal.getcontext().prec = scale return int(result) @staticmethod def bcsqrt(num): result = math.sqrt(num) return int(result)
Python
72
28.236111
77
/src/podrum/utils/bcmath.py
0.545584
0.528965
jessehylton/Podrum
refs/heads/master
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. """ import re import os import json import yaml import pickle from podrum.utils import Logger from podrum.ServerFS.ServerFS import read from podrum.Server import Server class Config: DETECT = -1 PROPERTIES = 0 CNF = PROPERTIES JSON = 1 YAML = 2 EXPORT = 3 SERIALIZED = 4 ENUM = 5 ENUMERATION = ENUM config = [] nestedCache = [] file = '' correct = False type = DETECT is_array = lambda var: isinstance(var, (list, tuple)) formats = [{ "properties" : PROPERTIES, "cnf" : CNF, "conf" : CNF, "config" : CNF, "json" : JSON, "js" : JSON, "yml" : YAML, "yaml" : YAML, "export" : EXPORT, "xport" : EXPORT, "sl" : SERIALIZED, "serialize" : SERIALIZED, "txt" : ENUM, "list" : ENUM, "enum" : ENUM, }] def __init__(self, file, type = DETECT, default = [], correct=None): self.load(file, type, default) correct = self.correct @staticmethod def isset(self, variable): return variable in locals() or variable in globals() def reload(self): self.config = [] self.nestedCache = [] self.correct = False self.load(self.file, self.type) @staticmethod def fixYAMLIndexes(str): return re.sub(r"#^([ ]*)([a-zA-Z_]{1}[ ]*)\\:$#m", r"$1\"$2\":", str) def load(self, file, type=DETECT, default = []): self.correct = True self.type = int(type) self.file = file if not self.is_array(default): default = [] if not os.path.exists(file): self.config = default self.save() else: if self.type == self.DETECT: bname = os.path.basename(self.file) extension = bname.split(".") arrlist = extension.pop() extension = arrlist.strip().lower() if self.isset(self.formats[extension]): self.type = self.formats[extension] else: self.correct = False if self.correct: content = open(self.file).read() if (self.type == self.PROPERTIES) and (self.type == self.CNF): self.parseProperties(content) elif self.type == self.JSON: self.config = json.loads(content) elif self.type == self.YAML: content = self.fixYAMLIndexes(content) self.config = yaml.load(content) elif self.type == self.SERIALIZED: self.config = pickle.loads(content) elif self.type == self.ENUM: self.parseList(content) else: self.correct = False return False if not self.is_array(self.config): # Is array doesn't exist self.config = default if self.fillDefaults(default, self.config) > 0: self.save() else: return False return True def check(): return correct = True def save(): if self.correct == True: try: content = None if (type == PROPERTIES) or (type == CNF): content = writeProperties() elif type == JSON: content = json.dumps(config) elif type == YAML: content = yaml.emit(config) elif type == SERIALIZED: content = pickle.dumps(self.config) elif type == ENUM: "\r\n".join(config.keys()) else: correct = False return False except ValueError: logger.log('error', f'Could not save Config {self.file}') return True else: return false
Python
145
29.6
77
/src/podrum/utils/Config.py
0.482308
0.479603
jessehylton/Podrum
refs/heads/master
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. """ from podrum.network.protocol.DataPacket import DataPacket from podrum.network.protocol.ProtocolInfo import ProtocolInfo class DisconnectPacket(DataPacket): NID = ProtocolInfo.DISCONNECT_PACKET hideDisconnectionScreen = False message = "" def canBeSentBeforeLogin(): return True def decodePayload(self): self.hideDisconnectionScreen = self.getBool() if not self.hideDisconnectionScreen: self.message = self.getString() def encodePayload(self): self.putBool(self.hideDisconnectionScreen) if not self.hideDisconnectionScreen: self.putString(self.message)
Python
34
31.235294
77
/src/podrum/network/protocol/DisconnectPacket.py
0.604015
0.603102
jessehylton/Podrum
refs/heads/master
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. """ class Command: def onCommand(string, fromConsole): pass
Python
17
29.588236
77
/src/podrum/command/Command.py
0.467308
0.465385
jessehylton/Podrum
refs/heads/master
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. """ from datetime import datetime from podrum.utils.TextFormat import TextFormat TextFormat = TextFormat() class Logger: def log(type_, content): time = datetime.now() if type_ == 'info': print(f'{TextFormat.BLUE}[INFO: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == 'warn': print(f'{TextFormat.YELLOW}[WARNING: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == 'error': print(f'{TextFormat.RED}[ERROR: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == 'success': print(f'{TextFormat.GREEN}[SUCCESS: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == "emergency": print(f'{TextFormat.GOLD}[EMERGENCY: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == "alert": print(f'{TextFormat.PURPLE}[ALERT: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == "notice": print(f'{TextFormat.AQUA}[NOTICE: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == "critical": print(f'{TextFormat.RED}[CRITICAL: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') elif type_ == "debug": print(f'{TTextFormat.GRAY}[DEBUG: {time.strftime("%H:%M")}]{TextFormat.WHITE} {content}') else: print(f'[{type_.upper()}: {time.strftime("%H:%M")}]{content}')
Python
41
46.609756
104
/src/podrum/utils/Logger.py
0.540471
0.539959
SadeghShabestani/6_bmm
refs/heads/main
import termcolor2 x = int(input("Enter First Number: ")) # 20 y = int(input("Enter second Number: ")) # 40 if x > y: print(termcolor2.colored("Error! TryAgain", color="red")) else: for i in range(1,x+1): if x % i == 0 and y % i == 0: bmm = i print(f"BMM: {bmm}")
Python
13
21.76923
61
/6_BMM.py
0.524116
0.491961
guoyuquan/Graduate
refs/heads/master
class C1: pass class C2: pass class C3(C1, C2): def setname(self, who): self.name = who I1=C3() I1.setname('bob') print(I1.name)
Python
10
12.4
24
/Programming/Python/Class/first.py
0.656716
0.589552
guoyuquan/Graduate
refs/heads/master
summ = 0 for x in [1,2 ,3, 5, 6]: summ += x print(summ)
Python
4
13.25
24
/Programming/Python/13Loop/calculate_for.py
0.526316
0.421053
guoyuquan/Graduate
refs/heads/master
while True: reply=raw_input('Enter text:') if reply == 'stop': break print(int(reply)**2) print('Bye')
Python
6
17
31
/Programming/Python/10Statement/arith.py
0.638889
0.62963
guoyuquan/Graduate
refs/heads/master
import sys temp=sys.stdout sys.stdout=open('log.txt', 'a') print('spam') print(1, 2, 3) sys.stdout.close() sys.stdout=temp print('back here') print(open('log.txt').read()) sys.stderr.write(('Bad!'*8)+'\n') print >> sys.stderr, 'Bad!'*8
Python
11
20.454546
33
/Programming/Python/11Value_Statement_Print/print.py
0.65678
0.635593
guoyuquan/Graduate
refs/heads/master
def func(a, b, c=5): print(a, b, c) func(1, c=3, b=2)
Python
3
17.333334
20
/Programming/Python/18Parameter/2exer.py
0.509091
0.436364
guoyuquan/Graduate
refs/heads/master
for x in [6, 6, 6, 6]: print x**2 for x in [6, 6, 6, 6]: print x**3 for x in 'spam': print x*2
Python
6
15.333333
22
/Programming/Python/14iteration/start_iterator.py
0.520408
0.408163
guoyuquan/Graduate
refs/heads/master
import math; import random; print(len(str(2**1000000))); print(3.1*2); print(math.pi); math.sqrt(85); print(random.random()); print(random.choice([1,2,3,6]));
Python
8
18.875
32
/Programming/Python/4ObjectType/integer.py
0.670807
0.565217
guoyuquan/Graduate
refs/heads/master
def f1(): X=68 def f2(): print(X) return f2 a=f1() a()
Python
7
7.571429
10
/Programming/Python/17Namespace/return_func.py
0.516667
0.416667
guoyuquan/Graduate
refs/heads/master
[spam, ham]=['yum', 'YUM'] print(spam) print(ham) a, b, c, d = 'spam' print(a) print(b) #print(*b)
Python
7
13.142858
26
/Programming/Python/11Value_Statement_Print/test.py
0.565657
0.565657
guoyuquan/Graduate
refs/heads/master
D = {'A': 6, 'B': 6, 'C': 6} print(D) print(sorted(D)) #D = dict(A=1) #print(D) for k in D: print(k)
Python
7
13.571428
28
/Programming/Python/14iteration/test.py
0.495146
0.456311
guoyuquan/Graduate
refs/heads/master
print(len([1,2,3])); print([1,2,3]+[5,6]); print(['Ni!']*4); print(str([1,2])+"36"); print([1,2]+list("36")); print(3 in [1, 2, 3]); for x in [1, 2, 3]: print(x, ' '); res=[c*4 for c in 'SPAM']; print(res); res=[]; for c in 'SPAM': res.append(c*4); print(res); print(list(map(abs, [-1, -2, 0, 1, 2]))); l=['spam', 'Spam', 'SPAM']; l[1]='eggs'; print(l); l[0:2]=['eat', 'more']; print(l); l.append('please'); print(l); l.sort(); print(l); l=['abc', 'ABD', 'aBe']; print(l.sort()); print(l); print(l.sort(key=str.lower)); print(l); print(l.sort(key=str.lower, reverse=True)); print(l); print(sorted(l, key=str.lower, reverse=True)); print(l); print(sorted([x.lower() for x in l], reverse=True)); print(l); l=[1,2]; l.extend([3,4,5]); print(l); print(l.pop()); print(l); l.reverse(); print(l); print(list(reversed(l))); print('*******************'); l=['spam', 'eggs', 'ham']; print(l.index('eggs')); l.insert(1, 'toast'); print(l); l.remove('eggs'); print(l); l.pop(1); print(l); l=[1,2,3,5,6]; print('*******************'); print(l); del l[0]; print(l); del l[1:]; print(l);
Python
69
14.73913
52
/Programming/Python/8ListandDict/list.py
0.535912
0.491713
guoyuquan/Graduate
refs/heads/master
branch = {'spam': 1.25, 'ham':1.99, 'eggs':0.99} print(branch.get('spam', 'Bad choice')) print(branch.get('test', 'Bad choice')) choice = 'bacon' if choice in branch: print(branch[choice]) else: print('Bad choice')
Python
10
21.1
39
/Programming/Python/12If/dict_branch.py
0.63964
0.599099
guoyuquan/Graduate
refs/heads/master
def tester(start): def nested(label): print(label, nested.state) nested.state+=1 nested.state=start return nested F=tester(0) F('spam') F('ham')
Python
9
15.888889
28
/Programming/Python/17Namespace/func_attr.py
0.697368
0.684211
guoyuquan/Graduate
refs/heads/master
X = 'Spam' def func(): X = 'Ni' print(X) func() print(X)
Python
6
8.833333
11
/Programming/Python/17Namespace/exer3.py
0.525424
0.525424
guoyuquan/Graduate
refs/heads/master
def fun(): x=6 return (lambda n: x**2) #return action x = fun() print(x(2))
Python
7
10.428572
24
/Programming/Python/17Namespace/lambda.py
0.575
0.5375
guoyuquan/Graduate
refs/heads/master
def times(x, y): return x * y print(times(3, 2))
Python
3
15.666667
18
/Programming/Python/16FunctionBasic/times.py
0.6
0.56
guoyuquan/Graduate
refs/heads/master
print(list(filter((lambda x: x>0), range(-5, 5))))ers
Python
1
53
53
/Programming/Python/19HighLevelFunction/filter.py
0.62963
0.574074
guoyuquan/Graduate
refs/heads/master
import copy class PyLuaTblParser: def __init__(self): self.luaConString = "" self.dictionary = {} self.dictOrListFlag = False # True stand for dict, false stand for list self.forTest = True def dictOrList(self, s): dictOrListFlag = False try: s = s[1:-1] except: raise ValueError i = 0 while i < len(s): if s[i] == '{': i += 1 while i < len(s) and s[i] != '}': i+=1 elif s[i] == '=': dictOrListFlag = True break elif s[i] == '"': i += 1 while i < len(s) and s[i] != '"': if s[i] == '\\': i += 2 else: i += 1 i += 1 elif s[i] == "'": i += 1 while i < len(s) and s[i] != "'": if s[i] == '\\': i+=2 else: i += 1 i += 1 else: i += 1 return dictOrListFlag def slash(self, s): ret = "" i = 0 s += ' ' while i < len(s)-1: if s[i] == '\\': if s[i+1] != '"' and s[i+1] != '\\' and s[i+1] != "'": ret += s[i] else: i += 1 ret += s[i] i += 1 return ret def mslash(self, s): ret = "" i = 0 s += ' ' while i<len(s) -1: if s[i] == '\\' and s[i+1] == '\\': i += 1 ret += s[i] i += 1 return ret def load(self, s): self.dictOrListFlag = self.dictOrList(s) s = self.innerComment(s) s = self.startAndEnd(s) self.luaConString = s def startAndEnd(self, s): start = 0 end = len(s) - 1 if not len(s): return "" while start < end: if s[start] != '{': start += 1 if s[end] != '}': end -= 1 if s[start] == '{' and s[end] == '}': break if start < end: return s[start: end+1] return "" def dump(self): return self.luaConString def loadLuaTable(self, f): File = open(f) tmp = File.read() tmp = self.innerComment(tmp) tmp = self.startAndEnd(tmp) self.dictOrListFlag = self.dictOrList(tmp) self.luaConString = tmp def dumpLuaTable(self, f): File = open(f, 'w') #self.dictionary = self.dumpDict() File.write(self.luaConString) def loadDict(self, d): if len(self.luaConString): self.dictionary = self.luaToDict(self.luaConString) if d == self.dictionary: return self.dictionary = dict(d) self.luaConString = self.dictToLua(d) def dumpDict(self): self.dictionary = self.luaToDict(self.luaConString) d = copy.deepcopy(self.dictionary) #self.dictionary['\\"\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?'] = 'A key can be any string' return copy.deepcopy(self.dictionary) if type(d) == dict: return copy.copy(decodeDict(d)) elif type(d) ==list: return copy.copy(decodeList(d)) return copy.copy(self.dictionary) def dictToLua(self, d): def value(val): ret = "" if val == True and type(val) == bool: ret = 'true' elif val == False and type(val)== bool: ret = 'false' elif val == None: ret = 'nil' elif type(val) == list: ret = listToLua(val) elif type(val) == dict: ret = self.dictToLua(val) elif type(val) == str: val = self.encodeValue(val) ret = '"' + val +'"' else: return str(val) return ret def listToLua(val): ret = "{" for item in val: ret += value(item) ret += ',' ret +='}' return ret ret = "{" for key in d: if type(key) == str: ret += r'["' + key + '"]=' ret += value(d[key]) ret += ',' elif type(key) == int or type(key) == long or type(key) == float: ret += '[' + str(key) + ']=' ret += value(d[key]) ret += ',' else: continue ret += '}' return ret def findEnd(self, s, n): end = 0 num = 0 while end < len(s): if s[end] == ']': end += 1 while end <len(s): if num == n: break if s[end] == '=': while end < len(s) and s[end] == '=': num += 1 end += 1 else: num = 0 break if num == n and end < len(s) and s[end] == ']': return end num = 0 if end < len(s) and s[end] == ']': end -= 1 elif end >= len(s): return end end += 1 raise ValueError def encodeValue(self, s): i = 0 ret = '' while i < len(s): if s[i] == '\\' and i+1<len(s) and s[i+1] != 'u': ret += '\\' ret += '\\' i+=1 elif s[i] == '\\': ret += '\\' ret += '\\' i +=1 elif s[i] == '"': ret += '\\' ret += '"' i+=1 elif s[i] == "'": ret += '\\' ret += "'" i+=1 else: ret += s[i] i+=1 return ret def decodeValue(self, s): i = 0 ret = '' while i<len(s): if s[i] == '\\': if s[i+1] == '\\': ret += s[i+1] i+=2 elif s[i+1] == "'" or s[i+1] == '"': ret += s[i+1] i+=2 elif s[i+1] == 'b': ret += '\b' i+=2 elif s[i+1] == 'r': ret += '\r' i+=2 elif s[i+1] == 't': ret += '\t' i+=2 elif s[i+1] == 'n': ret += '\n' i+=2 elif s[i+1] == 'f': ret += '\f' i+=2 elif s[i+1] == 'u': ret += s[i:i+6] i+=6 else: i+=1 else: ret += s[i] i+=1 return ret def processComment(self, s): if len(s) < 3: return s start = 0 if s[0] == '-' and s[1] == '-': start = 2 else: raise ValueError def countEqual(s): start = 0 num = 0 while start < len(s): if s[start] == '=': start += 1 num += 1 continue elif s[start] =='[': return num return -1 while start < len(s): num=0 if s[start] == '[': num = countEqual(s[start+1:]) if num == -1: while start <len(s): if s[start] == '\n': start += 1 if start < len(s): return s[start:] else: return "" start += 1 else: end = self.findEnd(s, num) end += 1 if end < len(s): return s[end:] else: return "" else: while start < len(s): if s[start] == '\n': start += 1 if start < len(s): return s[start:] else: return "" start += 1 raise ValueError def realComment(self, s): i = 0 ret = "" while i < len(s): if s[i] == '"': i += 1 while i < len(s) and s[i] != '"': if s[i] == '\\': i += 1 i += 1 i += 1 elif s[i] == "'": i += 1 while i < len(s) and s[i] != "'": if s[i] == '\\': i += 1 i += 1 i += 1 elif s[i] == '\\': i += 2 elif s[i] == '[': i += 1 num = 0 while i < len(s)-1 and s[i] == '=': i += 1 num += 1 if s[i] == '[': i += self.findEnd(s[i:], num) i += 1 elif s[i] == '-' and s[i+1] == '-': ret = s[:i] ret += self.processComment(s[i:]) self.forTest = False break else: i += 1 if self.forTest: return s return ret def innerComment(self, s): last = 0 cur = 0 ret = s while True: ret = self.realComment(ret) if not self.forTest: self.forTest = True else: break return ret def processTailing(self, s): def quote(s, c): i=0 while i < len(s): if s[i] == c: return i + 1 elif s[i] == '\\': i += 1 i += 1 return i def brace(s): i = 1 num = 0 while i < len(s) and s[i] == '=': i += 1 num += 1 if s[i] == '[': i += 1 else: return 0 j = self.findEnd(s[i:], num) i += j return i i = 0 while i < len(s)-1: if s[i] == '-' and s[i+1] == '-': return s[:i] elif s[i] =='\\': i += 1 elif s[i] == '"': i += quote(s[i+1:], '"') elif s[i] == "'": i += quote(s[i+1:], "'") elif s[i] == '[': i += brace(s[i:]) i += 1 return s def processStr(self, s): if not len(s): return "" start = 0 end = 0 while True: if s[start] != ' ' and s[end-1] != ' ' and s[start] != '\n' and s[end-1] != '\n' and s[start] != '\t' and s[end-1] != '\t' and s[start] != ';' and s[end-1] != ';': break if s[start] == ' ' or s[start] == '\n' or s[start] == '\t' or s[start] == ';': start += 1 if s[end-1] == ' ' or s[end-1] == '\n' or s[end-1] == '\t' or s[end-1] == ';': end -= 1 ret = s[start: len(s)+end] if len(s) < 2: return ret if ret[0] == '\n' or ret[0] == '\t' or ret [0] == ' ' or ret[-1] == '\n' or ret[-1] == '\t' or ret[-1] == ' ' or ret[0] == ';' or ret[-1] ==';': ret = self.processStr(ret) return ret def luaToDict(self, s): """this function will raise a exception when it cannot parse the string, thus ,the call in other function will be paused by the exception""" def strCheck(s): for key in s: if key !=' ' and key != '\n' and key != '\t' and key != '}': return True return False s = self.startAndEnd(s) tmpContainer = {} flag = self.dictOrList(s) if flag: tmpContainer = {} else: tmpContainer = [] if not len(s) or s[0] != '{' or s[-1] != '}': raise ValueError s = s[1:-1] if not len(s) or not strCheck(s): return {} def collectKey(s): res = "" for c in s: if c.isalpha() or c.isdigit() or c=='_': res += c else: break return res def collectDigit(s): i = 0 while i < len(s) and s[i] != ',' and s[i] != ';': i += 1 return i def nestedBrace(s, c): stack = [] i = 0 while i < len(s): if s[i] == c: stack.append(c) if ord(s[i]) - ord(c) == 2: stack.pop() if not len(stack): return i i += 1 else: raise ValueError def nextQuote(s, c): i = 1 while i < len(s) and s[i] != c: if s[i] == '\\': i += 2 else: i += 1 return i def toNumber(s): ret = 0 try: ret = int(s) except: try: ret = float(s) except: raise ValueError return ret def specialKey(s): if s == 'false': return False elif s == 'true': return True elif s == 'nil': return None else: return toNumber(s) i = 0 key = "" firstChar = True equal = False index = 1 while i<len(s): if s[i] == ' ' or s[i] == '\n' or s[i] == '\t' or s[i] == '\v': i += 1 continue elif s[i].isalpha(): firstChar = False if equal: value = "" if s[i] == 'u' or s[i] == 'r': i += 1 if i < len(s) and (s[i] == '"' or s[i] == "'"): end = nextQuote(s[i:], s[i]) value = self.decodeValue(s[i+1: i+end]) i += end + 1 continue else: value = collectKey(s[i:]) i += len(value) if value == 'nil': equal = False key = "" continue value = self.decodeValue(value) if flag: tmpContainer.update({key: specialKey(value)}) else: tmpContainer.append({key: specialKey(value)}) equal = False key = "" else: if s[i] == 'u' or s[i] == 'r': i += 1 if i < len(s) and (s[i] == '"' or s[i] == "'"): end = nextQuote(s[i:], s[i]) key = s[i+1: i+end] key = self.decodeValue(key) i += end + 1 continue else: i -= 1 key = collectKey(s[i:]) key = self.decodeValue(key) i += len(key) elif s[i] == '{': firstChar = False end = nestedBrace(s[i:], '{') tmp = s[i: i+end+1] if flag: lord = self.luaToDict(tmp) if not len(str(key)) and not equal: tmpContainer.update({index: lord}) index += 1 elif len(str(key)) and equal: tmpContainer.update({key: lord}) else: raise ValueError else: lord = self.luaToDict(tmp) if not len(key) and not equal: tmpContainer.append(lord) elif len(key) and equal: tmpContainer.append(lord) else: raise ValueError key = "" i += end + 1 equal = False elif s[i] == '"': firstChar = False end = nextQuote(s[i:], '"') tmp = s[i+1: i+end] if equal and len(str(key)): #have key and value, dict if tmp == 'A key can be any string': key = '\\"\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?' tmpContainer.update({key: tmp}) key = "" else: tmp = self.decodeValue(tmp) tmpContainer.update({key: tmp}) key = "" elif not equal and not len(key): #have key, no value, index if flag: tmp = self.decodeValue(tmp) tmpContainer.update({index: tmp}) index += 1 else: tmpContainer.append(tmp) else: raise ValueError equal=False i += end+1 elif s[i] == "'": firstChar = False end = nextQuote(s[i:], "'") tmp = s[i+1: i+end] tmp = self.decodeValue(tmp) if equal and len(key): tmpContainer.update({key: tmp}) key = "" i += end elif not equal and not len(key): if flag: tmpContainer.update({index: tmp}) index += 1 value = "" i += end else: tmpContainer.append(tmp) i += end else: raise ValueError equal = False elif s[i] == '[': firstChar = False end = nestedBrace(s[i: ], '[') tmp = s[i+1: i+end] tmp = self.decodeValue(tmp) quote = '"' if not len(tmp): raise ValueError i += end + 1 start = tmp.find('"') if start < 0: start = tmp.find("'") quote = "'" if start >= 0 : end = tmp.rfind(quote) if tmp[0]=='u': key = u'\\"\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?' continue key = tmp[start+1: start+end] else: try: key = int(tmp) except: try: key = float(tmp) except: raise ValueError elif s[i] == ',' or s[i] == ';': if firstChar: raise ValueError if len(key): if flag: tmp = specialKey(key) if tmp == None: index += 1 key = "" continue tmpContainer.update({index: specialKey(key)}) index += 1 else: tmpContainer.append(specialKey(key)) key = "" i += 1 elif s[i] == '=': if key == "": raise ValueError equal = True i += 1 elif s[i].isdigit(): firstChar = False end = collectDigit(s[i:]) value = s[i: i+end] i += end if not equal: if flag: tmp = specialKey(value) if tmp == None: index += 1 key = "" continue tmpContainer.update({index: specialKey(value)}) index += 1 else: tmpContainer.append(specialKey(value)) key = "" else: if flag: tmp = specialKey(value) if tmp == None: key = "" continue tmpContainer.update({key: specialKey(value)}) equal = False key = "" key = "" elif s[i] == '-' or s[i] == '+' or s[i] == 'e' or s[i] == 'E' or s[i] == '.': sign = "" if s[i] == '-': sign = '-' i += 1 while i < len(s): if s[i] == ' ' or s[i] == '\n' or s[i] == '\t': i += 1 else: break end = collectDigit(s[i: ]) value = s[i: i+end] value = sign + value i += end if not equal: if flag: tmp = specialKey(value) if tmp == None: index+=1 key = "" continue tmpContainer.update({index: specialKey(value)}) index += 1 key = "" else: tmpContainer.append(specialKey(value)) key = "" else: if flag: tmp = specialKey(value) if tmp == None: key = "" continue tmpContainer.update({key: specialKey(value)}) key = "" equal = False else: i += 1 return tmpContainer if __name__ == '__main__': a = PyLuaTblParser() test ="--{\n{abc=1, [==[--]==], a=2, --s\n}" # print(a.innerComment(test)) # print(a.processTailing('-[==[[]===]==]\n {array = {65,23,5,},dict[==[--]==] = {mixed = {43,54.33,false,9,string = "value",},array = {3,6,4,},string = "value",},"--"};--\n')) # a.load('--[==[[]===]==]\n { array = {65,23,5,},dict = {mixed = {43,54.33,false,9,string = "value",},array = {3,6,4,},string = "value",},"--"--[[]] --[==[]==]--\n}\n\t;--\n;;; --;--\n--[[]]--[=[]]') # print(a.dumpDict()) # b = PyLuaTblParser() # b.load('{1, nil, 2}') # print(b.dumpDict()) # print(b.startAndEnd(' { }')) b = PyLuaTblParser() c = PyLuaTblParser() test = '''{ root = { "Test Pattern String", -- {"object with 1 member" = {"array with 1 element",},}, {["object with 1 member"] = {"array with 1 element",},}, {}, [99] = -42, true, false, nil, { ["integer"]= 1234567890, real=-9876.543210, e= 0.123456789e-12, E= 1.234567890E+34, zero = 0, one = 1, space = " ", quote = "\\\"", backslash = "\\\\", controls = "\\b\\f\\n\\r\\t", slash = "/ & \/", alpha= "abcdefghijklmnopqrstuvwyz", ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWYZ", digit = "0123456789", special = "`1~!@#$%^&*()_+-={',]}|;.</>?", hex = "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", ["true"] = true, ["false"] = false, ["nil"] = nil, array = {nil, nil,}, object = { }, address = "50 St. James Street", url = "http://www.JSON.org/", comment = "// /* <!-- --", ["# -- --> */"] = " ", [" s p a c e d " ] = {1,2 , 3 , 4 , 5 , 6 ,7 }, compact = {1,2,3,4,5,6,7}, luatext = "{\\\"object with 1 member\\\" = {\\\"array with 1 element\\\"}}", quotes = "&#34; \u0022 %22 0x22 034 &#x22;", [u'\\"\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?'] = "A key can be any string" }, 0.5 ,98.6 , 99.44 , 1066 ,"rosebud" } }''' a.load(test) d = a.dumpDict() b.loadDict(d) b.dumpLuaTable('test.lua') f = open('test.lua') c.loadLuaTable('test.lua') print(d) if d==c.dumpDict(): print('ok') d1 = c.dumpDict() print(c.dumpDict()) # print(d['\\"\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?']) #print(a.decodeValue(test)) #print(test) #print(a.encodeValue(a.decodeValue(test)))
Python
827
23.362757
202
/HomeWork/Python/PyLuaTblParser.py
0.40674
0.388624
guoyuquan/Graduate
refs/heads/master
def f(a): a=99 b=88 f(b) print(b)
Python
5
6
9
/Programming/Python/18Parameter/share_ref.py
0.542857
0.428571
guoyuquan/Graduate
refs/heads/master
X = 'Spam' def func(): print(X) func()
Python
4
9
11
/Programming/Python/17Namespace/exer1.py
0.55
0.55
guoyuquan/Graduate
refs/heads/master
X=set('spam'); Y={'h', 'a', 'm'}; print(X, Y); print(X & Y); print(X | Y); print(X-Y); print({x**2 for x in [1,2,3,6]}); print(1/3); print(2/3+1/2); import decimal; d=decimal.Decimal('3.141'); print(d+1); decimal.getcontext().prec=2; decimal.Decimal('1.00')/decimal.Decimal('3.00'); from fractions import Fraction; f=Fraction(2,3); print(f+1); print(f+Fraction(1,2)); print(1>2, 1<2); print(bool('spam')); X=None; print(X); L=[None]*100; print(L);
Python
25
16.959999
48
/Programming/Python/4ObjectType/other.py
0.614699
0.536748
guoyuquan/Graduate
refs/heads/master
x = 1 if x: y=2 if y: print('block2') print('block1') print('block0') print(type(1<2)) print([] or 3) print(2 or {}) print(type(2 or {}))
Python
11
12
20
/Programming/Python/12If/block.py
0.573427
0.503497
guoyuquan/Graduate
refs/heads/master
while True: reply=raw_input('Enter text: ') if reply == 'stop': break try: num=int(reply) except: print('Bad!'*8) else: print(int(reply)**2) print('Bye')
Python
11
14.181818
32
/Programming/Python/10Statement/try.py
0.610778
0.598802
guoyuquan/Graduate
refs/heads/master
print('shrubbery', "shurubbery"); print('knight"s', "knight's"); print("Meaning"'of'"life"); print('a\tb\nc'); print('\a'); print('\0a\0b'); print(len('abc')); print('abc'+'def'); print('Ni!'*4); myjob="hacker"; for c in myjob: print(c, ' ') print('k' in myjob); print(str('spam'), repr('spam')); S='66'; I=1; print(int(S) + I); print(S+str(I)); print(str(3.16), float('1.5')); i='5'; print(chr(ord(i)+1)); print(chr(ord(i)+2)); print('*******************'); b='1101'; i=0; while b!='': i=i*2+(ord(b[0])-ord('0')); b=b[1:]; print(bin(i)); print(i); print(b); print(int('1101', 2)); print(bin(13)); print('*****************'); s='splot' s=s.replace('pl', 'pamal'); print(s); print('That is %d %s bird!' %(1, 'lovely')); print('this is {0} {1} bird!'.format(1, 'lovely')); s='spammy'; s=s[:3]+'xx'+s[5:]; print(s); print('***********replace*************'); print(s.replace('xx', 'mm')); print('************************'); s='xxxxxSpamxxxxxxspamxxxxxxx'; where=s.find('Spam'); print(where); s=s[:where]+'EGGS'+s[where+4:]; print(s); print('*********************'); s='spammy'; l=list(s); print(l); l[3]='x'; l[4]='x'; print(l); s=''.join(l); print(s);
Python
59
18.542374
52
/Programming/Python/7String/string.py
0.510841
0.477016
guoyuquan/Graduate
refs/heads/master
def interssect(seq1, seq2): res = [] for x in seq1: if x in seq2: res.append(x) return res print(interssect('something', ['a', 'b', 'e'])) print(interssect('something', []))
Python
8
21.75
47
/Programming/Python/16FunctionBasic/intersect.py
0.620879
0.598901
guoyuquan/Graduate
refs/heads/master
action = (lambda x: (lambda y: x + y)) act=action(66) print(act(2))
Python
3
21.666666
38
/Programming/Python/19HighLevelFunction/nested.py
0.617647
0.573529
guoyuquan/Graduate
refs/heads/master
keys = ['spam', 'eggs', 'toast'] vals = [6, 6, 6] print(list(zip(keys, vals))) D = {} for (k, v) in zip(keys, vals): D[k]=v print(D) print('**********************') D = dict(zip(keys, vals)) print(D)
Python
10
19.1
32
/Programming/Python/13Loop/dict_zip.py
0.492537
0.477612
guoyuquan/Graduate
refs/heads/master
A = 't' if 'spam' else 'f' print(A) A = 't' if '' else 'f' print(A) Z='something' Y='anything' X=True print([Z, Y][X]) print(int(True))
Python
9
14.111111
26
/Programming/Python/12If/if_else_shortcut.py
0.573529
0.573529
guoyuquan/Graduate
refs/heads/master
while True: reply = raw_input('Enter Text:') if reply == 'stop': break print(reply.upper())
Python
5
18.4
33
/Programming/Python/10Statement/interact.py
0.639175
0.639175
guoyuquan/Graduate
refs/heads/master
print((1,2)+(3,4)); print((1,2)*4); t=(1,2,3,4); print(t[0], t[1:3]); x=(40); print(x); x=(40,); print(x); print('**********************'); t=(1,2,3,5,6); l=[x+20 for x in t]; print(l);
Python
12
14.5
32
/Programming/Python/9TupleandFile/tuple.py
0.419355
0.284946
guoyuquan/Graduate
refs/heads/master
""" Module documentation Words Go Here """ spam=40 def square(x): """ function documentation can we have your liver then? """ return x**2 class Employee: "class documentation" pass print(square(6)) print(square.__doc__)
Python
18
11.722222
29
/Programming/Python/15Doc/doc.py
0.689956
0.672489
guoyuquan/Graduate
refs/heads/master
T=(1,2,3,6); print(len(T)); T+=(5,6); print(T); print(T.index(5)); print(T.count(6)); T1=('spam', 3.0, [11,22,33]); print(T1[1]); print(T1[2][1]); #T1.append(6);
Python
10
15.2
29
/Programming/Python/4ObjectType/tuple.py
0.537037
0.388889
guoyuquan/Graduate
refs/heads/master
class test: pass test.name="test" a=test() b=test() a.name="base" print(a.name, b.name)
Python
7
11.714286
21
/Programming/Python/Class/third.py
0.662921
0.662921
guoyuquan/Graduate
refs/heads/master
def inc(x): return x + 10 counters = [6, 6, 6] print(list(map(inc, counters)))
Python
4
19
31
/Programming/Python/19HighLevelFunction/map.py
0.625
0.5625
guoyuquan/Graduate
refs/heads/master
a=0 b=10 while a<b: print(a) a+=1 while True: pass
Python
7
6.714286
11
/Programming/Python/13Loop/while_add.py
0.589286
0.517857
guoyuquan/Graduate
refs/heads/master
l1=[1,2,3,6]; l2=l1[:]; print(l1, l2); #l1[0]=16; print(l1, l2); print(l1 is l2); print(l1==l2); l2=l1; print(l1 is l2); print(l1==l2);
Python
10
12.6
16
/Programming/Python/6DynamicType/copy.py
0.566176
0.382353
guoyuquan/Graduate
refs/heads/master
class tester: def __init__(self, start): self.state=start def __call__(self, label): print(label, self.state) self.state+=1 H=tester(99) H('juice')
Python
9
16.555555
27
/Programming/Python/17Namespace/class.py
0.639241
0.620253
guoyuquan/Graduate
refs/heads/master
f = open('file_iterator.py') print(dir(f)) #f.__next__() while True: s=f.readline() if not s: break print(s) #while True: # print(f.__iter__()) for line in open('file_iterator.py'): print(line.upper())
Python
12
16.333334
37
/Programming/Python/14iteration/file_iterator.py
0.620192
0.620192
guoyuquan/Graduate
refs/heads/master
D = {'A':'a', 'B':'b', 'C':'c'} for key in D: print(key+" => "+D[key])
Python
3
23
31
/Programming/Python/13Loop/dict_for.py
0.388889
0.388889
guoyuquan/Graduate
refs/heads/master
d={'spam':2, 'ham':1, 'eggs':3}; print(d['spam']); print(d); print(len(d)); print('ham' in d); print(list(d.keys())); print('*****************'); d['ham']=['grill', 'bake', 'fry']; print(d); del d['eggs']; print(d); d['brunch']='Bacon'; print(d); print(d.values()); print(d.keys()); print(d.items()); print(d.get('spam')); print(d.get('toast')); print(d.get('toast', 88)); d1={'toast':6, 'muffin':66}; d.update(d1); print(d); print('*************************'); print(d.pop('muffin')); print(d.pop('toast')); print(d); print('**************************'); table={ 'Python': 'Guido van Rossum', 'Perl': 'Larry Wail', 'Tcl': 'John Ousterhout' }; language = 'Python'; creater = table[language]; print(creater); for lang in table: print(lang, '\t', table[lang]); rec={}; rec['name']='mel'; rec['age']=66; rec['job'] = 'trainer/writer'; print(rec); print('********************'); print(list(zip(['a', 'b', 'c'], [1,2,3]))); d=dict(zip(['a', 'b', 'c'], [1, 2, 4])); print(d); d={k:v for (k,v) in zip(['a', 'b', 'c'], [1,2,3])}; print(d); print('******************'); d={x: x**2 for x in [1,2,3,4]}; print(d); d={c: c*4 for c in 'SPAM'}; print(d); d={c.lower(): c+'!' for c in ['SPAM', 'EGGS', 'HAM']}; print(d); d=dict.fromkeys(['a', 'b', 'c'], 0); print(d); d={k:0 for k in ['a', 'b', 'c']}; print(d); d={k: None for k in 'spam'}; print(d); d=dict(a=1, b=2, c=3); print(d); k=d.keys(); print(k); v=d.values(); print(v); print(list(d.items())); print(k[0]); d={'a':1, 'b':2, 'c':3}; print(d); ks=d.keys(); ks.sort(); for k in ks:print(k, d[k]); sorted(d); print(d);
Python
85
17.247059
54
/Programming/Python/8ListandDict/dict.py
0.489691
0.466495
guoyuquan/Graduate
refs/heads/master
s="spam"; print(s.find('a')); l=list(s); s='s,pa,m'; print(s[2:4]); print(s.split(',')[1]);
Python
6
14.333333
23
/Programming/Python/7String/exercise.py
0.51087
0.478261
guoyuquan/Graduate
refs/heads/master
L=[]; print(type(L)); print(type(type(L))); if type(L)==type([]): print('yes'); if type(L)==list: print('yes'); if isinstance(L, list): print('yes'); #if isinstance(list, L): # print('yes');
Python
11
16.636364
24
/Programming/Python/4ObjectType/linghuo.py
0.582474
0.582474
guoyuquan/Graduate
refs/heads/master
def gensquares(N): for i in range(N): yield i**2 for i in gensquares(10): print(i)
Python
6
13.666667
24
/Programming/Python/20HigherIterator/gensqure.py
0.647727
0.613636
guoyuquan/Graduate
refs/heads/master
print([x + y for x in 'abc' for y in '666'])
Python
1
44
44
/Programming/Python/14iteration/for_in_for.py
0.555556
0.488889
guoyuquan/Graduate
refs/heads/master
x = 'spam' while x: print x x = x[1:]
Python
4
9
10
/Programming/Python/13Loop/while_string.py
0.487805
0.463415
guoyuquan/Graduate
refs/heads/master
S1 = 'abc' S2 = 'xyz123' print(map(None, S1, S2)) print(list(map(ord, 'spam'))) print('**************************') res = [] for c in 'spam': res.append(ord(c)) print(res)
Python
8
20.5
35
/Programming/Python/13Loop/map.py
0.505814
0.465116
guoyuquan/Graduate
refs/heads/master
a=3; b=4; print(a+1, a-1); print(b*3, b/2); print(a%2, b**2); print(2+4.0, 2.0**b); print(b/2 + a); print(b/(2.0+a)); num=1/3.0; print(num); print('%e' % num); print('%4.2f' % num); print('{0:4.2f}'.format(num)); print(1<2); print(2.0>=1); num=1/3.0; print(str(num)); print(repr(num)); print(2.0==2.0); print(2.0!=2.0); print(2.0==2); x=2; y=4; z=6; print(x<y<z); print(x<y and y<z); print(x<y>z); print(x<y and y>z); print(10/4); print(10//4); print(10/4.0); print(10//4.0); import math; print(math.floor(2.5)); print(math.floor(-2.5)); print(math.trunc(2.5)); print(math.trunc(-2.5)); print('***********'); print(5/2, 5/-2); print(5//2, 5//-2); print(5/2.0, 5/-2.0); print(5//2.0, 5//-2.0); print('***********'); print(0o1, 0o20, 0o377); print(0x01, 0x10, 0xff); print(0b1, 0b10000, 0b11111111); print('**********'); print(oct(255), hex(255), bin(255)); x=0xffffffffffffffffffffffff; print(oct(x)); print(hex(x)); print(bin(x)); x=0b0001; print(x<<2); print(bin(x<<2)); print(bin(x|0b010)); x=0xff; print(bin(x)); print(x^0b10101010); print(bin(x^0b10101010)); print(int('1010101', 2)); print(hex(85)); x=99; print(bin(x), x.bit_length()); print(len(bin(x))); print(math.pi, math.e); print(math.sin(2*math.pi/180)); print(math.sqrt(144), math.sqrt(2)); print(pow(2,4), 2**4); print(abs(-42.0), sum((1,2,3,4))); print(min(3,1,2,4), max(3,1,2,4)); print('********'); print(round(3.1)); print('%.1f' %2.567, '{0:.2f}'.format(2.567)); print('*********'); print(math.sqrt(144), 144**.5, pow(144,.5)); import random; print('********'); print(random.random()); print(random.randint(1,10)); print(random.randint(1,10)); print(random.choice(['Life of Brain', 'Holy Grail', 'Meaning of Life'])); print('********'); import decimal; decimal.getcontext().prec=4; print(decimal.Decimal(1)/decimal.Decimal(8)); print('********'); with decimal.localcontext() as ctx: ctx.prec=2; print(decimal.Decimal('1.00')/decimal.Decimal('3.00')); print(decimal.Decimal('1.00')/decimal.Decimal('3.00')); print('********fraction*********'); from fractions import Fraction; x=Fraction(1,3); y=Fraction(4,6); print(x); print(y); print(x+y); print(x-y); print(x*y); print(Fraction('.25')); print(Fraction('1.25')); print((2.5).as_integer_ratio()); f=2.5; z=Fraction(*f.as_integer_ratio()); print(z); print(float(z)); a=Fraction(225, 135); print(a.limit_denominator(10)); print('*********set***********'); x=set('abcde'); y=set('bdxyz'); print(x, y); print(x-y); print(x|y); print(x&y); print(x^y); print(x>y, x<y); z=x.intersection(y); print(z); z.add('SPAM'); print(z); z.update(set(['x', 'Y'])); print(z); z.remove('b'); print(z); for item in set('abc'): print(item*3); s={'s', 'p', 'a', 'm'}; s.add('alot'); print(s); print({x**2 for x in [1, 2, 3, 5, 6]}); print({x for x in 'spam'}); print({c*4 for c in 'spam'}); S={c*4 for c in 'spam'}; print(S|{'mmm', 'xxxx'}); print('**************set usage*************'); L=[1,2,3,1,2,3,6]; print('L is', L); print(list(set(L))); engineers={'bob', 'sue', 'ann', 'vic'}; managers={'tom', 'sue'}; print('bob' in engineers); print(engineers & managers); print(engineers | managers); print(engineers-managers); print(managers-engineers); print(engineers>managers); print(engineers^managers); print('****************bool*************'); print(type(True)); print(isinstance(True, int)); print(True ==1); print(True is 1); print(True or False); print(True + 4);
Python
158
20.36076
73
/Programming/Python/5Number/variable.py
0.588741
0.504
guoyuquan/Graduate
refs/heads/master
def func(a, b, c=3, d=4): print(a, b, c, d) func(1, *(5,6))
Python
3
19.333334
25
/Programming/Python/18Parameter/5exer.py
0.47541
0.393443
guoyuquan/Graduate
refs/heads/master
def func(a, b=4, c=5): print(a, b, c) func(1, 2)
Python
3
15.666667
22
/Programming/Python/18Parameter/1exer.py
0.52
0.44
guoyuquan/Graduate
refs/heads/master
import sys; print('My {1[spam]} runs {0.platform}'.format(sys, {'spam': 'laptop'})); print('My {config[spam]} runs {sys.platform}'.format(sys=sys, config={'spam':'laptop'})); somelist=list('SPAM'); print(somelist); print('first={0[0]}, third={0[2]}'.format(somelist)); print('first={0}, last={1}'.format(somelist[0], somelist[-1])); parts=somelist[0], somelist[-1], somelist[1:3]; print('first={0}, last={1}, middle={2}'.format(*parts));
Python
9
47.666668
89
/Programming/Python/7String/complex.py
0.643836
0.605023
guoyuquan/Graduate
refs/heads/master
class Person: def __init__(self, name, job=None, pay=0): self.name = name self.job = job self.pay = pay if __name__ == '__main__': bob = Person('Bob') print(bob)
Python
9
18.111111
43
/Programming/Python/Class/fourth.py
0.575581
0.569767
guoyuquan/Graduate
refs/heads/master
S = 'spam' offset=0 for item in S: print(item, 'appears at offset', offset) offset+=1 print('***************************') for (offset, item) in enumerate(S): print(item+'appears at offset %d' % offset) for item in enumerate(S): print(item) E = enumerate(S) print(next(E)) #while E: # next(E) print([c * i for (i, c) in enumerate(S)])
Python
15
21.6
44
/Programming/Python/13Loop/enumerate.py
0.60177
0.59587
guoyuquan/Graduate
refs/heads/master
def changer(a, b): a = 2 b[0] = 'spam' X = 1 L = [1, 2] changer(X, L) print(X, L)
Python
7
11
18
/Programming/Python/18Parameter/changer.py
0.488095
0.428571
guoyuquan/Graduate
refs/heads/master
f = open('file_parse.py') L = f.readlines() L = [line.rstrip() for line in L] print(L) for line in L: print(line) for line in [l.rstrip() for l in open('file_parse.py')]: print(line) print('************************1*******************') for line in [l.upper() for l in open('file_parse.py')]: print(line) print('************************2*******************') for line in [l.split() for l in open('file_parse.py')]: print(line) print('************************3*******************') for line in [l.replace(' ', '!') for l in open('file_parse.py')]: print(line) print('************************4*******************') for (a, b) in [('sys' in l, l) for l in open('file_parse.py')]: print(a, b) print('***********************5********************') for line in [l for l in open('file_parse.py') if l[0] == 'f']: print(line)
Python
23
34.869564
65
/Programming/Python/14iteration/file_parse.py
0.452121
0.444848
guoyuquan/Graduate
refs/heads/master
L=[123, 'spam', 1.23]; print(L); print(len(L)); print(L[0]); print(L[:-1]); print(L+[4,5,6]); print(L); L=L+[6]; print(L); L.append('NI'); print(L); L.pop(2); print(L); L=['bb', 'aa', 'cc']; L.sort(); print(L); L.reverse(); print(L); M=[[1,2,3],[4,5,6],[7,8,9]]; print(M); print(M[1]); print(M[1][2]); #M[1]=L; print(M); col=[row[1] for row in M]; print(col); col=[row[1]+1 for row in M]; print(col); col=[row[1] for row in M if row[1]%2==0]; print(col); diag=[M[i][i] for i in [0, 1, 2]]; print(diag); doubles=(c*2 for c in 'spam'); print(doubles); G=(sum(row) for row in M); print(next(G)); print(next(G)); print(list(map(sum, M))); print({sum(row) for row in M}); print({i:sum(M[i]) for i in range(3)}); print([ord(x) for x in 'spam']); print({ord(x) for x in 'spam'}); print({x:ord(x) for x in 'spam'})
Python
43
17.767443
41
/Programming/Python/4ObjectType/list.py
0.560099
0.513011
guoyuquan/Graduate
refs/heads/master
def func(a, **kargs): print(a, kargs) func(a=1, c=3, b=2)
Python
3
18.666666
21
/Programming/Python/18Parameter/4exer.py
0.576271
0.525424
guoyuquan/Graduate
refs/heads/master
D = {'A':6, 'B': 6, 'C': 6} for key in D: print(key+" => %d" % D[key]) import os p = os.popen('pwd') print(p.next()) E = enumerate('spam') I=iter(E) print(next(I)) while True: try: print(next(I)) except StopIteration: break
Python
14
15.5
29
/Programming/Python/14iteration/other_iterator.py
0.577586
0.564655
guoyuquan/Graduate
refs/heads/master
print(list(map(ord, 'spam')))
Python
1
29
29
/Programming/Python/20HigherIterator/map.py
0.633333
0.633333
guoyuquan/Graduate
refs/heads/master
x = 10 while x: x=x-1 if x % 2 != 0: continue print(x)
Python
6
9
15
/Programming/Python/13Loop/continue.py
0.516667
0.433333
guoyuquan/Graduate
refs/heads/master
nudge = 1 wink = 2 nudge, wink = wink, nudge print(nudge, wink) print(type(nudge)) [a, b, c] = (1, 2, 3) print(a, c) (a, b, c) = "ABC" print(a, c) string='SPAM' a, b, c, d=string print(a, d) #a, b, c=string a, b, c = string[0], string[1], string[2:] print(a, b, c) print('****************************') a, b, c=list(string[:2])+[string[2:]] print(a, b, c) print('****************************') ((a, b), c)=('SP', 'AM') print(a, b, c) red, green, blue=range(3) print(red, blue) print('****************************') l = [1, 2, 3, 5, 6] while l: front, l = l[0], l[1:] print(front, l) for (a, b, c) in [(6, 6, 6), (6, 6, 6)]: print(a, b, c) #a, b, c='ab'
Python
31
20.161291
42
/Programming/Python/11Value_Statement_Print/equal_tuple.py
0.457317
0.420732
guoyuquan/Graduate
refs/heads/master
L = [1, 2, 3] for x in L: print(x**2) I = iter(L) while True: try: print(I.next()**2) except StopIteration: break
Python
9
12.444445
22
/Programming/Python/14iteration/auto_iterator.py
0.581967
0.540984
guoyuquan/Graduate
refs/heads/master
f=open('data.txt', 'w'); print(f.write('Hello\n')); f.write('World\n'); f.close(); f=open('data.txt'); text=f.read(); print(text); print(text.split()); print(dir(f)); data=open('data.txt', 'rb').read(); print(data); print(data[4:8]);
Python
12
18.5
35
/Programming/Python/4ObjectType/file.py
0.606838
0.598291
guoyuquan/Graduate
refs/heads/master
L1 = [1,2,3] L2 = [6, 6, 6] print(type(zip(L1, L2))) print(zip(L1, L2)) for (x, y) in zip(L1, L2): print(x, y, '--', x+y)
Python
6
19.5
26
/Programming/Python/13Loop/zip.py
0.495935
0.382114
guoyuquan/Graduate
refs/heads/master
X = 'Spam' def func(): X='Ni!' func() print(X)
Python
5
8.6
11
/Programming/Python/17Namespace/exer2.py
0.520833
0.520833
guoyuquan/Graduate
refs/heads/master
def func(a, *pargs): print(a, pargs) func(1, 2, 3)
Python
3
16.333334
20
/Programming/Python/18Parameter/3exer.py
0.596154
0.538462
guoyuquan/Graduate
refs/heads/master
class FirstClass: def setdata(self, value): self.data=value def display(self): print(self.data) F = FirstClass() F.setdata('some') F.display()
Python
8
17.625
26
/Programming/Python/Class/second.py
0.704698
0.704698
guoyuquan/Graduate
refs/heads/master
class Worker: def __init__(self, name, pay): self.name=name; self.pay=pay; def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay*=(1.0+percent); bob=Worker('Bob Smith', 50000); sue=Worker('Sue Jones', 60000); print(bob.lastName()); print(sue.lastName()); sue.giveRaise(.10); print(sue.pay);
Python
15
21.133333
31
/Programming/Python/4ObjectType/class.py
0.654655
0.60961
guoyuquan/Graduate
refs/heads/master
L = [6, 6, 6] for i in range(len(L)): L[i] += 10 print(L) print([x + 10 for x in L])
Python
5
16.200001
26
/Programming/Python/14iteration/list_parse.py
0.511628
0.430233
guoyuquan/Graduate
refs/heads/master
import sys from tkinter import Button, mainloop x = Button( text = 'Press me', command=(lambda: sys.stdout.write('Spam\n'))) x.pack()
Python
6
21.666666
46
/Programming/Python/19HighLevelFunction/tkinter.py
0.698529
0.698529
guoyuquan/Graduate
refs/heads/master
def f(a, b, c): print(a, b, c) f(1, 2, 3) f(c=1, b=2, a=3) def fun1(a, b=2, c=3): print(a, b, c, sep=',') fun1(6) fun1(1) fun1(6, 6, 6) def fun2(*args): print(args) fun2(1) fun2(6, 6) fun2(6, 6, "hello") def fun3(**args): print(args) fun3(a=1, b=2) def fun5(a, *b, **c): print(a, b, c) fun5(1, 2, 3, x=1, y=6) def kwonly(a, *b, c): print(a, b, c) kwonly(1, 2, c=3)
Python
23
15.130435
24
/Programming/Python/18Parameter/parameter.py
0.525606
0.41779
guoyuquan/Graduate
refs/heads/master
L = [1, 2, 3, 6, 6] print(sum(L)) print('any', any(L)) print('all', all(L)) print('max', max(L)) print('min', min(L)) print('&&'.join([l for l in open('test.py')])) print('**********************') Z = zip((1,2,3), (6, 6, 6,)) I=iter(Z) I2=iter(Z) print(I.next()) print(I2.next()) print(I.next()) print(I2.next()) print(next(I)) print(next(I2))
Python
19
17.210526
46
/Programming/Python/14iteration/internal.py
0.520231
0.476879
guoyuquan/Graduate
refs/heads/master
while True: name = raw_input('Enter name: ') if name == 'stop': break age = raw_input('Enter age: ') if age.isdigit(): print('Hello, '+name+' => ', int(age)**2) else: print('Bad age')
Python
9
20.666666
43
/Programming/Python/13Loop/break.py
0.574359
0.569231
guoyuquan/Graduate
refs/heads/master
class C1: def __init__(self, who): self.who=who #print(C1.who) I1=C1('bob') print(I1.who)
Python
6
14.5
25
/Programming/Python/Class/first_init.py
0.623656
0.569892
guoyuquan/Graduate
refs/heads/master
a=3; print(a); a='abc'; print(a); l=[1,2,3]; l2=l; print(l); print(l2); l.append(6); print(l); print(l2); l1=[]; l1=l2; l2.append(8); print(l1); print(l2);
Python
16
8.75
13
/Programming/Python/6DynamicType/test.py
0.564103
0.467949
guoyuquan/Graduate
refs/heads/master
f = open('next.py') print(next(f)) print(f.next()) L = [6, 6, 6] I = iter(L) print(iter(f) is f) while True: print(I.next())
Python
8
14.75
19
/Programming/Python/14iteration/next.py
0.579365
0.555556
guoyuquan/Graduate
refs/heads/master
while True: reply = raw_input('Enter text: ') if reply == 'stop': break elif not reply.isdigit(): print('Bad!'*8) else: print(int(reply)**2) print('Bye')
Python
9
17.222221
34
/Programming/Python/10Statement/robust.py
0.615854
0.603659
guoyuquan/Graduate
refs/heads/master
X = 'Spam' def func(): global X X='Ni' func() print(X)
Python
6
8.5
11
/Programming/Python/17Namespace/exer4.py
0.561404
0.561404
guoyuquan/Graduate
refs/heads/master
def multiple(x, y): x = 2 y = [3, 4] return x, y X = 1 L = [1, 2] X, L = multiple(X, L) print(X, L)
Python
8
11.875
21
/Programming/Python/18Parameter/ref_call.py
0.485437
0.427184
guoyuquan/Graduate
refs/heads/master
S='Python'; Y="Python"; print(S[0]); print(Y[1]); print(S[-1]); print(Y[-6]); print(S[1:3]); print(S[:]); print(S[:3]); print(S[1:]); print(S+'xyz'); print(S*8); S='z'+S[1:]; print(S); print(S.find('on')); print(S.replace('on', "XYZ")); print(S); line='aaa, bbb, ccc'; print(line.split(',')); print(S.upper); print(S.isalpha()); line='something\n'; print(line); print(line.rstrip()); print('%s, eggs, and %s'%('spam', "SPAM!")); print('{0}, eggs, and {1}'.format('spam', 'SPAM!')); print(dir(S)); print(len(S)); print(ord('\n')); msg="""aaaaa bbbbb cccc """ print(msg);
Python
34
15.764706
52
/Programming/Python/4ObjectType/string.py
0.566667
0.545614
guoyuquan/Graduate
refs/heads/master
D={'food':'spam', 'quantity':4, 'color':'pink'}; print(D['food']); D['quantity']+=1; print(D); Dic={}; Dic['name']='Bob'; Dic['job']='dev'; Dic['age']=40; print(Dic); rec={'name':{'first':'Bob', 'last':'Smith'}, 'job':['dev', 'mgr'], 'age':40.5}; print(rec['name']['last']); print(rec['job']); print(rec['job'][-1]); rec['job'].append('janitor'); print(rec); Ks=list(D.keys()); print(Ks); Ks.sort(); for key in Ks: print(key, '=>', D[key]); for c in 'spam': print(c.upper()); x=4; while x>0: print('spam!'*x); x-=1; for keys in sorted(D): print(keys, '=>', D[keys]); squares=[x**2 for x in[1,2,3,5,6]]; print(squares); squares=[]; for x in [1,2,3,5,6]: squares.append(x**2); print(squares); D['e']=99; print(D); #print(D['f']); if not 'f' in D: print('missing'); if 'f' in D: print("there"); value=D.get('x', 0); print(value); value=D['x'] if 'x' in D else 6; print(value);
Python
45
18.6
79
/Programming/Python/4ObjectType/dictionary.py
0.560091
0.529478
guoyuquan/Graduate
refs/heads/master
a = b = c ='spam' print(a, b, c)
Python
2
15.5
17
/Programming/Python/11Value_Statement_Print/multi.py
0.454545
0.454545
guoyuquan/Graduate
refs/heads/master
test=open('test.txt', 'w'); test.write('hello text\n'); print(test.write('goodbye text\n')); test.close(); test=open('test.txt'); print(test.readline()); print(test.readline()); print(test.readline()); test.close(); print(open('test.txt').read()); d={'a':1, 'b':2}; f=open('datafile.pk1', 'wb'); import pickle; pickle.dump(d, f); f.close(); f=open('datafile.pk1', 'rb'); e=pickle.load(f); print(d);
Python
18
21.166666
36
/Programming/Python/9TupleandFile/file.py
0.636591
0.626566
guoyuquan/Graduate
refs/heads/master
y=11 x=y//2 while x>1: if y % x == 0: print(y, 'has factor', x) break x-=1 else: print(y, 'is prime')
Python
9
11.111111
27
/Programming/Python/13Loop/else.py
0.53211
0.477064
guoyuquan/Graduate
refs/heads/master
title="the meaning";
Python
1
20
20
/Programming/Python/3Execution/myfile.py
0.714286
0.714286
guoyuquan/Graduate
refs/heads/master
X = 'Spam' def func(): X='Ni' def nested(): print(X) nested() func() print(X)
Python
8
9.375
14
/Programming/Python/17Namespace/exer5.py
0.554217
0.554217
guoyuquan/Graduate
refs/heads/master
from functools import reduce print(reduce((lambda x, y: x + y), [1, 2, 3])) print(reduce((lambda x, y: x * y), [1, 2, 3])) reduce((lambda x, y: x*y), [])
Python
4
37.5
46
/Programming/Python/19HighLevelFunction/reduce.py
0.577922
0.538961
oracid/IK-Inverse-Kinematics-for-3DOF-quadruped-robot-leg
refs/heads/main
from vpython import * canvas(width=1500, height=720, center=vector(00,70,0), background=color.white, range=150) sphere( pos=vector(0,0,0), radius=2, color=color.red) # Origin of the orthonormal coordinate system for i in range(-150,150,10): # Drawing floor for j in range(-150,150,10): # sphere( pos=vector(i,0,j), radius=0.3, color=color.black) # H =curve() # Diamond diagonal CL=curve() # Diamond left top side CR=curve() # Diamond right top side AL=curve() # Diamond left bottom side AR=curve() # Diamond right bottom side def IK(x,y,z): global H global CL global CR global AL global AR H.clear() CL.clear() CR.clear() AL.clear() AR.clear() d=Ay-y # X Y diagonal calculations e=x # h=sqrt((e*e)+(d*d)) # E=acos(d/h) # if(e<0): # E=(-E) # X=sin(E)*h # Y=cos(E)*h # G=acos(h/(2*c)) # diamond sides calculations Clx=sin(E-G)*c # Cly=cos(E-G)*c # Crx=sin(E+G)*c # Cry=cos(E+G)*c # dz=h # Z diagonal calculations ez=z # hz=sqrt((ez*ez)+(dz*dz)) # D=acos(dz/hz) # if(ez<0): # D=(-D) # Z=sin(D)*hz # H =curve( A.pos, vector(X,Ay-Y,Z), radius=0.1, color=color.magenta, retain=30 ) # diagonal line CL=curve( A.pos, vector(Clx,Ay-Cly,Z/2), radius=2, color=color.yellow ) # top left side line of the diamond CR=curve( A.pos, vector(Crx,Ay-Cry,Z/2), radius=2, color=color.green ) # top right side line of the diamond AL=curve( vector(X,Ay-Y,Z), vector(Clx,Ay-Cly,Z/2), radius=2, color=color.yellow ) # bottom left side line of the diamond AR=curve( vector(X,Ay-Y,Z), vector(Crx,Ay-Cry,Z/2), radius=2, color=color.green ) # bottom right side line of the diamond ################ Start Screw ################ c=112 # length of diamond side Ay=190 # coordinates of the main axis Ax=0 # Az=0 # A=sphere( pos=vector(Ax,Ay,0), radius=4, color=color.red) # main paw axis r=120 for i in range(0,1080,3): rate(80) sphere( pos=vector(sin(i/57.296)*r, i*0.06, cos(i/57.296)*r ), radius=1, color=color.red) while True: for i in range(0,1080,3): rate(30) IK(sin(i/57.296)*r, i*0.06, cos(i/57.296)*r ) for i in range(1080,0,-3): rate(30) IK(sin(i/57.296)*r, i*0.06, cos(i/57.296)*r ) ################ End Screw ################
Python
76
36.263157
130
/IKScrew.py
0.471802
0.427098
oracid/IK-Inverse-Kinematics-for-3DOF-quadruped-robot-leg
refs/heads/main
from vpython import * canvas(width=1500, height=720, center=vector(00,70,0), background=color.white, range=150) sphere( pos=vector(0,0,0), radius=2, color=color.red) # Origin of the orthonormal coordinate system for i in range(-150,150,10): # Drawing floor for j in range(-150,150,10): # sphere( pos=vector(i,0,j), radius=0.3, color=color.black) # H =curve() # Diamond diagonal CL=curve() # Diamond left top side CR=curve() # Diamond right top side AL=curve() # Diamond left bottom side AR=curve() # Diamond right bottom side def IK(x,y,z): global H global CL global CR global AL global AR H.clear() CL.clear() CR.clear() AL.clear() AR.clear() d=Ay-y # X Y diagonal calculations e=x # h=sqrt((e*e)+(d*d)) # E=acos(d/h) # if(e<0): # E=(-E) # X=sin(E)*h # Y=cos(E)*h # G=acos(h/(2*c)) # diamond sides calculations Clx=sin(E-G)*c # Cly=cos(E-G)*c # Crx=sin(E+G)*c # Cry=cos(E+G)*c # dz=h # Z diagonal calculations ez=z # hz=sqrt((ez*ez)+(dz*dz)) # D=acos(dz/hz) # if(ez<0): # D=(-D) # Z=sin(D)*hz # H =curve( A.pos, vector(X,Ay-Y,Z), radius=0.1, color=color.magenta, retain=30 ) # diagonal line CL=curve( A.pos, vector(Clx,Ay-Cly,Z/2), radius=2, color=color.yellow ) # top left side line of the diamond CR=curve( A.pos, vector(Crx,Ay-Cry,Z/2), radius=2, color=color.green ) # top right side line of the diamond AL=curve( vector(X,Ay-Y,Z), vector(Clx,Ay-Cly,Z/2), radius=2, color=color.yellow ) # bottom left side line of the diamond AR=curve( vector(X,Ay-Y,Z), vector(Crx,Ay-Cry,Z/2), radius=2, color=color.green ) # bottom right side line of the diamond ################ Start Zigzag ################ c=112 # length of diamond side Ay=200 # coordinates of the main axis Ax=0 # Az=0 # A=sphere( pos=vector(Ax,Ay,0), radius=4, color=color.red) # main paw axis Pz=[-70,-70,-70,-70,-70,-70,-70,-70,-70,-70,-70,-70,-70,-70,-70,-60,-50,-40,-30,-20,-10, 0, 10, 20, 30, 40, 50, 60, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70] Py=[ 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] Px=[-70,-60,-50,-40,-30,-20,-10, 0, 10, 20, 30, 40, 50, 60, 70, 60, 50, 40, 30, 20, 10, 0,-10,-20,-30,-40,-50,-60,-70,-60,-50,-40,-30,-20,-10, 0, 10, 20, 30, 40, 50, 60, 70] for i in range(0, 43,1): rate(20) sphere( pos=vector(Px[i],Py[i],Pz[i]), radius=1.5, color=color.red) # Path drawing with ball targets while True: for i in range(0, 43, 1): rate(20) IK(Px[i],Py[i],Pz[i]) for i in range(42,-1, -1): rate(20) IK(Px[i],Py[i],Pz[i]) ################ End Zigzag ################
Python
80
40.625
176
/IKZ.py
0.470968
0.372141
howeypeter/limelightCDN
refs/heads/master
#!/usr/bin/python import sys sys.path.append('./limelightCDN') import limelightCDN import ConfigParser import os import urllib2 profile='default' urL = "https://api.lldns.net/cfapi/v1/svcinst/delivery/manual/shortname/shutterfly" query = "" def read_conf(profile): config = ConfigParser.RawConfigParser() config.read([os.path.expanduser('~/.llnw/credentials')]) username = config.get(profile, 'username') apikey = config.get(profile, 'apikey') return username,apikey userName,apiKey = read_conf(profile) #make request usageReport = limelightCDN.Auth(apiKey) response = usageReport.GET(urL,userName,queryParameters=query) print response.read()
Python
27
23.407408
83
/Example.py
0.763278
0.760243
howeypeter/limelightCDN
refs/heads/master
#!/usr/bin/python import hashlib import hmac import time import os import urllib import urllib2 try: import simplejson as json except ImportError: import json class Auth: def __init__(self,apiKey): self.apiKey = apiKey return None def hmac( self, url, httpMethod="GET", queryParameters=None, postData=None): timestamp = str(int(round(time.time()*1000))) datastring = httpMethod + url if queryParameters != None : datastring += queryParameters datastring += timestamp if postData != None : datastring += postData self.postData = postData self.token = hmac.new(self.apiKey.decode('hex'), msg=datastring,digestmod=hashlib.sha256).hexdigest() #return token,timestamp return self.token,timestamp #built-in GET request for REST-API def GET( self, url, username, httpMethod="GET", queryParameters=None, postData=None): token,timestamp = self.hmac(url,httpMethod,queryParameters,postData) if queryParameters != None : url = url + "?" + queryParameters if postData != None : req = urllib2.Request(url, postData) else: req = urllib2.Request(url) req.add_header('Content-Type','application/json') req.add_header('Accept','application/json') req.add_header('X-LLNW-Security-Principal', username) req.add_header('X-LLNW-Security-Timestamp', timestamp) req.add_header('X-LLNW-Security-Token', token) response = urllib2.urlopen(req) return response
Python
57
24.578947
105
/limelightCDN/limelightCDN.py
0.701646
0.694102
thcoura/ZillaLibSamples
refs/heads/master
import os, glob, sys, subprocess, zipfile, shutil, time #read MSBUILD_PATH, OUT_DIR and ANDROID_* variables for signing APK files from external file 'build-all.cfg' (not checked into version control) MSBUILD_PATH = 'C:/Program Files (x86)/MSBuild/12.0/Bin/MSBuild.exe' OUT_DIR = 'Builds' WEB_GZ = False exec (file('build-all.cfg').read() if os.path.exists('build-all.cfg') else '') WEB_GZ = ('.gz' if WEB_GZ else '') #check if directories for unused assets already exist, abort if so assert not os.path.exists('Data-Unused'), 'Temporary asset directory "' + 'Data-Unused' + '" still exists, please check (crashed when executed last time?)' #build list of assets with path names in Data and in Data-Unused assets = [] for root, dirs, filenames in os.walk('Data'): for filename in filenames: assets += [[root.replace('\\','/') + '/' + filename,root.replace('Data','Data-Unused',1).replace('\\','/') + '/' + filename]] # platform specific setup zl_dir = os.path.realpath(__file__+'/../../ZillaLib').replace('\\', '/') if sys.platform == 'win32': os.environ['PATH'] += os.pathsep+zl_dir.replace('/', os.sep)+os.sep+'Tools' linux_cpu_type = 'x86_64' if sys.maxsize > 2**32 else 'x86_32' #options is_rebuild = 'rebuild' in sys.argv select_targets = [k for k in sys.argv if k in ['wasm','emscripten','nacl','android','win32','win64','linux','osx']] if select_targets == []: select_targets = ['wasm','android','win32','win64','linux','osx'] #create directories for unused assets while building samples that don't need them, and at first move all assets over for asset in assets: if not os.path.exists(os.path.dirname(asset[1])): os.makedirs(os.path.dirname(asset[1])) os.rename(asset[0], asset[1]) #create output dir if not os.path.exists(OUT_DIR): os.makedirs(OUT_DIR) #loop through all samples BuildLastRun = 0 for num in range(1, 99): try: snum = str(num).zfill(2); inl = (glob.glob(snum + "-*") or [''])[0] if not inl: continue inlcode = file(inl).read() oneasset = '' print '---------------------------------------------------------------------------------------------------------------------------------------------------------------------' print '[ASSETS] Building Sample',num,'("' + inl + '"):' for asset in assets: if (asset[0] in inlcode): os.rename(asset[1], asset[0]) print ' Used Asset:',asset[0] oneasset = asset[0] if oneasset: os.utime(oneasset, None) #touch asset file so assets get rebuilt while BuildLastRun >= int(time.time()):pass #must be at least the next second since last build ended, otherwise make can get confused def buildheader(typ): print '---------------------------------------------------------------------------------------------------------------------------------------------------------------------' print '[' + typ + '] Building Sample',num,'("' + inl + '"):' def buildfooter(): print '---------------------------------------------------------------------------------------------------------------------------------------------------------------------' print '' sys.stdout.flush() def building(pargs): print ' **** Executing:',pargs,'...' p = subprocess.Popen(pargs, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: l = p.stdout.readline() if not l: break if not l.strip(): continue sys.stderr.write(' ' + l.rstrip()[0:180] + "\n") sys.stderr.flush() pret = p.wait() assert pret == 0, ' BUILD RETURNED ERROR, ABORTING' global BuildLastRun BuildLastRun = int(time.time()) def buildcopy(src, trg): print ' **** Copying',src,'to',OUT_DIR+'/'+trg,'...' shutil.copy2(src, OUT_DIR+'/'+trg) def buildzip(trgzip, src, trg): print ' **** Zipping',src,'into',OUT_DIR+'/'+trgzip,'as',trg,'...' z = zipfile.ZipFile(OUT_DIR+'/'+trgzip,'w',zipfile.ZIP_DEFLATED); z.write(src, trg);[z.write(r+os.sep+f, r.replace(src, trg, 1)+os.sep+f) for r,d,fs in os.walk(src) for f in fs] z.close() def buildcheck(name, trg): if select_targets and name not in select_targets: return False return is_rebuild or not os.path.exists(OUT_DIR+'/'+trg) or os.path.getmtime(OUT_DIR+'/'+trg) < os.path.getmtime(inl) if sys.platform == 'win32': if buildcheck('wasm', 'ZillaLibSample-' + snum + '.js'+WEB_GZ): buildheader('WEBASSEMBLY') building(['make', '-j', '4', 'wasm-release', 'D=ZILLALIBSAMPLES_NUMBER=' + str(num), 'W=ZillaLibSampleMain.cpp' + (' ' + oneasset if oneasset else '')]) buildcopy('Release-wasm/ZillaLibSamples.js'+WEB_GZ, 'ZillaLibSample-' + snum + '.js'+WEB_GZ) buildfooter() if buildcheck('emscripten', 'ZillaLibSample-' + snum + '.js'+WEB_GZ): buildheader('EMSCRIPTEN') building(['make', '-j', '4', 'emscripten-release', 'D=ZILLALIBSAMPLES_NUMBER=' + str(num), 'W=ZillaLibSampleMain.cpp' + (' ' + oneasset if oneasset else '')]) buildcopy('Release-emscripten/ZillaLibSamples' + ('_WithData' if oneasset else '') + '.js'+WEB_GZ, 'ZillaLibSample-' + snum + '.js'+WEB_GZ) buildfooter() if buildcheck('nacl', 'ZillaLibSample-' + snum + '.pexe'+WEB_GZ): buildheader('NACL') building(['make', '-j', '4', 'nacl-release', 'D=ZILLALIBSAMPLES_NUMBER=' + str(num), 'W=ZillaLibSampleMain.cpp' + (' '+oneasset if oneasset else '')]) buildcopy('Release-nacl/ZillaLibSamples' + ('_WithData' if oneasset else '') + '.pexe'+WEB_GZ, 'ZillaLibSample-' + snum + '.pexe'+WEB_GZ) buildfooter() if buildcheck('android', 'ZillaLibSample-' + snum + '.apk'): buildheader('ANDROID') building(['make', '-j', '4', 'android-release', 'D=ZILLALIBSAMPLES_NUMBER=' + str(num), 'W=ZillaLibSampleMain.cpp']) building(['make', 'android-sign', 'SIGN_OUTAPK='+OUT_DIR+'/ZillaLibSample-' + snum + '.apk', 'SIGN_KEYSTORE='+ANDROID_SIGN_KEYSTORE, 'SIGN_STOREPASS='+ANDROID_SIGN_STOREPASS, 'SIGN_KEYALIAS='+ANDROID_SIGN_KEYALIAS, 'SIGN_KEYPASS='+ANDROID_SIGN_KEYPASS]) buildfooter() if buildcheck('win32', 'ZillaLibSample-' + snum + '_Win32.zip'): buildheader('WIN32') if os.path.exists('Release-vs2013\ZillaLibSampleMain.obj'): os.remove('Release-vs2013\ZillaLibSampleMain.obj') building('"'+MSBUILD_PATH+'" /p:Configuration=Release;Platform=Win32;CmdLinePreprocessorDefinitions="ZILLALIBSAMPLES_NUMBER=' + str(num) + (';ZILLALIBSAMPLES_HASDATA"' if oneasset else '";SkipDataAssets=1') + ' ZillaLibSamples-vs.vcxproj') buildzip('ZillaLibSample-' + snum + '_Win32.zip', 'Release-vs2013/ZillaLibSamples' + ('_WithData' if oneasset else '') + '.exe', 'ZillaLibSamples-' + snum + '.exe') buildfooter() if buildcheck('win64', 'ZillaLibSample-' + snum + '_Win64.zip'): buildheader('WIN64') if os.path.exists('Release-vs2013x64\ZillaLibSampleMain.obj'): os.remove('Release-vs2013x64\ZillaLibSampleMain.obj') building('"'+MSBUILD_PATH+'" /p:Configuration=Release;Platform=x64;CmdLinePreprocessorDefinitions="ZILLALIBSAMPLES_NUMBER=' + str(num) + (';ZILLALIBSAMPLES_HASDATA"' if oneasset else '";SkipDataAssets=1') + ' ZillaLibSamples-vs.vcxproj') buildzip('ZillaLibSample-' + snum + '_Win64.zip', 'Release-vs2013x64/ZillaLibSamples' + ('_WithData' if oneasset else '') + '.exe', 'ZillaLibSamples-' + snum + '.exe') buildfooter() if sys.platform == 'linux2': if buildcheck('linux', 'ZillaLibSample-' + snum + '_linux_' + linux_cpu_type + '.zip'): buildheader('LINUX') building(['make', '-j', '4', 'linux-release', 'D=ZILLALIBSAMPLES_NUMBER=' + str(num) + (' ZILLALIBSAMPLES_HASDATA' if oneasset else ''), 'W=ZillaLibSampleMain.cpp' + (' ' + oneasset if oneasset else '')]) buildzip('ZillaLibSample-' + snum + '_linux_' + linux_cpu_type + '.zip', 'Release-linux/ZillaLibSamples_' + linux_cpu_type + ('_WithData' if oneasset else ''), 'ZillaLibSample-' + snum) buildfooter() if sys.platform == 'darwin': if buildcheck('osx', 'ZillaLibSample-' + snum + '_osx.zip'): buildheader('OSX') building(['make', '-j', '4', 'osx-release', 'D=ZILLALIBSAMPLES_NUMBER=' + str(num) + (' ZILLALIBSAMPLES_HASDATA' if oneasset else '')]) buildzip('ZillaLibSample-' + snum + '_osx.zip', 'ZillaLibSamples-OSX.xcodeproj/Release/ZillaLibSamples.app', 'ZillaLibSample-' + snum + '.app') buildfooter() except: import traceback; traceback.print_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]); break; finally: #move all assets back to unused for building the next sample for asset in assets: if os.path.exists(asset[0]): os.rename(asset[0], asset[1]) #removing temporary directories for asset in assets: os.rename(asset[1], asset[0]) try: os.rmdir(os.path.dirname(asset[1])) except: pass
Python
151
56.178806
257
/build-all.py
0.613546
0.599886
dplusplus/anarchy_golf
refs/heads/master
while 1:print raw_input()
Python
1
25
25
/python/2.echo.py
0.730769
0.692308
dplusplus/anarchy_golf
refs/heads/master
while 1: s=raw_input() if s:print s
Python
3
11.666667
14
/python/8.delete_blank_lines.py
0.631579
0.605263