def apply(self, query): """ 引擎构建好后,即可解析query """ matched_items, special_post = self.searcher.search_match(query) sel = Selector(matched_items, special_post, self.rule_info) return sel.apply(query)
def get_selector(): # selector columns dataset = get_data(selector=False) train_data = dataset[dataset['rate'] > 0.0] test_data = dataset[dataset['rate'] < 0.0] train_data.reset_index(inplace=True, drop=True) test_data.reset_index(inplace=True, drop=True) columns = train_data.columns remove_columns = ['sample_id', 'rate'] features_columns = [ column for column in columns if column not in remove_columns ] x_train = train_data[features_columns] y_train = train_data['rate'] selector = Selector() select_columns = selector.get_select_features(x_train, y_train) select_columns.extend(remove_columns) remove_columns = [ column for column in train_data.columns if column not in select_columns ] train_data = train_data.drop(columns=remove_columns) test_data = test_data.drop(columns=remove_columns) dataset = pd.concat([train_data, test_data]) selector_name = os.path.join(ETLDATA_PATH, 'selector_features.csv') dataset.to_csv(selector_name, index=False)
def _parse_properties(self, htmltree): # Populate properties from selectors _properties = {} config_props = self.config['properties'] # Search for each property option for property in self._selector_properties: if property not in config_props: logging.info("No config found for {}".format(property)) continue logging.info('Working on {}'.format(property)) args = { 'selector': config_props[property], } if property in self._dates: args['is_date'] = True selector = Selector(**args) logging.info("Using selector \"{}\" with selector type {}".format( selector.selector, selector.SelectorType.__class__.__name__, )) result_text = selector.result(htmltree) logging.info('Found prop value {}'.format(result_text)) _properties[property] = result_text return _properties
class Manager(Toplevel): def __init__(self, master, writer, root, **kwargs): super().__init__(master, **kwargs) self.title("Settings") self.master = master self.writer = writer self.root = root self.record_of_names = {} self.selector = Selector(self, bg=self["bg"]) self.fake_frame_background = "white" self.fake_frame_place_info = {} self.selector.place(relx=0, rely=0, relwidth=1, relheight=1) def switch(self, widget, items, modifying=False): settings = Settings(self, widget, items, modifying) settings.place(relx=0, rely=0, relwidth=1, relheight=1) self.wait_window(settings) def switch_for_frame(self, board, tag, board_dims): settings = Settings_for_frame(self, board, tag, board_dims) settings.place(relx=0, rely=0, relwidth=1, relheight=1) self.wait_window(settings) def set_root(self, board): str_dimensions = self.writer.app_geometry.replace("+", " ").replace( "x", " ").split() dimensions = [int(dim) for dim in str_dimensions] settings = Settings_for_root(self, board, self.writer, self.writer.app_background, dimensions, self.writer.app_transparency) settings.place(relx=0, rely=0, relwidth=1, relheight=1) self.wait_window(settings)
def __init__(self, arg): # setting self.name_map = arg.name_map self.opt = Setting() # pygame pygame.init() self.screen = pygame.display.set_mode(self.opt.WINDOW_SIZE) pygame.display.set_caption(self.opt.TITLE % self.name_map) self.clock = pygame.time.Clock() self.set_grill_surface() # data self.path = os.path.dirname(__file__) self.path_img = os.path.join(self.path, "..", "src", "img") file = self.name_map + self.opt.LUA_FORMAT self.path_maps = os.path.join(self.path, "..", "src", "maps", file) self.create = not os.path.exists(self.path_maps) # objects self.builder = Builder(self) self.converter = Converter(self) self.images = Images(self) self.map = Map(self) self.selector = Selector(self) self.toolbar = Toolbar(self) # loop self.saved = True self.loop() pygame.quit()
def get_processing(self): # 最终处理数据生成特征的函数 dataset = self._get_data_plusaugmentation() boolean_columns = self._get_boolean_columns(dataset) remove_columns = ['id', 'score'] num_columns = list() # 摘取其余的特征 for column in dataset.columns: if column in remove_columns: continue if column in boolean_columns: continue num_columns.append(column) # 异常字段处理:手动分箱 abnormal_columns = [ 'online_shopping_num', 'logistics_num', 'financing_num', 'video_num', 'airplant_num', 'train_num', 'travel_num' ] abnormal_encoder_columns = list() for column in abnormal_columns: encoder_column = f'{column}_encoder' dataset[encoder_column] = dataset[column].apply( self._get_abnormal_label) abnormal_encoder_columns.append(encoder_column) dataset = pd.get_dummies(dataset, columns=abnormal_encoder_columns) #_get_abnormal_label函数只是把数据变成1234 但是要通过get_dummies变成哑变量0001 # 缺失值单独抽离特征:无效 这怎么可能有效啊!无语子 # 那既然这样无效的话 用什么办法处理缺失值呢? # 是认为 除了boolean特征和刚刚处理过的app使用次数特征之外 其余的0值就是missing data啦 # for column in num_columns: # # abnormal已处理过,continue # if column in abnormal_columns: # continue # column_name = f'{column}_missing' # dataset[column_name] = dataset[column].apply(self._get_missing_value) # 将bool类型重新组合 也就是交互特征啦 # 生成的特征有点过多了 可以考虑去掉 # dataset = self._recombine_boolean_columns(dataset, boolean_columns) # ??看看是啥特征 没看懂是在干嘛 # dataset = self._data_encoder(dataset, ['surfing_time', 'age']) # 业务逻辑特征 dataset = self._get_operation_features(dataset) if self.selector: train_data = dataset[dataset['score'] > 0] y_data = train_data['score'] x_data = train_data.drop(columns=['id', 'score']) # 选特征 select_features = Selector( ascending=self.ascending).get_select_features(x_data, y_data) select_features.extend(['id', 'score']) dataset = dataset[select_features] return dataset
def run(self): print 'hi, thread running' selector_obj = Selector() file_handler = FileHandler() #this won't work unless you make a separate thread. new_file = file_handler.monitor() self.results = selector_obj.validate(new_file) return
async def test_select_closed(self): """Select on a closed channel should return None""" sel = Selector() chan = Channel(2) await chan.close() sel.pop(chan) val = await sel.gather() self.assertEqual(val, (0, None))
def test_stop(self): """ Test .stop() """ sel = Selector(gt10, is_even, self.gens) sel.stop() self.assertEqual([], sel.gens) self.assertIsNone(sel.started) self.assertIsNone(sel.curr)
def child_by_text(self, txt, **kwargs): if "allow_scroll_search" in kwargs: allow_scroll_search = kwargs.pop("allow_scroll_search") name = self.jsonrpc.childByText(self.selector, Selector(**kwargs), txt, allow_scroll_search) else: name = self.jsonrpc.childByText(self.selector, Selector(**kwargs), txt) return AutomatorDeviceNamedUiObject(self.device, name)
def test_select_on(self): """ Test .select_on decorator """ sel = Selector(gt10) sel.select_on(gen1) self.assertEqual(1, len(sel.gens)) sel_gen = sel.gens[0] #self.assertEqual(gen1.__doc__, sel_gen.__doc__) self.assertEqual(gen1.__name__, sel_gen.__name__)
def __init__(self, ip, port, ReqeustHandle, **kwargs): self.loop = Selector() self.ip = ip self.port = port self.RequestHandle = ReqeustHandle self.kwargs = kwargs self.server = socket.socket() self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
def __prepareset(self, newSelector, namespaces=None): "Used by appendSelector and __setitem__" if not namespaces: namespaces = {} self._checkReadonly() if not isinstance(newSelector, Selector): newSelector = Selector((newSelector, namespaces), parent=self) if newSelector.wellformed: newSelector._parent = self # maybe set twice but must be! return newSelector
def Selecionar(): print('Informe o tipo de Consulta: C - COMPLETA | A - ATUALIZAÇÃO: ', end='') tipo = str(input()) print('Informe a Data INICIAL para a Consulta [YYYY-MM-DD]: ', end='') data_inicio = str(input()) print('Informe a Data FINAL para a Consulta [YYYY-MM-DD]: ', end='') data_final = str(input()) selecao = Selector( ) #Faz a seleção do conteudo dos tweets e insere em Banco de dados. selecao.select(tipo, data_inicio, data_final)
class TestSelector(Command): def __init__(self): super().__init__() self.testSelector = Selector([("row1", "op1", "op2", "op3")], (0, )) DriverStation.getInstance() def initialize(self): pass def execute(self): self.testSelector.selectorLogic()
def __init__(self, conf): self.conf = conf self.log = conf.get('log') self.site_statistic = SiteStatistics(conf['site_task_collect_db']) self.seed_statistic = SeedStatistics(conf['seed_task_collect_db']) self.scheduler = SiteSchedulerManager(self.conf, self.site_statistic, self.seed_statistic) self.selector = Selector(self.scheduler, self.conf) self.crawl_selector = CrawlSelector(self.log, conf['selector_conf'], conf['beanstalk_conf'], self.scheduler)
def get_processing(self): dataset = self._get_data() boolean_columns = self._get_boolean_columns(dataset) remove_columns = ['id', 'score'] num_columns = list() for column in dataset.columns: if column in remove_columns: continue if column in boolean_columns: continue num_columns.append(column) #异常字段处理:手动分箱 abnormal_columns = [ 'online_shopping_num', 'logistics_num', 'financing_num', 'video_num', 'airplant_num', 'train_num', 'travel_num' ] abnormal_encoder_columns = list() for column in abnormal_columns: encoder_column = f'{column}_encoder' dataset[encoder_column] = dataset[column].apply( self._get_abnormal_label) abnormal_encoder_columns.append(encoder_column) dataset = pd.get_dummies(dataset, columns=abnormal_encoder_columns) #缺失值单独抽离特征:无效 # for column in num_columns: # if column in abnormal_columns: # continue # column_name = f'{column}_missing' # dataset[column_name] = dataset[column].apply(self._get_missing_value) #将bool类型重新组合 dataset = self._recombine_boolean_columns(dataset, boolean_columns) #embedding #dataset = self._data_encoder(dataset,['surfing_time','age']) #业务逻辑特征 dataset = self._get_operation_features(dataset) if self.selector: train_data = dataset[dataset['score'] > 0] y_data = train_data['score'] x_data = train_data.drop(columns=['id', 'score']) #selects = Selector(ascending=self.ascending) select_features = Selector( ascending=self.ascending).get_select_features(x_data, y_data) select_features.extend(['id', 'score']) dataset = dataset[select_features] return dataset
def __init__(self, topic, user): self.topic = topic self.user = user self.user_loc = user.replace( '@', '__at__', ).replace('.', '__dot__') self.items = get_items_fb(['items', topic]) self.resp_sub_loc = ['response', topic, self.user_loc] res = Firebase.get_df(FB_URL, self.resp_sub_loc, False) self.responses = pd.DataFrame.from_dict(res, orient='index') self.item_selector = Selector(self.items)
def __init__(self, master, writer, root, **kwargs): super().__init__(master, **kwargs) self.title("Settings") self.master = master self.writer = writer self.root = root self.record_of_names = {} self.selector = Selector(self, bg=self["bg"]) self.fake_frame_background = "white" self.fake_frame_place_info = {} self.selector.place(relx=0, rely=0, relwidth=1, relheight=1)
def parse( self, url, html ): sel = Selector( html ) link = sel.xpath('//div[@class="menu_block"]/ul/li/a/@href') tmp = [] for u in link: if( u.find('www.gohappy.com.tw') != -1 ): tmp.append(u) else: tmp.append('http://www.gohappy.com.tw' + u) return True, tmp
def parse(self, url, html): sel = Selector(html) link = sel.xpath('//div[@class="menu_block"]/ul/li/a/@href') tmp = [] for u in link: if (u.find('www.gohappy.com.tw') != -1): tmp.append(u) else: tmp.append('http://www.gohappy.com.tw' + u) return True, tmp
def calculate(): room_key = str(request.form['room_key']) user_name = str(request.form['user_name']) if redis.client.hexists(room_key, 'outcome') == False: if (redis.client.hlen(room_key) != 0) & (redis.client.hget( room_key, 'host')['user_name'] == user_name): user_selector = Selector(redis.client.hgetall(room_key)) redis.client.hmset(room_key, {'outcome': user_selector.select()}) else: msg = { 'Data Processing, please revisit the page later. Thanks for your patience.' } return json.dumps(msg)
async def test_select_push(self): """Pushing on two channels should return the one with room""" sel = Selector() async with Channel(1) as chan1, Channel(1) as chan2: # Push to C2 first sel.push(chan1, 10) sel.push(chan2, 20) await chan1.push(11) val = await sel.gather() await chan1.close() self.assertEqual(val, (1, True)) self.assertEqual(await chan1.pop(), 11) self.assertEqual(await chan1.pop(), None) self.assertEqual(await chan2.pop(), 20)
class TCPServerBasic(object): """ TCP服务器 usage: server = TCPServer('0.0.0.0', 8000) server.run_forever() """ def __init__(self, ip, port, ReqeustHandle, **kwargs): self.loop = Selector() self.ip = ip self.port = port self.RequestHandle = ReqeustHandle self.kwargs = kwargs self.server = socket.socket() self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) def file(self): return self.server def setup(self, selector): selector.register(self, Selector.EVREADABLE) def on_readable(self): """ 服务器句柄可读 """ conn, addr = self.server.accept() connection = self.RequestHandle(conn, addr, **self.kwargs) hold = connection.begin() if hold is False: print("new connection aborted by", self.RequestHandle.__name__) connection.end() else: #print("new connection accepted.") connection.setup(self.loop) def on_writable(self): raise NotImplemented def run_forever(self): self.server.bind((self.ip, self.port)) self.server.listen(15) self.setup(self.loop) self.loop.run_forever()
def parse( self, url, html ): # This site has a Sitemap so parser will use Sitemap # The Url http://www.gohappy.com.tw/ is a standard start key url if( url == 'http://www.gohappy.com.tw/' ): # This Page will redriect to sitemap if( self.test_flag ): print 'Hihi' print self.config['name'] return False, [] return True, ['http://www.gohappy.com.tw/intro/sitemap.html'] elif( url == 'http://www.gohappy.com.tw/intro/sitemap.html' ): #Parse Sitemap sel = Selector( html ) block = sel.xpath('//div[@class="sitemap_group"]') #remove some Block tmp = [] # Create a tmp Url List for __block in block: #print __block.xpath('dl/dt/a/@title')[0] level1 = __block.xpath('dl/dd/ul/li/a/@href') level2 = __block.xpath('dl/dd/div/ul/li/a/@href') for u in level1: if ( u != '' ): if( u.find('www.gohappy.com.tw') != -1 ): tmp.append(u) else: tmp.append( 'http://www.gohappy.com.tw' + u ) for u in level2: if ( u != '' ): if( u.find('www.gohappy.com.tw') != -1 ): tmp.append(u) else: tmp.append( 'http://www.gohappy.com.tw' + u ) return True, tmp else: return False, []
def parse( self, url, html ): # Create XPath sel = Selector( html ) # Return State, New Link return True, []
def __init__(self, surfaceDest, gravityDir=DOWN, tutorialScheduler=None): """ constructeur. (thx captain obvious) entrée : surfaceDest : Surface principale de l'écran, sur laquelle s'affiche le jeu. """ self.initCommonStuff(surfaceDest, gravityDir, tutorialScheduler) self.arena = ArenaAspirin(surfaceDest, self.posPixelArena, ARENA_SIZE, 2) self.selectorPlayerOne = Selector(self.arena, 0) self.crawlerGravRift = ArenaCrawler(ARENA_SIZE) self.crawlerGravRift.config(RIGHT, DOWN) self.gravityMovementsRift = GravityMovements(LEFT, False, False) self.crawlerRegenRift = ArenaCrawler(ARENA_SIZE) self.crawlerRegenRift.config(LEFT, UP) self.crawlerGravRiftApply = ArenaCrawler(ARENA_SIZE) self.crawlerGravRiftApply.config(UP, RIGHT) self.nbAspirinTaken = 0 self.blinker = Blinker(self.arena) self.populateArena() self.arena.draw() pygame.display.flip()
def test_no_pause(self): """ Test Selector with stop_condition=gt10 and no pause condition """ sel = Selector(gt10, None, self.gens) expected = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 6, 7, 8, 9, 10] self.assertEqual(expected, list(sel))
def __init__(self, network, parent=None): super(MainWindow, self).__init__(parent) self.view = GraphicsView() self.scene = QtGui.QGraphicsScene(self) #self.scene.setSceneRect(network.left, network.bottom, # network.right - network.left, network.top - network.bottom) self.setCentralWidget(self.view) self.selector = Selector(self) self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.selector) self.setWindowTitle("Snake eye view of the streets of Singapore") self.add_network(network) self.view.setScene(self.scene)
def _setSelectorText(self, selectorText): """ :param selectorText: comma-separated list of selectors or a tuple of (selectorText, dict-of-namespaces) :exceptions: - :exc:`~xml.dom.NamespaceErr`: Raised if the specified selector uses an unknown namespace prefix. - :exc:`~xml.dom.SyntaxErr`: Raised if the specified CSS string value has a syntax error and is unparsable. - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if this rule is readonly. """ self._checkReadonly() # might be (selectorText, namespaces) selectorText, namespaces = self._splitNamespacesOff(selectorText) try: # use parent's only if available namespaces = self.parentRule.parentStyleSheet.namespaces except AttributeError: pass wellformed = True tokenizer = self._tokenize2(selectorText) newseq = [] expected = True while True: # find all upto and including next ",", EOF or nothing selectortokens = self._tokensupto2(tokenizer, listseponly=True) if selectortokens: if self._tokenvalue(selectortokens[-1]) == ',': expected = selectortokens.pop() else: expected = None selector = Selector((selectortokens, namespaces), parent=self) if selector.wellformed: newseq.append(selector) else: wellformed = False self._log.error(u'SelectorList: Invalid Selector: %s' % self._valuestr(selectortokens)) else: break # post condition if u',' == expected: wellformed = False self._log.error(u'SelectorList: Cannot end with ",": %r' % self._valuestr(selectorText)) elif expected: wellformed = False self._log.error(u'SelectorList: Unknown Syntax: %r' % self._valuestr(selectorText)) if wellformed: self.seq = newseq
def test_pause(self): """ Test Selector with stop_condition=gt10 and pause_condition=is_even """ sel = Selector(gt10, is_even, self.gens) expected = [5, 1, 7, 3, 9, 5, 7, 9] self.assertEqual(expected, list(sel))
def xpath(self, xpath_expr: str): """ xpath语法 :return: """ selector = Selector(self.content, xpath_expr=xpath_expr) return selector
def __init__(self, redis, events, periodics=[], select=[]): self.logger = logging.getLogger('reactor') self.selector = Selector(select) self.db = ReactorDB(redis) self.mapper = dict(self.mapper_gen(events)) self.periodics = periodics self.timeline = SortedDict() self.load()
def __init__(self, auth=False): self.proto = ProtoConnection(self.session) self.auth = auth if self.auth: self.sasl = SASL(self.proto) else: self.sasl = self.proto self._lock = RLock() self.condition = Condition(self._lock) self.waiter = Waiter(self.condition) self.selector = Selector.default() self.timeout = 120
def initialize_routes(config): """ Initialize a new selector that maps routes to surrogate-key generation. At the moment this is an empty map to which things can be added (see test_entity_to_keys). However, it ought to be possible to put all the (relevant) routes in this map and forgo the procedural code in current_uri_keys. Another option is to, at startup, wrap handlers in another handler which properly generates keys. That version needs to be tried to see if it is more tidy than this. """ fastly_selector = Selector() def not_found(environ, start_response): return [] fastly_selector.status404 = not_found fastly_selector.status405 = not_found config['fastly.selector'] = fastly_selector
def __init__(self, xml): DbusPipeline.__init__(self, 'Pipeline') Selector.__init__(self, xml) pipeline_tree = etree.parse(xml) root = pipeline_tree.xpath("/pipelines") self.__description__ = xml self.__thread__ = None self.__stopthread__ = False self.__dic__ = root[0].find("dic").get("file") self.__hmm__ = root[0].find("hmm").get("file") self.__pipeline__ = gst.parse_launch('gsettingsaudiosrc ! audioconvert ! audioresample ' + '! vader auto-threshold=true ! pocketsphinx name=asr ! fakesink') self.__lm__ = self.__getdefault__() self.__previoushyp__ = "" asr = self.__pipeline__.get_by_name('asr') asr.set_property('hmm', self.__hmm__) asr.set_property('dict', self.__dic__) asr.set_property('lmctl', self.__lmctl__) asr.set_property("lmname", self.__lm__) asr.connect('result', self.__onresult__)
def __init__(self, surfaceDest, gravityDir=DOWN, tutorialScheduler=None): """ constructeur. (thx captain obvious) entrée : surfaceDest : Surface principale de l'écran, sur laquelle s'affiche le jeu. """ self.initCommonStuff(surfaceDest, gravityDir, tutorialScheduler) self.arena = ArenaBasic(surfaceDest, self.posPixelArena, ARENA_SIZE, 2) self.selectorPlayerOne = Selector(self.arena, 0) self.populateArena() self.arena.draw() pygame.display.flip()
def __init__(self, app_conf): self.app_conf = app_conf self.sess_key = 'openid.amp.fm.gateway' self.base_url = self.app_conf['base_url'] self.ekey = 'openidgateway' self.urls = [ ('[/]', {'GET': self.index}), ('/login[/]', {'GET': self.login, 'POST': self.login}), ('/complete[/]', {'GET': self.complete, 'POST': self.complete}), ('/transform/openid-redirect.xsl', {'GET': self.openid_redirect_xslt}), ] self._s = Selector(self.urls) if self.app_conf.get('debug', False): self._s.add('/forms[/]', {'GET': self.forms}) self.store = filestore.FileOpenIDStore('./cache')
def __init__(self, surfaceDest, gravityDir=DOWN, tutorialScheduler=None, xyFirstTouillette=(2, 5)): """ constructeur. (thx captain obvious) entrée : surfaceDest : Surface principale de l'écran, sur laquelle s'affiche le jeu. """ self.initCommonStuff(surfaceDest, gravityDir, tutorialScheduler) self.nbTouilletteToRemove = 2 self.mustDisplayRemoving = False self.arena = ArenaTouillette(surfaceDest, self.posPixelArena, ARENA_SIZE, 2, LIST_CHIP_GENERATION) self.selectorPlayerOne = Selector(self.arena, 0) self.populateArena() self.arena.addBigObject(Touillette, pyRectTuple(xyFirstTouillette)) self.arena.draw() pygame.display.flip()
def post(self, request): try: #import pdb; pdb.set_trace() req = Request(request.environ) log.debug('Received HTTP Request: %s', req) print 'these are the request.params: ', request.params print "request.environ is" , request.environ #print "request.environ['CONTENT_LENGTH'] is" , request.environ['CONTENT_LENGTH'] print "FULL RAW POST Data:" #this CONTENT_LENGTH wasn't getting populated in the environment on remote installations using encryption #print request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH'])) print request.environ['wsgi.input'].read(req.content_length) print "FULL request.POST Data:" print request.POST postdatakeys = request.POST.keys() print "keys are:", postdatakeys #accept only one posted file per request for now stream_fieldstorage = request.POST[postdatakeys[0]] print "size of post data in bytes", len(stream_fieldstorage.value) #print "CGI FileStorage uploaded is: ", myfile #Create a file in a permanent location, moving it out of CGI FieldStorage #make file file_prefix = 'received_data_' + str(datetime.datetime.now()) file_prefix = file_prefix.replace(' ', '_') file_suffix_enc = '_encrypted.xml' file_suffix_unenc = '_unencrypted.xml' if inputConfiguration.USE_ENCRYPTION: print "using encryption" file_name = file_prefix + file_suffix_enc elif not inputConfiguration.USE_ENCRYPTION: print "not using encryption" file_name = file_prefix + file_suffix_unenc else: print "not sure if using encrypted file or not" if not os.path.exists(inputConfiguration.WEB_SERVICE_INPUTFILES_PATH[0]): os.mkdir(inputConfiguration.WEB_SERVICE_INPUTFILES_PATH[0]) file_full_path = os.path.join(inputConfiguration.WEB_SERVICE_INPUTFILES_PATH[0], file_name) print 'file_full_path: ', file_full_path #open file if inputConfiguration.USE_ENCRYPTION: try: print "trying to open encrypted file" encrypted_file = open(file_full_path, 'w') except: print "Error opening encrypted instance file for writing" raise Exception("Error opening encrypted instance file for writing") if not inputConfiguration.USE_ENCRYPTION: try: print "trying to open unencrypted file" unencrypted_file = open(file_full_path, 'w') except: print "Error opening unencrypted instance file for writing" raise Exception("Error opening unencrypted instance file for writing") #write to file if inputConfiguration.USE_ENCRYPTION: print 'writing', file_name, 'to', server_root, 'for decryption' print 'encrypted_file is', encrypted_file encrypted_file.write(stream_fieldstorage.value) encrypted_file.close() if not inputConfiguration.USE_ENCRYPTION: print 'writing', file_name, 'to', server_root, 'server root for parsing' print 'unencrypted_file is', unencrypted_file unencrypted_file.write(stream_fieldstorage.value) unencrypted_file.close() #check if a file was written, regardless of encryption if not os.path.exists(file_full_path): print "A file wasn't written" else: print "A file was written at: ", file_full_path #decrypt file if using decryption #assume file is encrypted, since it can be difficult to tell if it is. We could look for XML structures, but how do you easily tell bad/invalid XML apart from encrypted? If not encrypted, that's a problem. #decrypt file if inputConfiguration.USE_ENCRYPTION: try: encrypted_file = open(file_full_path, 'r') except: print "couldn't open encrypted file for reading/decryption" raise Exception("couldn't open encrypted file for reading/decryption") data_decrypted = False encoded_stream = encrypted_file.read() encrypted_file.close() cryptors = [DES3, GPG] for cryptor in cryptors: cobj = cryptor() try: if cobj.__class__.__name__ == 'DES3': keyiv = get_incoming_3des_key_iv() # decode base64 stream encrypted_stream = base64.b64decode(encoded_stream) # decrypt stream decrypted_stream = cobj.decrypt(str(encrypted_stream), keyiv['key'], iv=keyiv['iv']) # test if the resulting decrypted_stream is XML xml_test = etree.XML(decrypted_stream) data_decrypted = True xml_test = None break if cobj.__class__.__name__ == 'GPG': # decode base64 stream encrypted_stream = base64.b64decode(encoded_stream) # decrypt stream decrypted_stream = cobj.decrypt(str(encrypted_stream)) # test if the resulting decrypted_stream is XML xml_test = etree.XML(decrypted_stream) data_decrypted = True xml_test = None break except: continue if data_decrypted: file_suffix_unenc = '_decrypted.xml' file_name = file_prefix + file_suffix_unenc #file_full_path = fileutils.getUniqueFileNameForMove(file_name, inputConfiguration.INPUTFILES_PATH[0]) file_full_path = inputConfiguration.WEB_SERVICE_INPUTFILES_PATH[0] + '/' + file_name try: decrypted_file = open(file_full_path, 'w') except: print "Error opening decrypted instance file for writing" raise Exception("Error opening decrypted instance file for writing") #write to file print 'writing', file_name, 'to', server_root, 'to validate' decrypted_file.write(decrypted_stream) decrypted_file.close() if not os.path.exists(file_full_path): print "An decrypted file wasn't written" else: print "A file was written at: ", file_full_path else: message = "Unable to decrypt %s or the decoded|decrypted data is not valid XML" % file_full_path print message raise Exception(message) #read in candidate XML file # if inputConfiguration.USE_ENCRYPTION: # try: # unencrypted_file = open(file_full_path, 'r') # except: # print "couldn't open decrypted file for reading" # # if inputConfiguration.USE_ENCRYPTION: # try: # unencrypted_file = open(file_full_path, 'r') # except: # print "couldn't open unencrypted file for reading" # remove multiple source tags incoming_doc = etree.parse(file_full_path) ns='{https://raw.githubusercontent.com/211tbc/synthesis/master/src/xsd/TBC_Extend_HUD_HMIS.xsd}' for i, src in enumerate(incoming_doc.findall('{0}Source'.format(ns))): if i == 0: # we only care about the first one continue # remove the remaning source tags incoming_doc.getroot().remove(src) incoming_doc.write(file_full_path, pretty_print=True, encoding="UTF-8") except Exception as e: response = Response() response.status = '500 Server Error' response.body = file_full_path + '\n' + str(e) message = '@@@@@@@@@@@@@\nHTTP RESPONSE -- %s; %s\n@@@@@@@@@@@@@' % (response.status, response.body) print message return response # FBY :07/31/2017: Its assumed that we have a file so record that fact that it was received in the # last_date_time table db = DB() session = db.Session() try: # Assume that record exists so update it lifecycle_event = session.query(LastDateTime).filter(LastDateTime.event == 'file received').first() lifecycle_event.event_date_time = datetime.datetime.now() session.add(lifecycle_event) session.commit() except: # Assume that record does not exist so insert it lifecycle_event = LastDateTime(event='file received', event_date_time=datetime.datetime.now()) session.add(lifecycle_event) session.commit() # validate XML instance try: select = Selector() result = select.validate(file_full_path, False) this_schema = result.index(True) schema_name = select.current_tests[this_schema].__name__ if len(schema_name) > 4: schema_name = schema_name[:len(schema_name) - 4] response = Response() response.status = '202 Successful Validation' response.body = 'The posted xml (locally at %s) successfully validated against the %s schema.' % (file_name, schema_name) message = '@@@@@@@@@@@@@\nHTTP RESPONSE -- %s; %s\n@@@@@@@@@@@@@' % (response.status, response.body) print message # move valid file over to regular synthesis input_files directory for shredding print "moving valid file ", file_name, "over to input_files for shredding" # FBY: Call fileutils.moveFile to move unencrypted files into the input_files folder fileutils.moveFile(file_full_path, inputConfiguration.INPUTFILES_PATH[0]) return response except: details = ''.join(list(set([str(issue) for issue in select.issues]))) response = Response() response.status = '200 Unsuccessful Validation' response.body = 'Could not find a matching schema for the posted xml. Details: %s' % (details) message = '@@@@@@@@@@@@@\nHTTP RESPONSE -- %s; %s\n@@@@@@@@@@@@@' % (response.status, response.body) print message return response
class OpenIdGateway(object): def __init__(self, app_conf): self.app_conf = app_conf self.sess_key = 'openid.amp.fm.gateway' self.base_url = self.app_conf['base_url'] self.ekey = 'openidgateway' self.urls = [ ('[/]', {'GET': self.index}), ('/login[/]', {'GET': self.login, 'POST': self.login}), ('/complete[/]', {'GET': self.complete, 'POST': self.complete}), ('/transform/openid-redirect.xsl', {'GET': self.openid_redirect_xslt}), ] self._s = Selector(self.urls) if self.app_conf.get('debug', False): self._s.add('/forms[/]', {'GET': self.forms}) self.store = filestore.FileOpenIDStore('./cache') def __call__(self, environ, start_response): return self._s(environ, start_response) def get_consumer(self, sess): return consumer.Consumer(sess, self.store) def index(self, environ, start_response): url = ''.join([self.base_url, 'login']) raise HTTPSeeOther(location=url) def login(self, environ, start_response): req = Request(environ) set_template(environ, 'login.xslt') sess = environ['beaker.session'] params = {'base_uri': self.base_url} if not sess.get(self.ekey): sess[self.ekey] = {} sess.save() headers = [('Content-Type', 'application/xml')] if not (req.params.get('uname') or req.params.get('return_location')): message ='There must be a uname and return_location in the query string' raise HTTPBadRequest(detail=message) openid_url = req.params['uname'] sess[self.ekey]['return_location'] = req.params['return_location'] if not openid_url: # this seems better ... # raise HTTPBadRequest("need openid_url") params['message'] = "Don't leave your name blank." params['status'] = 'failure' set_params(environ, params) start_response('200 OK', headers) return [] consumer = self.get_consumer(sess[self.ekey]) try: request = consumer.begin(openid_url) except Exception, exc: params['message'] = 'Error in discovery: %s' % (cgi.escape(str(exc[0]))) params['status'] = 'failure' set_params(environ, params) start_response('200 OK', headers) return [] if request is None: errcode = cgi.escape(post['openid_url']) params['message'] = 'No OpenID services found for <code>%s</code>' % (errcode) params['status'] = 'failure' set_params(environ, params) start_response('200 OK', headers) return [] #sreg_request = sreg.SRegRequest(required=['nickname']) #request.addExtension(sreg_request) return_to = '%scomplete'% self.base_url return_to = '%s?identity=%s' % (return_to, openid_url) trusted_root = self.base_url sess[self.ekey]['trusted_root'] = trusted_root redirect_url = request.redirectURL(trusted_root, return_to) set_params(environ, {'redirect_url': redirect_url}) params['status'] = 'redirect' params['message'] = 'OpendID Login Redirection' sess.save() set_params(environ, params) start_response('200 OK', headers) return []
class GameAspirin(GameBasic): """ classe qui gère tout le jeu. """ def __init__(self, surfaceDest, gravityDir=DOWN, tutorialScheduler=None): """ constructeur. (thx captain obvious) entrée : surfaceDest : Surface principale de l'écran, sur laquelle s'affiche le jeu. """ self.initCommonStuff(surfaceDest, gravityDir, tutorialScheduler) self.arena = ArenaAspirin(surfaceDest, self.posPixelArena, ARENA_SIZE, 2) self.selectorPlayerOne = Selector(self.arena, 0) self.crawlerGravRift = ArenaCrawler(ARENA_SIZE) self.crawlerGravRift.config(RIGHT, DOWN) self.gravityMovementsRift = GravityMovements(LEFT, False, False) self.crawlerRegenRift = ArenaCrawler(ARENA_SIZE) self.crawlerRegenRift.config(LEFT, UP) self.crawlerGravRiftApply = ArenaCrawler(ARENA_SIZE) self.crawlerGravRiftApply.config(UP, RIGHT) self.nbAspirinTaken = 0 self.blinker = Blinker(self.arena) self.populateArena() self.arena.draw() pygame.display.flip() def populateArena(self): """ overriden """ for (coordX, coordY) in LIST_COORD_ASPRO_HALF_LEFT: tileToHardDefine = self.arena.getTile(pyRect(coordX, coordY)) tileToHardDefine.chip = ChipAsproHalfLeft() for (coordX, coordY) in LIST_COORD_ASPRO_HALF_RIGHT: tileToHardDefine = self.arena.getTile(pyRect(coordX, coordY)) tileToHardDefine.chip = ChipAsproHalfRight() def applyGravity(self): """ zonc """ securedPrint(u" applyGravity") #TRODO : une fonction/propriété, au lieu de ce len de merte. if len(self.gravityMovements.dicMovement) > 0: param = (self.crawlerGrav, self.gravityMovements, None) self.arena.applyGravity(*param) elif len(self.gravityMovementsRift.dicMovement) > 0: param = (self.crawlerGravRiftApply, self.gravityMovementsRift, self.crawlerRegenRift) self.arena.applyGravity(*param) self.arena.regenerateAllChipsAfterOneGravity(self.crawlerRegenRift) else: self.arena.removeHalfAsproBottom() def _determineAnyGravity(self): param = (self.crawlerGrav, self.gravityMovements) self.gravityMovements = self.arena.determineGravity(*param) #pas besoin de controler None ? gravNormalToDo = (self.gravityMovements is not None and len(self.gravityMovements.dicMovement) > 0) if gravNormalToDo: return True param = (self.crawlerGravRift, self.gravityMovementsRift) self.gravityMovementsRift = self.arena.determineGravityFullSegment(*param) gravColumnToDo = (self.gravityMovementsRift is not None and len(self.gravityMovementsRift.dicMovement) > 0) if gravColumnToDo: return True return False def needStabilization(self): """ overriden """ securedPrint(u"needStabilization") anyGravToDo = self._determineAnyGravity(); if anyGravToDo: securedPrint(u"needStabilization TRUE") return True if self.arena.hasAnyHalfAsproInBottom(): securedPrint(u"needStabilization true") return True securedPrint(u"needStabilization false") return False def handleGravity(self): securedPrint(u"handleGravity aspro") self.applyGravity() # Morceaux copié-collé exactement de GameBasic.handleGravity if self.needStabilization(): self.gravityCounter = DELAY_GRAVITY else: #arrache un peu no ? Réponse : oui. double-arrache. if (self.tutorialScheduler is None or not self.tutorialScheduler.mustLockGameStimuli() ): self.selectorPlayerOne.setStimuliLock(False) def gameStimuliInteractiveTouch(self): """ overriden """ #self.blinker.startBlink((pyRect(2, 2), pyRect(3, 2), pyRect(4, 2))) if self.arena.getAndResetTakenAsproFull(): self.nbAspirinTaken += 1 if self.nbAspirinTaken == NB_ASPIRIN_TO_TAKE: listTextWin = language.LIST_TEXTS_WIN[language.languageCurrent] self.console.addListTextAndDisplay(listTextWin, COLOR_WIN) else: textYeah = language.TEXT_YEAH[language.languageCurrent] self.console.addListTextAndDisplay((textYeah, )) if self.tutorialScheduler is None: strBla = u"%d/%d" % (self.nbAspirinTaken, NB_ASPIRIN_TO_TAKE) self.console.addListTextAndDisplay((strBla, ))
def OnInit(self): self.selector = Selector() self.init_frame() return True
class SampleApp(wx.App): def OnInit(self): self.selector = Selector() self.init_frame() return True def init_frame(self): self.frm_main = wx.Frame( None, wx.ID_ANY , "Quiz Script for QMAClone" , size=(400, 200) ) self.frm_main.Centre() self.panel = wx.Panel(self.frm_main) self.sizer_vbox = wx.BoxSizer(wx.VERTICAL) self.panel.SetSizer(self.sizer_vbox) self.sizer_1st = wx.BoxSizer() self.sizer_vbox.Add(self.sizer_1st, wx.TOP | wx.ALIGN_CENTER) self.sizer_2nd = wx.BoxSizer() self.sizer_vbox.Add(self.sizer_2nd, wx.TOP | wx.ALIGN_CENTER) self.sizer_3rd = wx.BoxSizer() self.sizer_vbox.Add(self.sizer_3rd, wx.TOP | wx.ALIGN_CENTER) self.sizer_4th = wx.BoxSizer() self.sizer_vbox.Add(self.sizer_4th, wx.TOP | wx.ALIGN_CENTER) # 1st column ## member self.sizer_1st.Add( wx.StaticText(self.panel, label="人数: ") , flag=wx.TOP | wx.ALIGN_CENTER ) element_array = [] for i in range(2,8+1): element_array.append(str(i)) self.combo_number = wx.ComboBox(self.panel, wx.ID_ANY, "" , choices = element_array, style=wx.CB_READONLY , size = (50,-1) ) self.combo_number.SetSelection(2) self.sizer_1st.Add(self.combo_number, flag=wx.TOP | wx.ALIGN_CENTER) ## Max Quiz Number self.sizer_1st.Add(wx.StaticText(self.panel, label="最大問題番号: ") , flag=wx.TOP | wx.ALIGN_CENTER) self.txt_max_quiz = wx.TextCtrl(self.panel, value=str(setting.MAX_QUIZ_NUM) , size = (50,-1)) self.txt_max_quiz.SetMaxLength(4) self.sizer_1st.Add(self.txt_max_quiz, flag=wx.TOP | wx.ALIGN_CENTER) ## rate self.sizer_1st.Add(wx.StaticText(self.panel, label="レート: ") , flag=wx.TOP | wx.ALIGN_CENTER) self.txt_rate = wx.TextCtrl(self.panel, value=str(setting.RATE) , size=(50,-1)) self.txt_rate.SetMaxLength(5) self.sizer_1st.Add(self.txt_rate, flag=wx.TOP | wx.ALIGN_CENTER) # 2nd Column ## Quiz Number self.txt_quiz_number = wx.StaticText(self.panel, label="Quiz Number") font = wx.Font(20,wx.FONTFAMILY_DEFAULT,wx.FONTSTYLE_NORMAL,wx.FONTWEIGHT_NORMAL) self.txt_quiz_number.SetFont(font) self.txt_quiz_number.SetForegroundColour("#0000FF") self.sizer_2nd.Add(self.txt_quiz_number, flag=wx.TOP | wx.ALIGN_CENTER) ## Total Money self.sizer_2nd.Add(wx.StaticText(self.panel, label="total: ") , flag=wx.TOP | wx.ALIGN_CENTER) self.txt_total_money = wx.StaticText(self.panel, label="0" , size = (50,-1)) self.sizer_2nd.Add(self.txt_total_money, flag=wx.TOP | wx.ALIGN_CENTER) # 3rd Column ## Money List self.grid_money_list = gridlib.Grid(self.panel) self.grid_money_list.CreateGrid(1, setting.MEMBER) for i in range(0, setting.MEMBER): self.grid_money_list.SetColLabelValue(i, str(i+1) + "位") self.grid_money_list.SetCellValue(0, i, "") self.grid_money_list.SetRowLabelSize(0) self.grid_money_list.AutoSize() self.sizer_3rd.Add(self.grid_money_list, flag=wx.TOP | wx.ALIGN_CENTER) # 4th Column ## Shuffle Button self.btn_quiz = wx.Button(self.panel) self.btn_quiz.SetLabel("Shuffle") self.btn_quiz.Bind(wx.EVT_BUTTON, self.on_shuffle) self.sizer_4th.Add(self.btn_quiz, 0, flag=wx.TOP | wx.ALIGN_CENTER) self.frm_main.Show() def on_shuffle(self, event): # Get Value from text_ctrl setting.MEMBER = int( self.combo_number.GetValue() ) setting.MAX_QUIZ_NUM = int( self.txt_max_quiz.GetValue() ) setting.RATE = int( self.txt_rate.GetValue() ) # Next Quiz self.selector.shuffle() self.txt_quiz_number.SetLabel(str(self.selector.quiz)) self.txt_total_money.SetLabel(str(self.selector.total_money)) # Reset Grid self.grid_money_list.ClearGrid() w = self.grid_money_list.GetNumberCols() diff = setting.MEMBER - w if diff > 0: self.grid_money_list.AppendCols(diff) elif diff < 0: self.grid_money_list.DeleteCols(0, abs(diff)) self.grid_money_list.SetSize( (1, setting.MEMBER) ) for i in range(0, setting.MEMBER): self.grid_money_list.SetColLabelValue(i, str(i+1) + "位") self.grid_money_list.SetCellValue(0, i , str(self.selector.money_list[i])) self.grid_money_list.AutoSize()
def __init__(self, connection): self.connection = connection self._lock = self.connection._lock self._selector = Selector.default() self.reset()
class Reactor(object): def __init__(self, redis, events, periodics=[], select=[]): self.logger = logging.getLogger('reactor') self.selector = Selector(select) self.db = ReactorDB(redis) self.mapper = dict(self.mapper_gen(events)) self.periodics = periodics self.timeline = SortedDict() self.load() def time(self): return itime() def mapper_gen(self, events): for event in events: yield event.type(), event def __getitem__(self, name): return self.selector.get(name) def add_to_queue(self, event, time): self.selector.process(event) self.get(time).append(event) def load(self): for time, event_queue in self.db.event_models: for event_db in event_queue: event = self.mapper.get(event_db.type.get()) if event: self.add_to_queue(event(**event_db.params.get()), time=time) def flush(self): self.timeline.clear() self.selector.clear() def get(self, time): queue = self.timeline.get(time) if queue is None: queue = self.timeline[time] = [] return queue def append(self, event, tdelta=None, time=None): time = time or self.time() + tdelta self.add_to_queue(event, time) self.db.dump(time, event) return time def wait_for_calc(self, time): done = False while self.timeline and not done: smallest_time, events = self.timeline.smallest_item() if smallest_time <= time: yield smallest_time, events else: done = True def remove_events(self, time): if time in self.timeline: del self.timeline[time] self.db.remove_item(time) def execute(self, event, time): try: event.do(self, time) except Exception: self.logger.error('%s executing at %s' % (event, time), exc_info=1) def calc(self, time=None): time = time or self.time() for event in self.periodics: self.execute(event, time) for expected_time, events in self.wait_for_calc(time): for event in events: self.execute(event, time) self.selector.remove(event) self.remove_events(expected_time)
class GameBasic(): """ classe qui gère tout le jeu. """ def __init__(self, surfaceDest, gravityDir=DOWN, tutorialScheduler=None): """ constructeur. (thx captain obvious) entrée : surfaceDest : Surface principale de l'écran, sur laquelle s'affiche le jeu. """ self.initCommonStuff(surfaceDest, gravityDir, tutorialScheduler) self.arena = ArenaBasic(surfaceDest, self.posPixelArena, ARENA_SIZE, 2) self.selectorPlayerOne = Selector(self.arena, 0) self.populateArena() self.arena.draw() pygame.display.flip() def populateArena(self): """ à overrider. On initialise l'arena avec les chips que l'on veut, si on veut. """ pass def execStimTutoNext(self): securedPrint(u"next tutorialization") # TRODO : un tutorial qui ne fait rien ? Ce qui permettrait d'éviter # ces tests de is None à chaque fois ? if self.tutorialScheduler is None: return if self.tutorialScheduler.takeStimTutoNext(): self.showCurrentTutoStep() if self.tutorialScheduler.getCurrentTellObjective(): zapValidatorDescrip = self.zapValidatorBase.getListStrDescription() param = (zapValidatorDescrip, COLOR_ZAP_OBJECTIVE) self.console.addListTextAndDisplay(*param) else: # re-blink, si le tuto n'avance pas, et que y'a des trucs à blinker. # comme ça le joueur revoit les blinks si il a pas eu le temps de les voir. # ATTENTION : code ajouté à l'arrache suite à reprise du projet à l'arrache. listPosBlink = self.tutorialScheduler.getCurrentBlink() if len(listPosBlink) and self.blinker is not None: self.blinker.startBlink(listPosBlink) def initCommonStuff(self, surfaceDest, gravityDir, tutorialScheduler=None): """ zob TRODO : c'est un peu le bordel d'avoir foutu ça là. Du coup, quand on regarde dans l'init, on se rend pas compte que y'a toutes ces variables membres. donc, c'est mal de faire ça. """ self.surfaceDest = surfaceDest self.blinker = None self.tutorialScheduler = tutorialScheduler self.console = Console(self.surfaceDest, pyRect(400, 10, 235, 460), nbCharMax=25) self.console.addText(language.TEXT_HELLO[language.languageCurrent]) self.console.refresh() self.console.display() self.manual = ManualInGame( self.surfaceDest, pyRect(10, 340, 400, 130), self.tutorialScheduler) self.manual.refresh() self.manual.display() self.posPixelArena = pyRect(10, 10) param = (self.posPixelArena, ARENA_SIZE, TILE_PIXEL_SIZE) self.stimuliStocker = StimuliStockerForGame(*param) #Ca c'est le putain d'objet qui permet de maîtriser le temps !!! #Talaaaa, je suis le maître du temps. et des frames par secondes aussi. self.clock = pygame.time.Clock() if gravityDir is None: self.crawlerGrav = None self.gravityMovements = None self.crawlerRegen = None else: (gravPrimDir, gravSecDir, primCoordIsX, gravIncsCoord, regenPrimDir, regenSecDir) = DICT_GRAVITY_CONFIG[gravityDir] self.crawlerGrav = ArenaCrawler(ARENA_SIZE) self.crawlerGrav.config(gravPrimDir, gravSecDir) param = (gravityDir, primCoordIsX, gravIncsCoord) self.gravityMovements = GravityMovements(*param) self.crawlerRegen = ArenaCrawler(ARENA_SIZE) self.crawlerRegen.config(regenPrimDir, regenSecDir) #print "self.crawlerRegen.secMove :", self.crawlerRegen.secMove def respawnZapValidator(self): """ redéfinit self.zapValidatorBase (qui n'est pas bien nommé, au passage) """ param = (self.arena, random.randrange(7, 23), random.randrange(3)) self.zapValidatorBase = ZapValidatorBase(*param) def tryToZap(self): """ zob """ selPath = self.selectorPlayerOne.selPath selSuppl = self.selectorPlayerOne.selSuppl if self.zapValidatorBase.validateZap(selPath, selSuppl, []): # gestion du tutorial, si y'en a un. if self.tutorialScheduler is not None: param = (selPath, selSuppl) if self.tutorialScheduler.takeStimTileSelected(*param): self.showCurrentTutoStep() if self.tutorialScheduler.totallyFailed: listTextFail = self.tutorialScheduler.getFailText() self.console.addListTextAndDisplay(listTextFail) self.zapWin() self.respawnZapValidator() self.arena.zapSelection(selPath, selSuppl) self.selectorPlayerOne.cancelAllSelection() if self.needStabilization(): self.gravityCounter = DELAY_GRAVITY self.selectorPlayerOne.setStimuliLock(True) if ((self.tutorialScheduler is None) or (self.tutorialScheduler.getCurrentTellObjective())): zapValidatorDescrip = self.zapValidatorBase.getListStrDescription() self.console.addListTextAndDisplay(zapValidatorDescrip, COLOR_ZAP_OBJECTIVE) else: lastTryDescrip = self.zapValidatorBase.getListStrLastTry() textFail = language.TEXT_FAIL[language.languageCurrent] self.console.addListTextAndDisplay(lastTryDescrip + (textFail, )) def zapWin(self): """ à overrider """ textYeah = language.TEXT_YEAH[language.languageCurrent] self.console.addListTextAndDisplay((textYeah, )) def periodicAction(self): """ à overrider """ pass def applyGravity(self): """ zonc """ param = (self.crawlerGrav, self.gravityMovements, self.crawlerRegen) self.arena.applyGravity(*param) self.arena.regenerateAllChipsAfterOneGravity(self.crawlerRegen) def needStabilization(self): """ zob """ param = (self.crawlerGrav, self.gravityMovements) self.gravityMovements = self.arena.determineGravity(*param) if (self.gravityMovements is not None and len(self.gravityMovements.dicMovement) > 0 ): return True if self.arena.hasChipToRegenerate(self.crawlerRegen): return True return False def handleGravity(self): self.applyGravity() if self.needStabilization(): self.gravityCounter = DELAY_GRAVITY else: #arrache un peu no ? Réponse : oui. double-arrache. if (self.tutorialScheduler is None or not self.tutorialScheduler.mustLockGameStimuli() ): self.selectorPlayerOne.setStimuliLock(False) def gameStimuliInteractiveTouch(self): """ à overrider """ pass # debug à l'arrache if False: if hasattr(self.arena, "listBigObj"): for bigObject in self.arena.listBigObj: securedPrint(u"bigobj : %s" % unicode(bigObject.posTopLeft)) securedPrint(u" listPosArena : %s" % bigObject.listPosArena) for line in self.arena.matrixTile: for tile in line: if tile.chip.getBrouzouf() == 10: print "10 ", elif tile.chip.getBrouzouf() > 0: print " " + str(tile.chip.getBrouzouf()) + " ", elif tile.chip.getSugar() > 0: print " S ", elif tile.chip.getChipType() == 4: print " B ", elif tile.chip.getChipType() == 1: print " 0 ", else: print "?" + str(tile.chip.getChipType()) + " ", print "" def showCurrentTutoStep(self): """ """ if self.tutorialScheduler is None: return listTextDescrip = self.tutorialScheduler.getCurrentText() if len(listTextDescrip): securedPrint(unicode(listTextDescrip)) param = (listTextDescrip, COLOR_TUTORIAL) self.console.addListTextAndDisplay(*param) # sound soundTuto = self.tutorialScheduler.getCurrentSound() if soundTuto is not None: pygame.mixer.stop() soundTuto.play() #blink listPosBlink = self.tutorialScheduler.getCurrentBlink() if len(listPosBlink) and self.blinker is not None: self.blinker.startBlink(listPosBlink) #lock if self.tutorialScheduler.mustLockGameStimuli(): securedPrint("locked !!!") self.selectorPlayerOne.setStimuliLock(True) else: # Euh... Faut délocker ou rien faire ? Bonne question. self.selectorPlayerOne.setStimuliLock(False) def playOneGame(self): """ zob """ # TRODO : pourquoi y'a du code d'init ici ? self.gravityCounter = 0 self.respawnZapValidator() self.showCurrentTutoStep() if ((self.tutorialScheduler is None) or (self.tutorialScheduler.getCurrentTellObjective())): zapValidatorDescrip = self.zapValidatorBase.getListStrDescription() self.console.addListTextAndDisplay(zapValidatorDescrip, COLOR_ZAP_OBJECTIVE) while True: #ça, c'est la classe, déjà pour commencer. #Le jeu va s'auto-ralentir pour atteindre le nombre de FPS spécifié self.clock.tick(FRAME_PER_SECOND) self.stimuliStocker.resetStimuli() self.stimuliStocker.takeEventsFromMouseAndKeyboard() #TRODO : une sorte de mapping ? if self.stimuliStocker.stimuliQuitGame: return if self.stimuliStocker.mustStandBy: self.selectorPlayerOne.takeStimuliStandBy() for posSelected in self.stimuliStocker.listPosArenaToActivate: securedPrint(unicode(posSelected)) self.selectorPlayerOne.takeStimuliActivateTile(posSelected) if self.stimuliStocker.stimuliTryZap: # TRODO condition foutue à l'arrache. # Faut rendre le stimuliStocker configurable. On y locke/délocke des trucs if (self.tutorialScheduler is None or not self.tutorialScheduler.mustLockGameStimuli()): self.tryToZap() if self.stimuliStocker.stimuliEmptySelection: self.selectorPlayerOne.cancelAllSelection() if self.stimuliStocker.stimuliChangeZapConstraint: self.respawnZapValidator() zapValidatorDescrip = self.zapValidatorBase.getListStrDescription() self.console.addListTextAndDisplay(zapValidatorDescrip, COLOR_ZAP_OBJECTIVE) if self.stimuliStocker.stimuliConsoleScrollUp: self.console.moveCursorText(-1) self.console.refresh() self.console.display() if self.stimuliStocker.stimuliConsoleScrollDown: self.console.moveCursorText(+1) self.console.refresh() self.console.display() if self.stimuliStocker.stimTutoNext: self.execStimTutoNext() if self.stimuliStocker.stimReblink: # TODO : il aurait vraiment fallu un tutorialScheduler par # défaut, bidon, qui ne fait rien. Là on s'en sort pas à le # tester à chaque fois si il existe. if self.tutorialScheduler is not None: listPosBlink = self.tutorialScheduler.getCurrentBlink() else: listPosBlink = [] if len(listPosBlink) and self.blinker is not None: self.blinker.startBlink(listPosBlink) # Je ne sais plus pourquoi je raconte ça ici, ni ce que ça veut dire. # #si stand by : stand by #si activate. on chope la coord. # si coord none. : stan by. Et previous = None # sinon : # si previous = None. On active et c'est tout. # sinon : on active tout le chemin entre previous et actuel # previous = actuel posInteract = self.stimuliStocker.posArenaToInteractTouch if posInteract is not None: # ça faut le foutre dans la fonction qu'on override. # C'est peut être mieux non ? if self.arena.stimuliInteractiveTouch(posInteract): self.selectorPlayerOne.cancelAllSelection() if self.needStabilization(): self.selectorPlayerOne.setStimuliLock(True) self.gravityCounter = DELAY_GRAVITY if (self.tutorialScheduler is not None and self.tutorialScheduler.takeStimInteractiveTouch()): self.showCurrentTutoStep() # c'est de cette fonction là que je parle. self.gameStimuliInteractiveTouch() #TRODO : faudra une 'tite classe pour les compteurs. if self.gravityCounter: self.gravityCounter -= 1 if not self.gravityCounter: self.handleGravity() self.periodicAction() if self.blinker is not None: self.blinker.advanceTimerAndHandle() #TRODO : optimiser ça. Pas de refresh géant à chaque frame. self.arena.draw() pygame.display.flip()
def main(): app = Selector(wrap=Yaro) app.add('401', GET=get_401) app.add('', GET=get_index) app.add('/', GET=get_index) app.add('/items.json', GET=get_items_json) app.add('/items', GET=get_item) app.add('/item/{id}', GET=get_item) app.add('/dropbox', POST=post_to_dropbox,GET=get_dropbox) app.add('/notes', POST=post_to_notes,GET=get_notes) app.add('/note/{id}', DELETE=delete_note) app.add('/dropbox/{id}', GET=get_dropbox_item) app.add('/thumbnail/{blob_key}', GET=get_thumbnail) app.add('/serve/{blob_key}', GET=serve_blob) app.add('/attributes', GET=get_attributes,POST=post_to_attributes) app.add('/attribute/{ascii_id}', GET=get_attribute,DELETE=delete_attribute) app.add('/upload/{user_id}', POST=process_upload) app.add('/formupload/{user_id}', POST=process_formupload) app.add('/upload_url', GET=get_upload_url) run_wsgi_app(app)
class GameTouillette(GameBasic): """ classe qui gère tout le jeu. """ def __init__(self, surfaceDest, gravityDir=DOWN, tutorialScheduler=None, xyFirstTouillette=(2, 5)): """ constructeur. (thx captain obvious) entrée : surfaceDest : Surface principale de l'écran, sur laquelle s'affiche le jeu. """ self.initCommonStuff(surfaceDest, gravityDir, tutorialScheduler) self.nbTouilletteToRemove = 2 self.mustDisplayRemoving = False self.arena = ArenaTouillette(surfaceDest, self.posPixelArena, ARENA_SIZE, 2, LIST_CHIP_GENERATION) self.selectorPlayerOne = Selector(self.arena, 0) self.populateArena() self.arena.addBigObject(Touillette, pyRectTuple(xyFirstTouillette)) self.arena.draw() pygame.display.flip() def periodicAction(self): """ à overrider """ # À priori, ce genre de truc n'a rien à foutre dans une "periodicAction". # On n'a besoin de le tester uniquement quand une touillette # est arrivée en bas de l'écran. if self.mustDisplayRemoving: securedPrint(u"blorp") nbTouRemoved = self.arena.nbTouilletteRemoved nbTouToRem = self.nbTouilletteToRemove self.mustDisplayRemoving = False if nbTouRemoved == nbTouToRem: listTextWin = language.LIST_TEXTS_WIN[language.languageCurrent] self.console.addListTextAndDisplay(listTextWin, COLOR_WIN) else: strBla = u"%d/%d" % (nbTouRemoved, nbTouToRem) textTouy = language.TEXT_TOUY[language.languageCurrent] self.console.addListTextAndDisplay((textTouy, strBla)) def handleGravity(self): securedPrint(u"handleGravity") if self.arena.removeBottomTouillette(): touilletteRemoved = True self.mustDisplayRemoving = True else: touilletteRemoved = False self.applyGravity() if self.needStabilization() or touilletteRemoved or self.arena.hasTouilletteInBottom(): securedPrint(u"there is still gravity.") self.gravityCounter = DELAY_GRAVITY else: securedPrint(u"lock set to false.") self.selectorPlayerOne.setStimuliLock(False)
import barrel.cooper import static import json from selector import Selector from unipath import FSPath as Path app = Selector() base = Path(__file__).parent for course in base.listdir(filter=Path.isdir): subapp = static.Cling(course.child('html')) if course.child('auth.json').exists(): users = json.load(open(course.child('auth.json'))) auth = barrel.cooper.basicauth(users=users, realm="Course Material") # FIXME: worth allowing customization here? subapp = auth(subapp) app.add("/%s|" % course.name, GET=subapp)
# guess what - don't change this unless you're running this out of # something less like gunicorn/etc. Oh... You're welcome. __all__ = ['application'] def say_hello(environ, start_response): """ Test app... """ args, kwargs = environ['wsgiorg.routing_args'] print args start_response("200 OK", [('Content-type', 'text/plain')]) return ["Hello, %s!" % kwargs['name']] # I know - a long variable name, but don't change it - see the above # message above ``__all__`` for more context... application = Selector() # include for smoke testing application.add('/hello/{name}', GET=say_hello) application.add(ENDPT_PREFIX + '/hello/{name}', GET=say_hello) # Change to include a version number as a prefix application.add(ENDPT_PREFIX + '/lookup[/]', GET=lookup) application.add(ENDPT_PREFIX + '/register/{object_id:word}/{object_name:segment}/' + '{object_desc:segment[/{parent_uuid:word}][/]', POST=register) application.add(ENDPT_PREFIX + '/provenance/{uuid:word}/{username}/{service_name}/' + '{event_name}/{category_name}[/]', POST=provenance) application.add(ENDPT_PREFIX + '/provenance/{service_name}/{event_name}/{category_name}[/]',