Recent Entries 10
- pattern minor 112d agoRails 5 controller to get information about Steam usersI've done a bit of modifications and finally got it working, and did a lot of reading about `@` vs `@@` vs just declaring and I came up with. It goes to Steam's API to return information (JSON Format) based on the endpoint. A list of games they own, a list of games they recently played, profile information, etc. ``` class SteamController < ApplicationController def initialize @steamKey = ENV["steam_api_key"] @ISteamUrl = "http://api.steampowered.com/ISteamUser/" @IPlayerUrl = "http://api.steampowered.com/IPlayerService/" end def get_steam_summary_per_user #/steam/:id @steamEndpoint = "GetPlayerSummaries/v0002/?key="+@steamKey+"&steamids=" @steamId = User.find(params[:id]).steamId @playerUrl = @ISteamUrl + @steamEndpoint + @steamId.to_s @games = HTTParty.get(@playerUrl).to_json render json: @games end def get_steam_recently_played_per_user #/game/:id @recPlayedEndpoint = "GetRecentlyPlayedGames/v0001/?key="+@steamKey+"&steamid=" @steamId = User.find(params[:id]).steamId @playerUrl = @IPlayerUrl + @recPlayedEndpoint + @steamId.to_s @games = HTTParty.get(@playerUrl).to_json render json: @games end def get_steam_owned_games_per_user #/allGames/:id @allGamesUrl = "GetOwnedGames/v0001/?key="+@steamKey+"&steamid=" @steamId = User.find(params[:id]).steamId @playerUrl = @IPlayerUrl + @allGamesUrl + @steamId.to_s @games = HTTParty.get(@playerUrl).to_json render json: @games end end ``` `Routes` ``` get '/steam/:id', to: 'steam#get_steam_summary_per_user' get '/games/:id', to: 'steam#get_steam_recently_played_per_user' get '/allgames/:id', to: 'steam#get_steam_owned_games_per_user' ``` I originally just has `@baseUrl` but realized they have multiple services and versions, but even before that I couldn't figure out why doing `@baseUrl = "http://api.steampowered.com/"+@recPlayedEndpoint+"etcetc` wouldn't work - I assumed it was related to initializing the `@recPlayedEndpoint
- pattern minor 112d agoEmail ControllerI'm developing a Social Engineering Awareness Training Application. This is the focus of my thesis for my undergraduate degree. This will be a multi-part review request, however, if you want to see the entire application, it can be found on GitHub. For this request, I'm looking to see how my EmailController is set up and how efficient you think it might be. I open to any and all suggestions about any facet of the code. This will be a long request as I couldn't figure out how to split up a lot of the logic into multiple requests without meaning being lost. Keep in mind that this application is nearly to testing, however, there are a few pieces still left to do (a few templates, a few views, documentation). EmailController ``` /** * sendEmail * Function mapped to Laravel route. Defines variable arrays and calls Email Class executeEmail. * * @param Request $request Request object passed via AJAX from client. */ public static function sendPhishingEmail(Request $request) { if(Auth::check()) { $fromEmail = Campaign_Email_Addresses::where('EmailAddress',$request->input('fromEmailText'))->first(); $template = Template::where('FileName',$request->input('templateText'))->first(); $campaign = Campaign::where('Id',$request->input('campaignText'))->first(); if(!empty($fromEmail) && !empty($template) && !empty($campaign)) { putenv("MAIL_USERNAME=$fromEmail->EmailAddress"); putenv("MAIL_NAME=$fromEmail->Name"); $cryptor = new Cryptor(); $password = $cryptor->decrypt($fromEmail->Password); putenv("MAIL_PASSWORD=$password"); $templateClass = "\\App\\Mail\\$template->Mailable"; $sendingChoice = $request->input('sendingChoiceRadio'); if($sendingChoice == 'user') { $user = Mailing_List_User::where('Id',$request->input('userIdText'))->first(); if(!empty($user)) { Mail::to($user->Email,$user->Fir
- pattern moderate 112d agoC# Rental ProgramI knew a little Java, and thought what the hell, I'll help my school and design this program that'll help checkout phone chargers and calculators and things to students. So I got in way over my head, but I got the program working. I wrote it in C#, and while the whole thing needs review, I really feel my checkout function could use immediate improvement. This is the controller function for creating a checkout record, I have 6 different tables: - `tb_BannedUsersTable` - `tb_CheckoutCheckin` - `tb_Items` - `tb_LabTech` (employees) - `tb_Student` It starts by taking a Student ID and up-to 3 items from an HTML view to create a record. it creates a new record per item, because of how everything gets checked in. It's a long garbled mess, so any advice is greatly appreciated. ``` public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(string StudentID, string upc, string upc1, string upc2) { try { ViewModels view = new ViewModels(); Student_Entities ExternalDB = new Students_Entities(); tb_Student sfh = new tb_Student(); if (StudentID.Length > 9) { //Shortens the scanned StudentID to 9 characters StudentID = StudentID.Truncate(9); } // Checks for Student record in the exsisting database var queryCount = db.tb_Student.Where(s => s.ID == StudentID).Count(); if (queryCount s.ID == StudentID); if (bsh == null) { ViewBag.Message = "Student ID # not found in the system, please add the student from the Home menu"; return View("Index"); } //creates student record if its found sfh.ID = bsh.ID; sfh.EMAIL_ADDRESS = bsh.EMAIL_ADDRESS; sfh.UserNAME = bsh.UserNAME; sfh.FIRST_NAME = bsh.FIRST_NAME; sfh.LAST_NAME = bsh.LAST_NAME; sfh.PHONE =
- pattern minor 112d agoSpring MVC dynamically adding form elementsI made a simple form with an option of adding one text field dynamically on mouse click. And I will be grateful for suggestions on how I may improve the code. ``` @Controller public class MyController { public ArrayList fieldArrayList; @RequestMapping(value="/create", method= RequestMethod.GET) public String myForm(Model model, @ModelAttribute NewField newField) { fieldArrayList = new ArrayList<>(); fieldArrayList.add(newField); model.addAttribute("dataForm", new DataForm()); return "create"; } @RequestMapping(value="/create", method=RequestMethod.POST) public String formSubmit(Model model, HttpServletRequest hsr, @ModelAttribute DataForm dataForm) { if (hsr.getParameterValues("lastField") != null) { String[] lastF = null; lastF = hsr.getParameterValues("lastField"); List d = Arrays.asList(lastF); int count = d.size() + 1; for (int i = 2; i < count+1; i++) { NewField newField = new NewField(); String s1 = hsr.getParameter("p_new_" + String.valueOf(i)); String s2 = hsr.getParameter("l_" + String.valueOf(i)); newField.setStr1(s2); newField.setStr2(s1); fieldArrayList.add(newField); } } model.addAttribute("dataForm", dataForm); model.addAttribute("fieldArrayList", fieldArrayList); return "view"; } ``` ` Getting Started: Handing Form Submission Form Id: Name: $(function() { var addDiv = $('#addinput'); var i = $('#addinput p').size() + 1; $('#addNew').live('click', function() { $(' ' + document.getElementById('p_new').value + ' ').appendTo(addDiv); //alert(i); i++; return false; }); $('#remNew').live('click', function() { if( i > 2 ) { $(this).parents('p').remove(); i--;
- pattern minor 112d agoList enrolled users & show checkmark if all activities are completeI'm a beginner with rails working on a rails 4 project to use with my students. Users enroll in lessons; on enrollment, four activities are created for each user (expositions, scrambled, dictations, and spellings). Each of these activities has a number of words which are set to `false` in the db upon creation, and change to `true` as the user rewrites them correctly. At the bottom of each lesson's view I'm displaying a list of enrolled users. If the user completes all four activities, I'm displaying a font-awesome checkmark icon. I'm noticing as more students enroll in each lesson that loading times for the lesson show view are increasing--most probably because my setup to find whether each user completed the lessons is inefficient. In my lessonss controller I wrote helper methods to list the lesson's enrolled users, and to generate arrays with users who completed each of the lessons activities. In the view page, I'm testing whether each of the listed users completed all four activities in order to add the "completed" checkmark to his or her name. As things are right now the code does what it's supposed to, but I'd love to learn and improve the student-user's experience. Any feedback regarding how I can improve this process will be well received. In lessons controller: ``` helper_method :enrolled_users def enrolled_users lesson = Lesson.find(params[:id]) enrollments = lesson.enrollments enrolled_users = enrollments.map { |enrollment| enrollment.user } end helper_method :completed_scram def completed_scram lesson = Lesson.find(params[:id]) completed_scram = enrolled_users.map do |user| current_enrollment = lesson.enrollment_for(user) all_unscramble = current_enrollment.scrambled_words user if all_unscramble.all? { |scrambled| scrambled.completed == true } end end helper_method :completed_expos def completed_expos lesson = Lesson.find(params[:id]) completed_expos = enrolled_users.map do |user|
- pattern minor 112d agoBaseball player statistics controllerI'm somewhat new to JavaScript and AngularJS, and read in Doug Crockford's book that hoisted function declarations can lead to issues. If you have any pointers on how to structure my file, those would be much appreciated. ``` (function() { 'use strict'; function PlayerProfileStatsCtrl($q, ColumnService, LookupService, PlayerService, PlayerStatsService) { var vm = this; var loadStats = function (player) { $q.all({ catchingStats: PlayerStatsService.getCatchingStats(player.playerId), fieldingStats: PlayerStatsService.getFieldingStats(player.playerId), hittingStats: PlayerStatsService.getHittingStats(player.playerId), pitchingStats: PlayerStatsService.getPitchingStats(player.playerId), playerStats: LookupService.getByKeyPromise('lkplayerstat'), statTypes: LookupService.getListPromise('lkstattype') }).then(function (results) { // Associate stat result lists with string keyed stat types. vm.statResults = { C: results.catchingStats.statList, F: results.fieldingStats.statList, H: results.hittingStats.statList, P: results.pitchingStats.statList }; // Assign the player stat lookup object. vm.playerStats = results.playerStats; // Assign the stat type lookup list. vm.statTypes = results.statTypes; initStatColumnDefs(); }); }; // Call loadStats() after the player promise is resolved. vm.player = PlayerService.getPlayer(loadStats); var initStatColumnDefs = function () { // The column definitions are contained in lists and associated by stat type. vm.statColumnDefs = {}; for (var i = 0; i < vm.statTypes.length; i++) { // Get the
- pattern minor 112d agoASP controller for tracking equipmentThis was originally posted here. I'm hoping Code Review will be a little more helpful in giving me a concrete direction. I've been working on a project based off of this tutorial. Unfortunately, the controller classes in this are quite dense and have terrible separation of concerns. I should have realized this originally but, I ran with it and now am stuck dealing with the terrible design from this tutorial with my added features/bad decisions. I've been stuck and overthinking this. In my case, I have 3 controllers: Hardware, Employee, Project. They access the database, filter the data and pass them along to the view. I also create certain UI components in the controller (see SelectList in the Create function below). I want to break down these controllers into smaller, reusable parts. Filtering for example, could be re-used by different models but I can't quite abstract this in my head. There's a lot going on in most controller. Here's one of them for example: ``` public class HardwareController : Controller { private LATTContext db = new LATTContext(); // GET: Hardware public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page) { ViewBag.CurrentSort = sortOrder; ViewBag.SerialNoParm = sortOrder == "serialNo" ? "serialNo_desc" : "serialNo"; ViewBag.CabModelParm = sortOrder == "cabModel" ? "cabModel_desc" : "cabModel"; ViewBag.PlatformParm = sortOrder == "plat" ? "plat_desc" : "plat"; ViewBag.VendorParm = sortOrder == "vendor" ? "vendor_desc" : "vendor"; ViewBag.CategoryParm = sortOrder == "category" ? "category_desc" : "category"; ViewBag.EmployeeParm = sortOrder == "employee" ? "employee_desc" : "employee"; if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; var hardwares = from h in db.hardwares
- pattern minor 112d agoExtracting queries from controller to modelI had a complex query in the controller like: ``` def outgoing_tasks @tasks = current_user. assigned_tasks. uncompleted. includes(executor: :profile). order("deadline DESC"). paginate(page: params[:page], per_page: Task.pagination_per_page) end ``` and since I have some other collections in that controller I refactored to this: ``` def outgoing_tasks @tasks = current_user.assigned_tasks.assigned_default(page: params[:page]) end ``` with these new methods in the model: ``` def self.ordered order("deadline DESC") end def self.paginated(page: 1) paginate(page: page, per_page: self.pagination_per_page) end def self.assigned_default(page: 1) uncompleted.includes(executor: :profile).ordered.paginated(page: page) end ``` Should I do something differently or is this okay?
- pattern minor 112d agoDrawing Routes on a MapI have this class: ``` public class MapController { private Polyline _currentPolyline; // The line connecting two locations on the map private GoogleMap _map; private Context _context; public MapController(GoogleMap map, Context context) { _map = map; _context = context; } /** * Draws a route on the map. * * @param directions the Google Map Directions JSON string with the routes * @throws JSONException */ public void drawRoute(String directions) throws JSONException { // First parse the JSON to extract the points into an easily manipulated form List>> routes = new DirectionsHelper().parsePathsFromJson(directions); // Only one polyline can be shown on the map at a time hideRoute(); ArrayList points; PolylineOptions polyLineOptions = null; // Traversing through routes for (int i = 0; i (); polyLineOptions = new PolylineOptions(); List> path = routes.get(i); for (int j = 0; j point = path.get(j); double lat = Double.parseDouble(point.get("lat")); double lng = Double.parseDouble(point.get("lng")); LatLng position = new LatLng(lat, lng); points.add(position); } polyLineOptions.addAll(points); polyLineOptions.color(ContextCompat.getColor(_context, R.color.colorPrimary)); } _currentPolyline = _map.addPolyline(polyLineOptions); } /** * Removes the currently drawn {@link Polyline} from the map. */ public void hideRoute() { if (_currentPolyline != null) { _currentPolyline.removeRoute(); } } } ``` Is it generally a good practice to call `hideRoute()` inside the `drawRoute()` method or does it depend on other factors? For example: should the caller be responsible for clearing the map before drawing the new path
- pattern minor 112d agoCakePHP static pages (without entity) but with dynamic contentI have a few pages that is not connected with entities (index page, terms of use page, email page). Detailed description: In CakePHP, when you want to have a static page (such as index for example), you should use the `PagesController` (not connected to any entity). However, my static pages have dynamic content, as the index page (the `navbar` is dynamic: it has the name of the user when logged in, and special buttons). 1st: To do this, I create a `CustomStaticPagesController` controller (which is not connected to any entity), in which I created the methods (index, email, termos-de-servico). 2nd: I edited the `routes.php` references to the actions without the standard localhost/controller/action now this localhost/action. Question: How can I improve (do it right) the two points referred to above? Any other point to improve ? CustomStaticPagesController controller code: ``` Auth->user('id'); $username = $this->Auth->user('username'); $this->loadModel('Categories'); $categories = $this->Categories->getAllCategories(); $this->loadModel('SubCategories'); $subCategories = $this->SubCategories->getAllSubCategories(); $subCategoriesName = $this->SubCategories->listAllSubCategories(); $this->loadModel('UserTypes'); $userTypes = $this->UserTypes->listSubCategories(); $this->loadModel('Banners'); $fullBanners = $this->Banners->full(); $smallBanners = $this->Banners->small(); $this->loadModel('Products'); $productsBestSeller = $this->Products->getProductTrendByColumn('sold', 0); $productsNewer = $this->Products->getProductTrendByColumn('created', 0); $productsMostPopular = $this->Products->getProductTrendByColumn('visited', 0); $this->loadModel('Offers'); $offers = $this->Offers->offersRecursive(); $this->loadModel('News'); $news = $this->News->getRecentNews(); $this->set(compact('userId', 'username', 'use