def handle_route(route, station2, wayList, step, way): # todo 方向 if route.prevStation is not None: step += 1 stepO = Step(route.prevStation, route.line) if route.prevStation == station2: way.appendStep(stepO) Manager.minStep = min(step, Manager.minStep) wayList.append(way) return if step >= Manager.minStep: return newWay = copy.copy(way) newWay.appendStep(stepO) find else : if route.nextStation == station2: step = Step(route.nextStation, route.line) way.appendStep(step) return if route.prevStation
def step_of_current(self, passedTime=None, holdingTime=0.0): return Step( self.curState.stateId, copy.copy(self.curState.apSet), passedTime=passedTime, holdingTime=holdingTime )
def _next_step(self, passedtime, duration): key = tuple([v.get_value() for v in self._vars.values()]) enabled_cmds = self._state_cmd_map[key] next_move = self._next_move(passedtime, enabled_cmds) if passedtime + next_move.holding_time > duration: next_move = NextMove(passedtime) apset = self._state_ap_map[key] return Step(apset, next_move)
def assign_steps(routes): for route in routes['routes']: for leg in route['legs']: for step in leg['steps']: distance = step['distance']['value'] duration = step['duration']['value'] latitude = step['end_location']['lat'] longitude = step['end_location']['lng'] s = Step(distance, duration, latitude, longitude) steps.append(s)
def __init__(self, size): self.size = size self.steps = [] # set first step IC to all zeros cols = [] for i in range(size): cols.append([]) for j in range(size): cols[i].append(0) init_step = Step(self.size) init_step.set_init_cond(cols) self.steps.append(init_step)
def InsertRows(self, pos, numRows=1): if (pos == -1): pos = 0 newPos = pos + 1 if (self.steps.size() == 0): lastLabel = 0 else: lastLabel = pos newLabel = lastLabel + 1 try: self.steps.append(Step()) except ARM.ARMException, errorText: dlg = wx.MessageDialog(self.GetView(), str(errorText), 'Add Step', wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return
def __update_raw_tests(self): self.raw_test.scenarios.append( Scenario(url=self.url, feature_name=self.feature_name, text="Example test scenario")) for choice in self.cases[0].selected_expands: self.raw_test.scenarios[0].steps.append( Step(step_type=choice.parent.step_type, feature_name=self.feature_name, x_path=choice.parent.xpath, input_type=choice.parent.input_type, cases=[], label="Element " + choice.parent.name + " has value <choice{}>".format(choice.parent.id))) for case in self.cases: for i, choice in enumerate(case.selected_expands): self.raw_test.scenarios[0].steps[i].cases.append(choice.choice)
def scrape_page(page_link): page_reponse = requests.get(page_link) page_soup = BeautifulSoup(page_reponse.text, "html.parser") try: image_url = page_soup.select_one( ".recipeGallerySegment .bigImg img")['src'] if "without-watermark" not in image_url: global recipes_with_watermarks recipes_with_watermarks += 1 return recipe_title = page_soup.select_one( ".recipeTitleSegment h1").text.strip() before_split = page_soup.select_one(".method .info .info").text.strip() recipe_preparation_time = int(re.findall("\d+", before_split)[0]) if "min" in before_split: recipe_preparation_time = int(60 * recipe_preparation_time) elif "val" in before_split: recipe_preparation_time = int(60 * 60 * recipe_preparation_time) recipe_portion_amount = page_soup.select_one(".info").text.strip() if len(recipe_portion_amount) is 0: recipe_portion_amount = int(4) else: recipe_portion_amount = int( re.findall("\d+", recipe_portion_amount)[0]) recipe_description = '' try: recipe_description = page_soup.select_one( ".authorsDescription").text.strip() except AttributeError: recipe_description = '' print('No description') amounts = page_soup.select(".ingredients .infoA table tr") recipe_products = [] for amount in amounts: cells = amount.select("td") if len(cells) is 1: continue quantity = cells[0].text.strip() product_name = cells[1].text.strip()[0:30].strip() new_product = Product(product_name, quantity) recipe_products.append(new_product.__dict__) steps = page_soup.select(".infoA .description") recipe_steps = [] for step in steps: step_text = step.select_one(".text") # print(step_text.text) new_step = Step(step_text.text) recipe_steps.append(new_step.__dict__) recipe_view_count = int(0) recipe_rating = int(0) recipe_votes_count = int(0) image_extension = image_url.split('.')[-1] image_fileName = '' image_name = '' while True: image_name = uuid.uuid4().hex image_fileName = image_name + "." + image_extension if not os.path.isfile("Photos/" + image_fileName): break opener = urllib.request.URLopener() opener.addheader( 'User-Agent', 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405' ) opener.retrieve(image_url, "Photos/" + image_fileName) # urllib.request.urlretrieve(image_url, "Photos/" + image_fileName) recipe_image = Photo(image_fileName) recipe_images = [] recipe_images.append(recipe_image.__dict__) # Tags recipe_tags = [] temp = Tag("grilio patiekalai") recipe_tags.append(temp.__dict__) tags = page_soup.select(".guidelinesSegment a") for tag in tags: if not "lamaistas" in tag.text: new_tag = Tag(tag.text) recipe_tags.append(new_tag.__dict__) new_recipe = Recipe(recipe_title, recipe_products, recipe_steps, recipe_portion_amount, recipe_preparation_time, recipe_description, recipe_view_count, recipe_rating, recipe_votes_count, recipe_images, recipe_tags) new_recipes.append(new_recipe.__dict__) print("Saved " + page_link + " " + str(len(new_recipes))) except Exception as e: print("Error " + str(e) + " || " + page_link)
def plan_journey(self, from_location, to_station, time, departure): base_url = "journeys?lang=nl-NL&" time = "dateTime=" + time from_station = "&from=" + from_location to_station = "&to=" + to_station before = "&before=1" after = "&after=5" sequence = "&sequence=1" options = "&byFerry=true&bySubway=true&byBus=true&byTram=true&byTrain=true" search_type = "&searchType=" + departure url = self.url + base_url + time + from_station + to_station + before + after + sequence + options + search_type journeys = requests.get(url).json() print(url) steps = [] first = True counter = 1 destination_temp = "" end_time_temp = "" for part in journeys['journeys'][1]['legs']: last_stop = part['stops'][-1]['location'] first_stop = part['stops'][0]['location'] step = Step() if part['type'] == "continuous": if first: step.kind = part['mode']['name'][0:5] step.departure_location = first_stop['name'] if 'stopType' in last_stop: step.arrival_location = last_stop[ 'stopType'] + " " + last_stop['place'][ 'name'] + last_stop['name'] else: step.arrival_location = last_stop['place'][ 'name'] + " " + last_stop['stationType'] step.departure_time = journeys['journeys'][1]['departure'] step.arrival_time = self.calculate_end_time( journeys['journeys'][1]['departure'], part['duration']) step.duration = part['duration'] elif counter == len(journeys['journeys'][1]['legs']): step.kind = part['mode']['name'][0:5] step.departure_location = destination_temp step.arrival_location = last_stop['place'][ 'name'] + " " + last_stop['name'] step.departure_time = end_time_temp step.arrival_time = journeys['journeys'][1]['arrival'] step.duration = part['duration'] else: step.kind = part['mode']['name'][0:5] step.departure_location = destination_temp if 'stopType' in last_stop: step.arrival_location = last_stop['place'][ 'name'] + " " + last_stop['stopType'] else: step.arrival_location = last_stop['place'][ 'name'] + " " + last_stop['stationType'] step.departure_time = end_time_temp step.arrival_time = self.calculate_end_time( end_time_temp, part['duration']) step.duration = part['duration'] else: end_time_temp = part['stops'][-1]['arrival'] if part['mode']['type'] == 'train': destination_temp = last_stop[ 'stationType'] + " " + last_stop['name'] step.kind = part['mode']['name'] + " richting " + part[ 'destination'] step.departure_location = first_stop[ 'stationType'] + " " + first_stop['name'] step.arrival_location = last_stop[ 'stationType'] + " " + last_stop['name'] step.departure_time = part['stops'][0]['departure'] step.arrival_time = part['stops'][-1]['arrival'] step.duration = self.calculate_duration( part['stops'][-1]['arrival'], part['stops'][0]['departure']) else: destination_temp = last_stop['stopType'] + " " + last_stop[ 'place']['name'] + " " + last_stop['name'] step.kind = part['mode']['name'] + " richting " + part[ 'destination'] step.departure_location = first_stop[ 'stopType'] + " " + first_stop['place'][ 'name'] + " " + first_stop['name'] step.arrival_location = last_stop[ 'stopType'] + " " + last_stop['place'][ 'name'] + " " + last_stop['name'] step.departure_time = part['stops'][0]['departure'] step.arrival_time = part['stops'][-1]['arrival'] step.duration = self.calculate_duration( part['stops'][-1]['arrival'], part['stops'][0]['departure']) steps.append(step) counter += 1 first = False return steps
def gen_random_path(self, duration, cachedPrefixes=None): # Since when initilize a module, all its local variables # have been initilized if not self.commPrepared: self.prepareCommands() self.commPrepared = True path = list() timeSum = 0.0 passedTime = 0.0 while timeSum < duration: # get enabled commands list variables = [var.getValue() for _, var in self.localVars.items()] varsStr = ''.join([str(v) for v in variables]) if len(self.scDict) == 0: # 由于存在unbounded变量,无法提前判断所有的变量组合的enabled commands # 因此需要手工判断 cmd_probs = [] for _,module in self.modules.items(): for _,comm in module.allCommands().items(): if comm.guard(self.localVars, self.constants): cmd_probs.append((comm, comm.prob())) else: cmd_probs = self.scDict[varsStr] if len(cmd_probs) == 0: path.append(self.step_of_current(passedTime=passedTime)) self.restoreSystem() return None, path transition, holdingTime, rate, biasingRate, exitRate, biasingExitRate = self.nextState( cmd_probs, duration=duration - timeSum) timeSum += holdingTime if len(path) == 0 and holdingTime > duration: # The first transition is not possible to happen within the given duration # In this situation, we think that the transition not made. # return the path: [Step(initState, emptyTransition)] # self._updateCurAndPrevState() step = self.step_of_current() path.append(step) self.restoreSystem() return (None, path) if timeSum > duration: holdingTime -= (timeSum - duration) step = Step( self.prevState.stateId, self.prevState.apSet.copy(), holdingTime, passedTime, transition, rate, biasingRate, exitRate, biasingExitRate) path.append(step) passedTime += holdingTime if len(path) >= 1 and self.stopCondition and self.stopCondition( self.localVars, self.constants): # add this empty step (with no transition made) # to represent the state the system currently is in. path.append(self.step_of_current(passedTime=passedTime)) self.restoreSystem() return (None, path) # MUST be executed before the function returns # to prepare generating next random path. self.restoreSystem() return None, path
def __init__(self, initial_state: State): self.steps = [Step(None, None, initial_state)]
def add_step(self, action: int, reward: float, new_state: State): self.steps.append(Step(action, reward, new_state))
import Processor from Step import Step with open('input.txt') as f: common_code = f.readline().strip().split(',') computer = Processor.Processor(common_code, 0) computer.reset() step_tree = Step(None, (0, 0), 'O') direction_map = [None, 2, 1, 4, 3] oxygen_coords = (None, None) def withdraw(direction): while True: try: computer.run() except Processor.ProcessorInputException: computer.push_input(direction_map[direction]) except Processor.ProcessorOutputException: return def do_step(upstream, direction): global oxygen_coords while True: try: computer.run() except Processor.ProcessorInputException: computer.push_input(direction)
def setUp(self): self.root = Step(None, (0, 0), "O") self.leaf1 = self.root.add_leaf(1, ".") self.leaf11 = self.leaf1.add_leaf(1, ".") self.leaf113 = self.leaf11.add_leaf(3, ".") self.leaf1132 = self.leaf113.add_leaf(2, ".")
def startElement(self, name, attrs): self.currentElementName = name if name == 'persona': self.theName = attrs['name'] self.theType = attrs['type'] self.theImage = attrs['image'] if (attrs['assumption_persona'] == 'TRUE'): self.isAssumptionPersona = True elif name == 'persona_environment': self.theEnvironmentName = attrs['name'] if (attrs['is_direct'] == 'FALSE'): self.isDirect = False elif name == 'persona_role': self.theRoles.append(attrs['name']) elif name == 'external_document': self.theName = attrs['name'] self.theVersion = attrs['version'] self.theDate = attrs['date'] self.theAuthors = attrs['authors'] elif name == 'document_reference': self.theName = attrs['name'] self.theContributor = attrs['contributor'] self.theDocument = attrs['document'] elif name == 'concept_reference': self.theName = attrs['name'] self.theConcept = attrs['concept'] self.theObject = attrs['object'] elif name == 'persona_characteristic': self.thePersona = attrs['persona'] self.theBvName = u2s(attrs['behavioural_variable']) self.theModalQualifier = attrs['modal_qualifier'] elif name == 'task_characteristic': self.theTask = attrs['task'] self.theModalQualifier = attrs['modal_qualifier'] elif name == 'grounds': refName = attrs['reference'] refType = attrs['type'] refArtifact = '' self.theGrounds.append((refName, '', refType)) elif name == 'warrant': refName = attrs['reference'] refType = attrs['type'] refArtifact = '' self.theWarrants.append((refName, '', refType)) elif name == 'rebuttal': refName = attrs['reference'] refType = attrs['type'] refArtifact = '' self.theRebuttals.append((refName, '', refType)) elif name == 'task': self.theName = attrs['name'] try: self.theCode = attrs['code'] except KeyError: self.theCode = '' self.theAuthor = attrs['author'] if (attrs['assumption_task'] == 'TRUE'): self.isAssumptionTask = True elif name == 'task_environment': self.theEnvironmentName = attrs['name'] elif name == 'task_persona': self.theTaskPersonas.append( (attrs['persona'], durationValue(attrs['duration']), frequencyValue(attrs['frequency']), attrs['demands'], attrs['goal_conflict'])) elif name == 'task_concern': self.theConcerns.append(attrs['asset']) elif name == 'task_concern_association': self.theConcernAssociations.append( (attrs['source_name'], a2s(attrs['source_nry']), attrs['link_name'], attrs['target_name'], a2s(attrs['target_nry']))) elif name == 'usecase': self.theName = attrs['name'] self.theAuthor = attrs['author'] self.theCode = attrs['code'] elif name == 'actor': self.theActors.append(attrs['name']) elif name == 'usecase_environment': self.theEnvironmentName = attrs['name'] elif name == 'step': self.theCurrentStepNo = attrs['number'] self.theCurrentStep = Step(attrs['description']) elif name == 'exception': self.theExcName = attrs['name'] self.theExcType = attrs['type'] self.theExcValue = attrs['value'] self.theExcCat = u2s(attrs['category']) elif name == 'activities': self.inActivities = 1 self.theActivities = '' elif name == 'attitudes': self.inAttitudes = 1 self.theAttitudes = '' elif name == 'aptitudes': self.inAptitudes = 1 self.theAptitudes = '' elif name == 'motivations': self.inMotivations = 1 self.theMotivations = '' elif name == 'skills': self.inSkills = 1 self.theSkills = '' elif name == 'intrinsic': self.inIntrinsic = 1 self.theIntrinsic = '' elif name == 'contextual': self.inContextual = 1 self.theContextual = '' elif name == 'narrative': self.inNarrative = 1 self.theNarrative = '' elif name == 'consequences': self.inConsequences = 1 self.theConsequences = '' elif name == 'benefits': self.inBenefits = 1 self.theBenefits = '' elif name == 'excerpt': self.inExcerpt = 1 self.theExcerpt = '' elif name == 'description': self.inDescription = 1 self.theDescription = '' elif name == 'definition': self.inDefinition = 1 self.theDefinition = '' elif name == 'dependencies': self.inDependencies = 1 self.theDependencies = '' elif name == 'objective': self.inObjective = 1 self.theObjective = '' elif name == 'preconditions': self.inPreconditions = 1 self.thePreconditions = '' elif name == 'postconditions': self.inPostconditions = 1 self.thePostconditions = '' elif name == 'tag': self.theTags.append(attrs['name'])
def set_init_cond(self, cols): self.steps.clear() new_step = Step(self.size) new_step.set_init_cond(cols) self.steps.append(new_step) return