def init_values(self): """Initialize statuses of whether or not files have been loaded, whether shaft information displays are normalized, and whether or not the plot needs to be refreshed. Also initialize a class holding constants. """ # Holds the states of whether the necessary files have been loaded. # The 4 required files are: # - designs specifications # - material properties # - load factors # - wind history. self.loaded = [False, False, False, False] # This value determines how details of the shaft sections are displayed. # A value of 'True' scales text uniformly; A value of 'False' places # text underneath plotted shaft sections. self.normalized = False # This value determines whether solutions have to be (re)solved. # Prevents recalculating solutions if user only wants to change views. self.reload = True # Initialize constants. self.c = Constants()
def robotInit(self): """Run when the robot turns on.""" field_styles = coloredlogs.DEFAULT_FIELD_STYLES field_styles['filename'] = {'color': 'cyan'} coloredlogs.install( fmt= "%(asctime)s[%(msecs)d] %(filename)s:%(lineno)d %(name)s %(levelname)s %(message)s", datefmt="%m-%d %H:%M:%S", field_styles=field_styles) # install to created handler Command.getRobot = lambda x=0: self # Update constants from json file on robot # if self.isReal(): # Constants.updateConstants() # Update constants for dashboard editing Constants.initSmartDashboard() # Initialize drive objects drive.Drive().init() # The PDP # self.pdp = PDP(7) # Set command group member variables self.autonomous = autogroup.AutonomousCommandGroup() self.disabled = disabledgroup.DisabledCommandGroup() self.disabled.setRunWhenDisabled(True) self.teleop = teleopgroup.TeleopCommandGroup() self.test = testgroup.TestCommandGroup() self.global_ = globalgroup.GlobalCommandGroup() self.global_.setRunWhenDisabled(True) # Start the camera sever CameraServer.launch() self.watchdog = watchdog.Watchdog(0.05, self._watchdogTimeout) self.globalInit()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.img = c.IMG("blackbox.png") self.box = c.SPRITE(self.img, x=370, y=250) self.box.scale = 3 self.center_x = (self.img.width // 2) + self.box.x self.center_y = (self.img.height // 2) + self.box.y self.showing = False self.decided = False self.letters = [] self.letter_scale = 3 self.coords = {} self.question = c.LABEL(font_name=c.FONT, x=self.center_x, y=self.center_y, font_size=24, width=self.box.width, batch=c.PROBLEM_BATCH) self.x_offset = 40 #setup alphabet image indices for letter in enumerate(lowercase): self.coords[letter[1]] = letter[0] * 8 for letter in enumerate(uppercase): self.coords[letter[1]] = letter[0] * 8
def main(): """main block get barcode scanner device connect to sql database start task loop """ cursor, dev = None, None signal.signal(signal.SIGINT, signal_handler) conf_path = os.path.abspath(Constants.config_file()) config = get_config(conf_path, Constants.config_sections()) conn_check(config['host']) devlist = ast.literal_eval(config['devlist']) dev = get_device(devlist) if not dev: logger.error("failed to find {}".format(devlist)) sys.exit(1) dev.grab() conn = db_connect(config['host'], config['user'], config['password'], config['database'], config['query_timeout'], config['login_timeout']) if conn == None: logger.info("failed to connect to db") sys.exit(2) cursor = conn.cursor() logger.info('entering task loop') task_loop(dev, cursor, conn, config)
def __init__(self, logger, force=False): c = Constants() self.files = c.files() self.url = c.url() self.path_root = c.path_root self.force = force self.logger = logger
def check_user_credentials_with_credentials(user_id, token): # Check token status status = TokenSerializer.verify_auth_token(token, user_id) # Is token is expired? if status == SignatureExpired: # Yes: return error status return Constants.error_token_expired() # Is toke not valid? elif status == BadSignature: # Yes: return error status return Constants.error_token_not_valid() # Try to find user with received ID person_model = PersonModel.query.filter_by(person_id=user_id).first() # Have we user with received ID? if person_model is None: # No we haven't: return error status return Constants.error_no_user_id() # Is received token correct? if person_model.token != token: # No: return error status return Constants.error_token_not_valid() # If everything is Ok - return person model return person_model
def f_prime(u_now0, u_now1, u_now2, u_next0, u_next1, u_next2, f_now, f_next): u_tmp = (pow(abs(u_next2), 2) * u_next2) - (pow(abs(u_next0), 2) * u_next0) + (pow(abs(u_now2), 2) * u_now2) - (pow(abs(u_now0), 2) * u_now0) p1 = u_now2 - 2.0 * u_now1 + u_now0 p2 = -0.5 * Constants.beta * Constants.h() * complex(0,1) * u_tmp p3 = -1.0 * complex(0,1) * pow(Constants.h(), 2) * (f_next + f_now) p4 = -2.0 * pow(Constants.h(), 2) * complex(0,1) * u_now1 / Constants.tau return p1 + p2 + p3 + p4
def main(): constants = Constants() GRID_SIZE = constants.getGridSize() collected_data_dates = constants.getNineteenDates() PMstrs = ['PM1', 'PM2.5', 'PM10'] #Example values for performing a grid search over kernel size and learning rate kernel_sizes = [1] learning_rates = [0.001] beta = 1 for kernel_size in kernel_sizes: for learning_rate in learning_rates: PM_index = 1 #Train only on PM2.5 PM_str = PMstrs[PM_index] for i in range(np.shape(collected_data_dates)[0]): valid_date = collected_data_dates[ np.shape(collected_data_dates)[0] - 1] print("iteration i : ", i, "valid_date : ", valid_date) X, Y = load_data(GRID_SIZE, collected_data_dates, PM_index) directory = os.path.dirname( '../results/tune19examples/learning_rate/learning_rate_' + str(learning_rate) + '/kernel_size_' + str(kernel_size) + '/valid_date_' + str(valid_date) + '/') if not os.path.exists(directory): os.makedirs(directory) train(X, Y, 0.95, kernel_size, GRID_SIZE, valid_date, PM_index, learning_rate, beta) collected_data_dates = np.roll(collected_data_dates, 1) valid_date = collected_data_dates[ np.shape(collected_data_dates)[0] - 1]
def run_basis(FSS): """ Runs crosscorrlation vs wave plartes experiment. """ print 'Running diag basis with FSS', FSS.astype('|S4').tostring() constants = Constants() constants.FSS = FSS experiment = Experiment(constants) experiment.bench.setHWP(np.pi/8, np.pi/8) experiment.bench.setLabMatrix('NBSNBS HWPHWP SS PBSPBS') experiment.run('basis') experiment.pcm.channel('D1D3').normalize(experiment.laser.pulse_width) experiment.pcm.channel('D1D4').normalize(experiment.laser.pulse_width) experiment.pcm.channel('D2D3').normalize(experiment.laser.pulse_width) experiment.pcm.channel('D2D4').normalize(experiment.laser.pulse_width) for key in experiment.pcm._channels: x = experiment.pcm._channels[key].bin_edges y = experiment.pcm._channels[key].counts save.savedata(x, y, name = 'diag' + '_' + key + '_' + FSS.astype('|S4').tostring(), dir = 'auto_g2_v_fss_dephase2.5e10secondaty0.18') g2 = experiment.pcm.channel('D1D3').g2 g2_cross = experiment.pcm.channel('D1D4').g2 return g2_cross
class FormField(object): Tag = Constants("INPUT", "BUTTON", "TEXTAREA") Type = Constants("CHECKBOX", "TEXT", "PASSWORD", "HIDDEN", "SUBMIT", "IMAGE", "FILE", "BUTTON", "OTHER") def __init__(self, tag, type, name, value=None): self.tag = tag self.type = type self.name = name self.value = value def __str__(self): return self._str def __repr__(self): return self._str @lazyproperty def _str(self): return "FormField(%s %s %s=%s)" % (self.tag, self.type, self.name, self.value) def __hash__(self): return self.hash @lazyproperty def hash(self): return hash(self._str) def __cmp__(self, o): return cmp(self.hash, o.hash)
def start_mission(self): """ Manages the agent's action loop and the environment's record-keeping mechanics """ score = 0 while (score > Constants.get_min_score()): time.sleep(self._tick_length) # Get player's next move in their plan, then execute next_act = self._agent.get_next_move() self._move_request(next_act) # Return a perception for the agent to think about and plan next perception = {"loc": self._player_loc, "tile": self._ag_tile} self._agent.think(perception) # Assess the post-move penalty and whether or not the game is complete penalty = Constants.get_pit_penalty() if self._pit_test( self._player_loc) else Constants.get_mov_penalty() score = score - penalty if self._verbose: print("\nCurrent Loc: " + str(self._player_loc) + " [" + self._ag_tile + "]\nLast Move: " + str(next_act) + "\nScore: " + str(score) + "\n") if self._goal_test(self._player_loc): break if self._verbose: print("[!] Game Complete! Final Score: " + str(score)) return score
def __init__(self, *args, **kwargs): self.right = c.IMG("powbutton.png") self.right_seq = c.GRID(self.right, 1, 1) self.right_anim = c.ANIM(self.right_seq, 1, False) self.left_anim = self.right_anim self.left = self.right super().__init__(self.right_anim, *args, **kwargs)
def embed(self): embed = discord.Embed( title="BJay Signup Bot", description=f"Event {self.name}", color=0xebc20a ) embed.set_author( name="Get Off My Base Peasants", url=Constants.outfit_url(), icon_url=Constants.outfit_icon() ) if self.squad_lead: embed.add_field(name="Squad Leader", value=self.squad_lead.embed_string__) if self.fireteam_lead: embed.add_field(name="Fireteam Leader", value=self.fireteam_lead.embed_string__) for role in self.composition: member_list = str() for member in self.composition[role]: member_list += f"{member.embed_string__}\n" role_string = f"{role.capitalize()}: {len(self.composition[role])}/{self.max_composition.get(role, '-')}" embed.add_field(name=role_string, value=member_list, inline=False) return embed
def readConfig(): with io.open('config', 'r') as reader: lines = [x[:-1] if x[-1] == '\n' else x for x in reader.readlines()] lines.remove('') #remove empty lines win_size = vec2(-1, -1) for line in lines: m = re.match('^(.*): (.*)$', line) if m: gr = m.groups() first = gr[0].lower() if len(gr) != 2: raise NoidError('Invalid config record.') if first == 'width': win_size.x = int(gr[1]) elif first == 'height': win_size.y = int(gr[1]) elif first == 'fullscreen': Constants.IS_FULLSCREEN = (gr[1] in ['True', 'true', '1']) elif first == 'levels': Constants.LEVELS = gr[1].split() Constants.init(win_size)
def __init__(self, x=0, y=0, *args, **kwargs): self.poof = c.IMG("poof.png") self.poof_seq = c.GRID(self.poof, 1, 4) self.poof_anim = c.ANIM(self.poof_seq, 0.1, False) super().__init__(self.poof_anim, *args, **kwargs) self.x = x self.y = y self.batch=c.ANIMATION_BATCH
def insert_values(self: object, query: str) -> None: """ Inserts Value to the table. """ try: self.cursor.execute(query) return Constants().VOTE_COMMIT except mysql.connector.Error as err: print(err.msg) return Constants().VOTE_ABORT
def robotInit(self): """Run when the robot turns on""" # Update constants from json file on robot Constants.updateConstants() # Robot odemetry command self.updateodemetry = updateodemetry.UpdateOdemetry() # Set command group member variables self.autonomous = autogroup.AutonomousCommandGroup()
def init(self): constants = Constants() self.gridResolution = constants.getGridSize() self.topLat = constants.corners[0][0] self.bottomLat = constants.corners[2][0] self.leftLon = constants.corners[0][1] self.rightLon = constants.corners[1][1]
def __init__(self): self.constants = Constants() self._querystartlink = None self._queryendlink = None self._imagestartlink = None self._summarystartlink = None
class MazeProblem: ################################################################## # Class Constants ################################################################## # Static COST_MAP for maze components and the cost to move onto them # Any maze block not listed here is assumed to have a cost of 1 # HINT: You can add block types to this! COST_MAP = { Constants.PIT_BLOCK: Constants.get_pit_penalty(), NewConstants.MAYBE_PIT_BLOCK: NewConstants.get_potential_pit_penalty(), NewConstants.CURIOUS_BLOCK: NewConstants.get_curious_penalty(), Constants.GOAL_BLOCK: NewConstants.get_goal_penalty(), Constants.SAFE_BLOCK: Constants.get_mov_penalty(), } ################################################################## # Constructor ################################################################## def __init__(self, maze): """ Constructs a new pathfinding problem from a maze :maze: a list of list of strings containing maze elements """ self.maze = maze ################################################################## # Methods ################################################################## def transitions(self, state): """ Given some state s, the transitions will be represented as a list of tuples of the format: [(action1, cost_of_action1, result(action1, s)), ...] For example, if an agent is at state (1, 1), and can only move right and down into clear tiles (.), then the transitions for that s = (1, 1) would be: [("R", 1, (2, 1)), ("D", 1, (1, 2))] :state: A maze location tuple """ s = state possible = [("U", (s[0], s[1]-1)), ("D", (s[0], s[1]+1)), ("L", (s[0]-1, s[1])), ("R", (s[0]+1, s[1]))] return [(s[0], self.cost(s[1]), s[1]) for s in possible if self.maze[s[1][1]][s[1][0]] != Constants.WALL_BLOCK] def cost(self, state): """ Returns the cost of moving onto the given state, and employs the MazeProblem's COST_MAP :state: A maze location tuple """ cm = MazeProblem.COST_MAP cell = self.maze[state[1]][state[0]] return cm[cell] if cell in cm else Constants.get_mov_penalty()
def upload_file(current_user,curent_preference,filename,db): if File.query.filter_by(file_name=str( Constants.cloud_script_folder_path(current_user, curent_preference) + filename)).first() is None: file = File( file_name=str(Constants.cloud_script_folder_path(current_user, curent_preference) + filename)) db.session.add(file) db.session.commit() preference_file = Preference_file(file_id=file.id, preference_id=curent_preference.preference_id) db.session.add(preference_file) db.session.commit()
def to_xml(self, xml_name): print "generating plan to %s" % xml_name root = ElementTree.Element('testplan') for suite_name in self.suites: suite = self.suites[suite_name] root.append(suite.to_xml()) Constants.indent(root) tree = ElementTree.ElementTree() tree._setroot(root) tree.write(xml_name, encoding="utf-8")
def generate_rerun_params(self): f = "-f \"" param = Constants.EXECUTE_PREFF + "\"" + Constants.WRT_LAUNCHR_CMD for suite in self.suites.keys(): suite_obj = self.suites[suite] f += "%s " % suite_obj.get_rerunxml_name() param += " %s" % suite f = Constants.add_right_enbrace(f) param = Constants.add_right_enbrace(param) return f + param + Constants.RERUN_OUTPUT
def __init__(self, *args, **kwargs): self.left = c.IMG("bigboostandleft.png") #TODO, realign boo, too far right # self.center_floating_player(self.left) self.left_seq = c.GRID(self.left, 1, 1) self.left_anim = c.ANIM(self.left_seq, 1, False) self.walk_right = c.IMG("bigboowalkright.png") self.walk_right_seq = c.GRID(self.walk_right, 1, 1) self.walk_right_anim = c.ANIM(self.walk_right_seq, 0.1, True) self.walk_left = c.IMG("bigboowalkleft.png") self.walk_left_seq = c.GRID(self.walk_left, 1, 1) self.walk_left_anim = c.ANIM(self.walk_left_seq, 0.1, True) super().__init__(self.left, *args, **kwargs) self.x = c.OFF_SCREEN_R self.y = c.FLOAT_H self.batch = c.PLAYER_BATCH self.scale = 1.5 #TODO, figure out why this method only works if within the __init__ block def mini_sprite(self) -> Any: """Makes mini-sprite version of self. Overrides base class method.""" mini = Score(self) mini.image = self.walk_left_anim return mini
def init(self): constants = Constants() self.gridResolution = constants.getGridSize() self.topLat = constants.corners[0][0] self.bottomLat = constants.corners[2][0] self.centerLat = self.bottomLat + (self.topLat - self.bottomLat) / 2 self.leftLon = constants.corners[0][1] self.rightLon = constants.corners[1][1] self.centerLon = self.leftLon + (self.rightLon - self.leftLon) / 2
def __init__(self, game, x, y): self.game = game self.position = Vector(x, y) # Static images needed self.static_images = [os.path.join('..', 'assets', 'char.png')] self.static_images_loaded = Constants.makeImage(self.static_images) # Walk cycle needed self.walk_images = [os.path.join('..', 'assets', 'char.png')] self.walk_images_loaded = Constants.makeImage(self.walk_images) self.span = Constants.getCharacterSpan(self.static_images[0], self.position)
def draw_text(screen, render): """Draw text on screen. :param screen: game screen :param render: comma separated string :return: """ if render: for word in render.split(','): screen.blit(Constants.get_available_text()[word]['text'], Constants.get_available_text()[word]['pos'])
def check_cloud_folder_structure(current_user, curent_preference): if not os.path.exists(Constants.cloud_preference_folder_path(current_user)): os.mkdir(Constants.cloud_preference_folder_path(current_user)) if not os.path.exists(Constants.cloud_folder_path(current_user, curent_preference)): os.mkdir(Constants.cloud_folder_path(current_user, curent_preference)) if not os.path.exists(Constants.cloud_resource_folder_path(current_user, curent_preference)): os.mkdir(Constants.cloud_resource_folder_path(current_user, curent_preference)) if not os.path.exists(Constants.cloud_module_folder_path(current_user, curent_preference)): os.mkdir(Constants.cloud_module_folder_path(current_user, curent_preference)) if not os.path.exists(Constants.cloud_script_folder_path(current_user, curent_preference)): os.mkdir(Constants.cloud_script_folder_path(current_user, curent_preference))
def get_suite_param(self): param = Constants.XMLFILE_PREFF + "\"" for suite_name in self.options.suites: param += "%s " % suite_name param = Constants.add_right_enbrace(param) param += Constants.EXECUTE_PREFF + ("\" %s " % Constants.WRT_LAUNCHR_CMD) for e_name in self.options.suites: param += "%s " % e_name param = Constants.add_right_enbrace(param) return param
def quit_driver(driver=None): ''' Quits a selenium driver. If driver is running in docker, it stops the docker containers. @param driver: selenium driver to quit ''' logger.info('Quitting {} driver'.format(driver)) const = Constants() if driver is not None: driver.quit() if const.get_docker() is True: selenium_docker_container.stop_docker()
def update_db(user,current_preference): all_files = Files.get_all_files_from_db_by_user_preference(current_preference.preference_id) db_files = [ str(file[0]).replace(Constants.cloud_folder_path(user,current_preference),"") for file in all_files] exist = [path.replace(Constants.cloud_folder_path(user,current_preference), "") for path in Files.get_files_from_cloud(user,current_preference)] print(db_files) print(exist) not_exist = [] for file in exist: if file in db_files: db_files.remove(file) else: not_exist.append(file)
def post(self): parser = reqparse.RequestParser() parser.add_argument('userID', type=str, help='User ID', location='form', required=True) parser.add_argument('userData', type=str, help='User Data', location='form', required=True) parser.add_argument('userToken', type=str, help='User Token', location='form', required=True) args = parser.parse_args() user_id = args['userID'] token = args['userToken'] model = BaseResource.check_user_credentials_with_credentials(user_id, token) if not isinstance(model, PersonModel): # Some error happens here return model json_data = args['userData'] try: json_data = json.loads(json_data) except ValueError: return Constants.error_wrong_json_format() if not isinstance(json_data, list): return Constants.error_wrong_json_structure() print json_data result = [] for event_dict in json_data: if isinstance(event_dict, dict): event_model = EventModel.find_event(event_dict.get(EventModel.k_event_id)) event_model.creator_id = user_id event_model.configure_with_dict(event_dict) db.session.add(event_model) db.session.commit() event_json = event_model.to_dict() result.append(event_json) time_stamp = datetime.utcnow() response = dict() response[Constants.k_time_stamp] = time_stamp.isoformat() response['result'] = result # print response return response
def get_feature(self, daily_sale, menu_item_index, weather_item, with_days=False): if with_days: return [ menu_item_index, weather_item[Constants.JSON_TEMP], Constants.get_weather_type(weather_item) ] else: return [ self.get_day_of_week(daily_sale), menu_item_index, weather_item[Constants.JSON_TEMP], Constants.get_weather_type(weather_item) ]
def mapStaticSensors(self, map_obj, plotColor): constants = Constants() staticCoords = constants.staticSensorCoords() plotSensors(map_obj, staticCoords, plotColor) for i in range(staticCoords.shape[0]): folium.CircleMarker( (staticCoords[i][0], staticCoords[i][1]), radius=8, color='#000000', weight=1.0, fill_color='#000000', fill=True, fill_opacity=1, ).add_to(map_obj)
def mapExistingSensors(self, map_obj, plotColor): constants = Constants() existingCoords = constants.getExistingSensorCoords() existingNames = constants.getExistingSensorNames() #self.plotSensors(map_obj, existingCoords, plotColor) for i in range(existingCoords.shape[0]): folium.CircleMarker( (existingCoords[i][0], existingCoords[i][1]), radius=8, color=plotColor, weight=1.0, fill_color=plotColor, fill=True, fill_opacity=1, ).add_child(folium.Popup(existingNames[i])).add_to(map_obj)
def generate_params(self): f = Constants.XMLFILE_PREFF + "\"" tmp = "" for suite in self.suites.keys(): suite_obj = self.suites[suite] p_name = suite[0: suite.find("tests")] + "tests" f += Constants.DEVICE_TESTS_FILE % p_name if suite_obj.get_command().startswith(Constants.WRT_LAUNCHR_CMD): tmp += "%s " % suite_obj.get_command()[(len(Constants.WRT_LAUNCHR_CMD) + 1):] f = Constants.add_right_enbrace(f) e = "" if not tmp.isspace(): e = Constants.EXECUTE_PREFF + "\"" + Constants.WRT_LAUNCHR_CMD +" " + tmp e = Constants.add_right_enbrace(e) return f + " " + e
def _send_request(self, byte, expected_response=None): data = Constants.serialize_packet(byte) self.ser.write(data) response = self._get_response() if expected_response is not None and expected_response != response: raise PnuematicActuatorDriverResponseError(response, expected_response) return response
def post(self): user = users.get_current_user() if not user: # Send the user to the login page self.redirect(users.create_login_url(self.request.uri)) return assert user newKey = None if (self.request.get(Constants.ACTION_WORDS_PARAM) and self.request.get(Constants.REDIRECT_LINK_PARAM)): if self.request.get(Constants.ACTION_ID_PARAM): newAction = ndb.Key('Action', int(self.request.get(Constants.ACTION_ID_PARAM)), parent=getAccountKey(user.user_id())).get() else: newAction = Action(parent=getAccountKey(user.user_id())) newAction.user_id = user.user_id() newAction.redirect_link = self.request.get(Constants.REDIRECT_LINK_PARAM) newAction.actionwords = UserInput( self.request.get(Constants.ACTION_WORDS_PARAM)).getAllActionWords() newKey = newAction.put() if self.request.get(Constants.AJAX_REQUEST_PARAM): return ajaxSuccess(self) return self.redirect(listPagePath(Constants.NEW_KEY_PARAM, str(newKey.id()))) if self.request.get(Constants.AJAX_REQUEST_PARAM): return ajaxFailure(self) template_values = { 'user_nickname': user.nickname(), 'Constants': Constants.instance(), 'actionwords_input': self.request.get(Constants.ACTION_WORDS_PARAM), 'redirect_link_input': self.request.get(Constants.REDIRECT_LINK_PARAM)} template = JINJA_ENVIRONMENT.get_template('add.html') self.response.write(template.render(template_values))
def test_AlternativeReplacements(self): constantJson = { 'sets' : { }, 'specials' : { }, 'alternative_names' : { 'carda' : 'ca', 'card b' : ['cb', 'cb b'] } } with TempJson(constantJson) as json: c = Constants(json) self.assertEqual(c.translateAlt("ca"), "carda") self.assertEqual(c.translateAlt("cb"), "cardb") self.assertEqual(c.translateAlt("cc"), "cc")
def write(self, data): request = Constants.deserialize_packet(data) request = request[0] if request == Constants.PING_REQUEST: rospy.loginfo('Ping received') byte = Constants.PING_RESPONSE elif request > 0x20 and request < 0x30: rospy.loginfo('Open port {}'.format(request - 0x20)) byte = Constants.OPEN_RESPONSE elif request > 0x30 and request < 0x40: rospy.loginfo('Close port {}'.format(request - 0x30)) byte = Constants.CLOSE_RESPONSE else: rospy.loginfo('Default') byte = 0x00 self.buffer += Constants.serialize_packet(byte) return len(data)
def _get_response(self): data = self.ser.read(2) if len(data) != 2: raise PnuematicActuatorTimeoutError() response = Constants.deserialize_packet(data) data = response[0] chksum = response[1] self._verify_checksum(data, chksum) return data
def post(self): # user_id = request.form['userID'] # token = request.form['userToken'] # event_id = request.form['eventID'] # model = BaseResource.check_user_credentials_with_credentials(user_id, token) # # if not isinstance(model, PersonModel): # # Some error happens here # return model # items = EventModel.query.filter_by(event_id=event_id).all() # if len(items) > 0: # return {'status': 'event_not_exist'}, 401 team_members_json = request.form["teamMembersID"] try: team_members = json.loads(team_members_json) except ValueError: return Constants.error_wrong_json_format() if not isinstance(team_members, list): return Constants.error_wrong_json_structure() result = {} for team_member in team_members: local_user_id = team_member["user_id"] if local_user_id is None: continue person_model = PersonModel() person_model.first_name = team_member["first_name"] person_model.last_name = team_member["last_name"] # Add person to the model db.session.add(person_model) db.session.commit() result[local_user_id] = person_model.to_dict() return result
def __init__(self): self.num_shapes = 3 self.tri=0; self.trap = 1;self.tri_stop=2; self.adj = 1; self.non_adj = 0 self.num_dir = 2; self.num_adj = 2 self.right = 0; self.left = 1 self.graph = None self.out = [] self.weights = None self.sentence = None self.constants = Constants()
def post(self): parser = reqparse.RequestParser() parser.add_argument('facebookID', type=str, help='Facebook ID', location='form') parser.add_argument('email', type=str, help='User email', location='form', required=True) parser.add_argument('firstName', type=str, help='First Name', location='form', required=True) parser.add_argument('lastName', type=str, help='Last Name', location='form', required=True) parser.add_argument('password', type=str, help='Password', location='form', required=True) args = parser.parse_args() person_model = PersonModel() person_model.email = args['email'] items = PersonModel.query.filter_by(email=person_model.email).all() if len(items) > 0: return Constants.error_with_message_and_status('user_is_already_exist', 401) parameter = 'password' if not parameter in args: return Constants.error_missed_parameter(parameter) person_model.first_name = args['firstName'] person_model.last_name = args['lastName'] person_model.facebook_id = args['facebookID'] # Encrypt user password password = request.form['password'] encr_password = passlib.encrypt(password, salt_length=100) person_model.password = encr_password # Generate user token with expiration date person_model.token = TokenSerializer.generate_auth_token(person_model.person_id) # Add person to the model db.session.add(person_model) db.session.commit() return person_model.to_dict()
def test_SpecialReplacements(self): constantJson = { 'sets' : { }, 'specials' : { "dream cards" : ["dream", "emeralddrake", "laughingsister", "nightmare", "ysera awakens"] }, 'alternative_names' : { } } with TempJson(constantJson) as json: c = Constants(json) # tests replace replaced = c.replaceSpecial(["111", "dreamcards", "333", "444"]) self.assertEqual(replaced, ["111", "dream", "emeralddrake", "laughingsister", "nightmare", "yseraawakens", "333", "444"])
def main(stdscr): """Initialises the Game object and basically gets out of the way""" # Make sure the screen is big enough for our amazing game (ywidth, xwidth) = stdscr.getmaxyx() if (ywidth < Constants.YRES or xwidth < Constants.XRES): stdscr.addstr("The terminal should be at least {} by {}".format(Constants.XRES, Constants.YRES)) stdscr.getch() return -1 # Set-up the colours we'll be using' curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK) Constants.initColours() # Make the window.. win = curses.newwin(Constants.YRES, Constants.XRES) win.bkgd(' ', curses.color_pair(0)) # Start the game, with the title screen. title = TitleScreen(win) title.execute()
def __parse_rc_file(self, rcfile): parser = ConfigParser() with open(rcfile) as fp: parser.read_file(fp) for section in parser.sections(): # Ignore sections having enabled = False if parser.has_option(section, 'enabled') and parser.getboolean(section, 'enabled') is False: continue # Case insensitive mapping - [logger]\nlevel=INFO in config becomes # self.config['logger.level'] = 'INFO' for key, value in parser.items(section): key = ('%s.%s' % (section, key)).lower() value = Constants.expand_value(value) self.config[key] = value
def get(self): user = users.get_current_user() if not user: # Send the user to the login page self.redirect(users.create_login_url(self.request.uri)) return assert user match = self.request.get(Constants.MATCH_PARAM, '') highlightKey = self.request.get(Constants.NEW_KEY_PARAM, '0') matchingUserActions = fetchMatchingActions(match, user) template_values = { 'user_nickname': user.nickname(), 'matching_actions': matchingUserActions, 'user_id': user.user_id(), 'match': match, 'Constants': Constants.instance(), 'highlight_key': int(highlightKey)} template = JINJA_ENVIRONMENT.get_template('list.html') self.response.write(template.render(template_values))
def merge_suite_result(self, result_xml, plan_name): os.chdir(self.latest_result_folder) root = ElementTree.Element('test_definition') first = True start_at = None end_at = None summary_xml = TotalSummary(plan_name) for suite_name in self.suites: result_name = "%s.xml" % suite_name if os.path.isfile(result_name): print "Reading the result of suite : %s" % suite_name if True: xml_tree = ElementTree.parse(result_name) xml_root = xml_tree.getroot() if first: first = False env_elm = xml_root.find('environment') root.append(env_elm) summary_xml.set_environment(env_elm) root.append(xml_root.find('summary')) summary = xml_root.find('summary') this_start = summary.find('start_at') this_end = summary.find('end_at') start_at = self.select_start_at(start_at, this_start.text) end_at = self.select_end_at(end_at, this_end.text) for this_suite in xml_root.findall('suite'): root.append(this_suite) summary_xml.add_suite_elm(this_suite) else: print "[Error] the expecting result of the suite %s is not found! " % suite_name s_tag = root.find('summary/start_at') if s_tag is not None: s_tag.text = start_at e_tag = root.find('summary/end_at') if e_tag is not None: e_tag.text = end_at sum_elm = root.find('summary') summary_xml.set_summary(sum_elm) capability_root = self.parse_capablities() summary_xml.set_capabilities(capability_root) tree = ElementTree.ElementTree() tree._setroot(root) d = os.path.abspath(os.path.dirname(result_xml)) if not os.path.exists(d): os.makedirs(d) tree.write(result_xml, encoding="utf-8") print "Generating the merged result XML '%s'" % result_xml sum_tree = ElementTree.ElementTree() sum_root = summary_xml.to_xml() Constants.indent(sum_root) sum_tree._setroot(sum_root) print "Generating the summary XML in %s" % (self.latest_result_folder + "summary.xml") outFile = open(self.latest_result_folder + "summary.xml", 'w') outFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") outFile.write("<?xml-stylesheet type=\"text/xsl\" href=\"summary.xsl\"?>\n") sum_tree.write(outFile, encoding="utf-8") outFile.close()
def open_report(self): Constants.copy_style_in_result_folder(self.latest_result_folder)
def get_f(self): f = Constants.XMLFILE_PREFF + "\"" + Constants.DEVICE_TESTS_FILE % self.get_name() return Constants.add_right_enbrace(f)
# Import Modules import pygame import resourceLoader from level import Level from sprite import Sprite, AnimatedSprite, Animation, BackgroundSprite, DynamicSprite from player import Player from camera import Camera # Initialize PyGame pygame.init() # Initialize constants from constants import Constants as C C.init_constants() # Setup the screen SCREEN = pygame.display.set_mode((C.SCREEN_WIDTH,C.SCREEN_HEIGHT)) # Load resources resourceLoader.load_resources() # Load level Level.load_level("tatooine_1.json") # Create background BackgroundSprite(resourceLoader.get_image("backgrounds\\tatooine.png")) # Create player player = Player() player.set_position(300, 0)
def get_e(self): e = Constants.EXECUTE_PREFF + "\"" + Constants.WRT_LAUNCHR_CMD + " %s" % self.get_name() return Constants.add_right_enbrace(e)
logging.info("\nIn find_routes_for_colloquial_bus_numbers: dict_colloquial_bus_numbers :"+str(dict_colloquial_bus_numbers)) return dict_colloquial_bus_numbers def get_all_buses(self): """ Returns the list of colloquial_bus_numbers for the specified city/university. """ doublemap_routes_url = self.DOUBLEMAP_ROUTES_API_URL response = json.loads(urllib.urlopen(doublemap_routes_url).read()) busList = [] for route in response: busList.append(route['name']) return busList if __name__ == "__main__": #Input city = "IUB" #target location coordinates targetCoordinates = (39.17155659473131, -86.50890111923218) #Create constans object to fetch all constant values constantsObject = Constants() constantsObject.load_constants("constants.json") #Create route object routeObject = Route(constantsObject, city) listColloquialBusNumbers = ['3 College Mall / Bradford Place','6 Campus Shuttle - Sat'] listOfActualBusNumbers = routeObject.get_actual_bus_numbers(listColloquialBusNumbers) print listOfActualBusNumbers
class EisnerAlgo: def __init__(self): self.num_shapes = 3 self.tri=0; self.trap = 1;self.tri_stop=2; self.adj = 1; self.non_adj = 0 self.num_dir = 2; self.num_adj = 2 self.right = 0; self.left = 1 self.graph = None self.out = [] self.weights = None self.sentence = None self.constants = Constants() def eisner_first_order(self, sentence): self.sentence = sentence n = len(sentence) coder = np.arange((self.num_shapes * self.num_dir * n * n), dtype=np.int64).reshape([self.num_shapes, self.num_dir, n, n]) self.out = np.arange(n * n * self.num_shapes * self.num_dir * 2, dtype=np.int64).reshape([self.num_shapes, self.num_dir, 2, n, n]) chart = pydecode.ChartBuilder(coder, self.out) chart.init(np.diag(coder[self.tri, self.right]).copy()) chart.init(np.diag(coder[self.tri, self.left, 1:, 1:]).copy()) for direction in range(self.num_dir): for tri, triStop, index in zip(np.diag(coder[self.tri, direction]), np.diag(coder[self.tri_stop, direction]), range(n)): if(index == 0): continue chart.set(triStop, [[tri]], labels=[np.int64(self.out[self.tri_stop,\ direction, self.adj, index, index])]) self.all_label_indices = np.array([],dtype=np.int64) for k in range(1, n): for s in range(n): t = k + s if t >= n: break # First create incomplete items. out_ind = np.zeros([t-s], dtype=np.int64) if s!=0: label_indices = self.compute_label_indices(self.trap, self.left, t , s) chart.set_t(coder[self.trap, self.left, s, t], coder[self.tri_stop, self.right, s, s:t], coder[self.tri, self.left, s+1:t+1, t], labels=label_indices) label_indices = self.compute_label_indices(self.trap, self.right, s, t) chart.set_t(coder[self.trap, self.right, s, t], coder[self.tri, self.right, s, s:t], coder[self.tri_stop, self.left, s+1:t+1, t], labels= label_indices) if s!=0: label_indices = self.compute_label_indices(self.tri, self.left, t, s) chart.set_t(coder[self.tri, self.left, s, t], coder[self.tri_stop, self.left, s, s:t], coder[self.trap, self.left, s:t, t]) label_indices = self.compute_label_indices(self.tri_stop, self.left, s, t) chart.set(coder[self.tri_stop, self.left, s, t], [[coder[self.tri, self.left, s, t]]], labels= label_indices) label_indices = self.compute_label_indices(self.tri, self.right, s, t) chart.set_t(coder[self.tri, self.right, s, t], coder[self.trap, self.right, s, s+1:t+1], coder[self.tri_stop, self.right, s+1:t+1, t]) if s!=0 or (s==0 and t==n-1): label_indices = self.compute_label_indices(self.tri_stop, self.right, s, t) chart.set(coder[self.tri_stop, self.right, s, t], [[coder[self.tri, self.right, s, t]]], labels=label_indices) self.graph = chart.finish() return self.graph def compute_weights(self, label_scores): if self.weights == None: self.weights = pydecode.transform(self.graph, label_scores) return self.weights def reset_values(self): self.weights = None def compute_marginals(self, label_scores): self.compute_weights(label_scores) edge_marginals = pydecode.marginals(self.graph, self.weights) return edge_marginals def best_path(self, label_scores): self.compute_weights(label_scores) return pydecode.best_path(self.graph, self.weights) def best_edges(self, label_scores): path = self.best_path(label_scores) best_edges = path.edges heads = np.array([], dtype=np.int64) for edge in best_edges: heads = np.append(heads, edge.head.label) shapes, direction, head, modifier = self.get_indices_of_heads(heads, len(self.sentence)) print "shapes" pprint.pprint(shapes) print "direct" pprint.pprint(direction) print "head" pprint.pprint(head) print "mod" pprint.pprint(modifier) right_indices = np.where(direction == 0) left_indices = np.where(direction == 1) depen = np.full(len(self.sentence), -1, dtype=np.int64) depen[modifier[right_indices].tolist()] = head[right_indices].tolist() depen[head[left_indices].tolist()] = modifier[left_indices].tolist() return depen def get_indices_of_heads(self, heads, n): shapes, direction, row, column = self.constants.get_indices(heads, n) indices_needed = np.where(shapes == 1) return shapes[indices_needed], direction[indices_needed], row[indices_needed], column[indices_needed] def compute_label_indices(self, shape, direction, head, mod): indices = np.tile([shape, direction, 0, head, mod], abs(head-mod)).\ reshape(abs(head-mod), 5) indices[:,2] = self.compute_adj(head, mod) if(indices.shape[0] == 1): return np.array([self.out[indices[0,0], indices[0,1], indices[0,2], indices[0, 3], indices[0, 4]]]) return self.out[indices[:,0].tolist(),indices[:,1].tolist(), indices[:,2].tolist(), indices[:,3].tolist(), indices[:,4].tolist()] def compute_adj(self, head, mod): if(head > mod): split = np.arange(mod, head) else: split = np.arange(head, mod) vfunc = np.vectorize(self.is_adj) return vfunc(head, split) def is_adj(self, head, split): if abs(head - split) <=1: return self.adj else: return self.non_adj
class AppWindow(QtGui.QMainWindow): """This is the main application window displaying the shaft geometries and relevant safety factors. A toolbar allows the user to load & save files, edit the configuration, and alter views. """ def __init__(self): QtGui.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("Wind Turbine Shaft Analysis") self.setFixedSize(1280,720) self.create_actions() self.create_menu() # Setup the main application. self.main_widget = QtGui.QWidget(self) self.layout = QtGui.QVBoxLayout(self.main_widget) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) # Initialize constants and statuses of the application. self.init_values() # Update the main window with solutions. self.update_solution() # Tell the user what files are still required. self.update_status() def init_values(self): """Initialize statuses of whether or not files have been loaded, whether shaft information displays are normalized, and whether or not the plot needs to be refreshed. Also initialize a class holding constants. """ # Holds the states of whether the necessary files have been loaded. # The 4 required files are: # - designs specifications # - material properties # - load factors # - wind history. self.loaded = [False, False, False, False] # This value determines how details of the shaft sections are displayed. # A value of 'True' scales text uniformly; A value of 'False' places # text underneath plotted shaft sections. self.normalized = False # This value determines whether solutions have to be (re)solved. # Prevents recalculating solutions if user only wants to change views. self.reload = True # Initialize constants. self.c = Constants() def create_actions(self): """Create menu actions.""" # File Menu Actions self.act_obt_design = QtGui.QAction('Obtain Design', self, shortcut='Ctrl+1', triggered=self.open_design) self.act_obt_prop = QtGui.QAction('Obtain Material Properties', self, shortcut='Ctrl+2', triggered=self.open_prop) self.act_obt_load = QtGui.QAction('Obtain Load Factors', self, shortcut='Ctrl+3', triggered=self.open_load) self.act_obt_wind = QtGui.QAction('Obtain Wind History', self, shortcut='Ctrl+4', triggered=self.open_wind) self.act_save_design = QtGui.QAction('Save Design', self, shortcut='Ctrl+S', triggered=self.save_design) self.act_quit = QtGui.QAction('Quit', self, shortcut='Ctrl+Q', triggered=self.quit_file) # Edit Menu Actions self.act_edit_design = QtGui.QAction('Edit Design', self, shortcut='Ctrl+E', triggered=self.edit_design) # View Menu Actions self.act_normalize_view = QtGui.QAction('Normalize View', self, shortcut='Ctrl+V', checkable=True, triggered=self.normalize_view) self.act_normalize_view.setStatusTip('Uniformly reposition shaft ' 'information. The order of information still ' 'corresponds to the order of shaft sections ' 'i.e. the first set of information corresponds' ' to section 1, the second to section 2, etc.') # Help Menu Actions self.act_about = QtGui.QAction('About', self, shortcut='Ctrl+A', triggered=self.about) def create_menu(self): """Create the application menu with File, Edit, View, Help and About tabs. """ file_menu = QtGui.QMenu('File', self) file_menu.addAction(self.act_obt_design) file_menu.addAction(self.act_obt_prop) file_menu.addAction(self.act_obt_load) file_menu.addAction(self.act_obt_wind) file_menu.addSeparator() file_menu.addAction(self.act_save_design) file_menu.addSeparator() file_menu.addAction(self.act_quit) edit_menu = QtGui.QMenu('Edit', self) edit_menu.addAction(self.act_edit_design) view_menu = QtGui.QMenu('View', self) view_menu.addAction(self.act_normalize_view) help_menu = QtGui.QMenu('Help', self) help_menu.addAction(self.act_about) menubar = self.menuBar() menubar.addMenu(file_menu) menubar.addMenu(edit_menu) menubar.addMenu(view_menu) menubar.addMenu(help_menu) def update_solution(self): """Plot shaft sections and related info to the application window. """ if self.loaded == [True, True, True, True]: if self.reload == True: self.sol = Solutions(self.c) self.sol.solve() infoplot = InfoPlot(self.sol, self.c, self.normalized, self.main_widget) self.layout.addWidget(infoplot) self.reload = False else: infoplot = InfoPlot(self.sol, self.c, self.normalized, self.main_widget) self.layout.addWidget(infoplot) def delete_solution(self): """Delete the current plot of the shaft and infomation.""" for i in range(self.layout.count()): self.layout.itemAt(i).widget().setParent(None) def normalize_view(self): """Scale the info dislayed beneath each shaft section so that text does not interfer with each other or the plot. """ self.normalized = not self.normalized self.refresh() def refresh(self): """Refresh the plot by deleting current solutions and updating with another set of solutions. """ self.delete_solution() self.update_solution() self.update_status() def update_status(self): """Update the status bar and display what files are still required. """ self.statusBar().showMessage(self.check_loaded()) def status_format_error(self): """Display an error message on the status bar if the format of a file is not usable.""" self.statusBar().showMessage("ERROR. Please check formatting of file.") def open_design(self): """Load shaft geometries from a file.""" try: file = QtGui.QFileDialog.getOpenFileName(self, 'Open design') self.c.open_design(str(file)) self.loaded[0] = True self.reload = True self.refresh() except IndexError or ValueError: self.status_format_error() def open_prop(self): """Load material properties from a file.""" try: file = QtGui.QFileDialog.getOpenFileName(self, 'Open material properties') self.c.open_prop(str(file)) self.loaded[1] = True self.reload = True self.refresh() except IndexError or ValueError: self.status_format_error() def open_load(self): """Load external/environmental factors from a file.""" try: file = QtGui.QFileDialog.getOpenFileName(self, 'Open load factors') self.c.open_load(str(file)) self.loaded[2] = True self.reload = True self.refresh() except IndexError or ValueError: self.status_format_error() def open_wind(self): """Load wind history from a file.""" try: file = QtGui.QFileDialog.getOpenFileName(self, 'Open wind history') self.c.open_wind(str(file)) self.loaded[3] = True self.reload = True self.refresh() except IndexError or ValueError: self.status_format_error() def check_loaded(self): """Check to see what files have been loaded and return a message stating which files are still needed. """ msg0 = msg1 = msg2 = msg3 = msg4 = "" if False in self.loaded: msg0 = "Required: " if self.loaded[0] == False: msg1 = "Design specifications. " if self.loaded[1] == False: msg2 = "Material properties. " if self.loaded[2] == False: msg3 = "Load factors. " if self.loaded[3] == False: msg4 = "Wind history." message = "%s%s%s%s%s" % (msg0, msg1, msg2, msg3, msg4) return message def save_design(self): """Save the current design by storing shaft lengths and diameters into a file. Original design specifications are stored in order to preserve the design file format. """ if self.loaded[0] == False: self.statusBar().showMessage("Please load design specifications first.") else: c = self.c design = (('%g %g %g %g %g %g %g\n' '%g %g %g %g %g %g %g\n' '%g %g %g %g %g %g %g') % (c.L[1], c.L[2], c.L[3], c.L[4], c.L[5], c.L[6], c.L[7], c.D[1], c.D[2], c.D[3], c.D[4], c.D[5], c.D[6], c.D[7], c.sf_o, c.sf_s, c.life, c.twist_max, c.R[1], c.R[2], c.R[3])) file = QtGui.QFileDialog.getSaveFileName(self, 'Save design', selectedFilter='*.txt') fname = open(file, 'w') fname.write(design) fname.close() def edit_design(self): """Open a new window to allow users to edit the lengths and diameters of the shaft sections. """ if self.loaded[0] == False: self.statusBar().showMessage("Please load design specifications first.") else: self.edit_window = EditWindow(self.c, parent=self) self.edit_window.show() self.edit_window.setWindowTitle('Edit Design [m]') def about(self): QtGui.QMessageBox.about(self, 'About', "This project builds off a" " project given by Cornell's Spring 2013 MAE" " 2120 course. Given external settings," " material properties, and the design for a" " wind turbine, students were asked to solve" " for and summarize mechanical factors faced" " by sections of the turbine's shafts." " Originally coded as a single, standalone" " file in MATLAB, this program utilizes" " object-oriented programming via Python and" " integrates multiple libraries in order to" " solve for, plot, display, and iterate via a" " GUI turbine shaft geometries and safety" " factors.") # Close the application when Ctrl+Q keyboard command is inputted or when # 'Quit' is selected in the 'File' menu tab. def quit_file(self): self.close() # Close the application when the red 'X' of the window is pressed. def closeEvent(self, event): self.close()