branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<repo_name>re2005/vue-beautiful-chat<file_sep>/types/vue-beautiful-chat.d.ts declare module 'vue-beautiful-chat' { import {PluginFunction, PluginObject} from 'vue'; /** * Vue Beautiful Chat * * @class */ class VueBeautifulChat implements PluginObject<{}> { [key: string]: any; install: PluginFunction<{}>; static install(pVue: typeof Vue, options?:{} | undefined): void; } namespace VueBeautifulChat { } export = VueBeautifulChat; }
db9f95eeecc1864e739c538bfabf9ee41ddbe759
[ "TypeScript" ]
1
TypeScript
re2005/vue-beautiful-chat
04b26997230b963183b9d5337e32ac22b9c62e3b
0fe5ef14a1878ac85ae6aa217434fe8bdae66eb4
refs/heads/test
<file_sep>package com.fy.springmiracledemo2.util; /** * @Description : java类作用描述 * @author : fuhw * @CreateDate : 2020/7/7 16:15 * @UpdateUser : fuhw * @UpdateDate : 2020/7/7 16:15 * @UpdateRemark : 修改内容 * @Version : 1.0 */ public class ResultMsg { /** * 响应编码,0是正常,其他异常,详细看msg */ private int statusCode = 0; /** * 响应信息 */ private String message; private Object data; public ResultMsg(){ } ResultMsg(int code, String msg){ this.statusCode =code; this.message = msg; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public static ResultMsg ok(){ return new ResultMsg(0,"success"); } public static ResultMsg error(int code,String msg){ return new ResultMsg(code,msg); } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } <file_sep>/* package com.fy.springmiracledemo.rocket; import org.apache.rocketmq.common.message.MessageExt; import java.util.List; */ /** * @author fuhw * @date 2019/12/10 9:59 * @ClassName MQMsgProcessor * @Description *//* public interface MQMsgProcessor { */ /** * 消息处理<br/> * 如果没有return true ,consumer会重新消费该消息,直到return true<br/> * consumer可能重复消费该消息,请在业务端自己做是否重复调用处理,该接口设计为幂等接口 * * @param topic 消息主题 * @param tag 消息标签 * @param msgs 消息 * @return 2019年12月10日 fuhw *//* MQConsumeResult handle(String topic, String tag, List<MessageExt> msgs); } */ <file_sep>package com.fy.springmiracledemo; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient //@EnableApolloConfig public class SpringMiracleDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringMiracleDemoApplication.class, args); // Config config = ConfigService.getAppConfig(); // String fuhognwei = config.getProperty("fuhongwei", "defaultValue"); // System.out.println(fuhognwei); } } <file_sep>package com.fy.springmiracledemo2.util; import com.alibaba.fastjson.JSONObject; /** * @Description : java类作用描述 * @author : fuhw * @CreateDate : 2020/7/7 16:16 * @UpdateUser : fuhw * @UpdateDate : 2020/7/7 16:16 * @UpdateRemark : 修改内容 * @Version : 1.0 */ public class RequestMsg { /** * 基础授权信息 */ private JSONObject authInfo; /** * 业务数据 */ private JSONObject data; public JSONObject getAuthInfo() { return authInfo; } public void setAuthInfo(JSONObject authInfo) { this.authInfo = authInfo; } public JSONObject getData() { return data; } public void setData(JSONObject data) { this.data = data; } } <file_sep>package com.fy.springmiracledemo2.util; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import java.util.concurrent.TimeUnit; /** * @Description : java类作用描述 * @author : fuhw * @CreateDate : 2020/7/7 16:15 * @UpdateUser : fuhw * @UpdateDate : 2020/7/7 16:15 * @UpdateRemark : 修改内容 * @Version : 1.0 */ public class RedisClient { private StringRedisTemplate redisTemplate; public void setRedisTemplate(StringRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public RedisTemplate<String, String> getRedisTemplate() { return redisTemplate; } public void set(String key, String val) throws Exception { ValueOperations<String, String> ops = redisTemplate.opsForValue(); ops.set(key, val); } public Boolean set(String key, String val, long expireSecond) throws Exception { ValueOperations<String, String> ops = redisTemplate.opsForValue(); ops.set(key, val); return redisTemplate.expire(key, expireSecond, TimeUnit.SECONDS); } public String get(String key) throws Exception { ValueOperations<String, String> ops = redisTemplate.opsForValue(); return ops.get(key); } public Boolean exists(String key) throws Exception { return redisTemplate.hasKey(key); } } <file_sep>package com.fy.springmiracledemo2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringMiracleDemo2Application { public static void main(String[] args) { SpringApplication.run(SpringMiracleDemo2Application.class, args); } }
334d510dc2885a280e2d2e953fe164e7e2e31a63
[ "Java" ]
6
Java
fuyu7811/miracle
f4111765ed09096e39481fbd0d120b4cfb9eb863
dc27e881d0a3cee2db165906b246f89baf044dba
refs/heads/master
<repo_name>k3llymariee/oo-melons<file_sep>/melons.py from random import randint from time import localtime """Classes for melon orders.""" class AbstractMelonOrder(): """An abstract base class that other Melon Order inherit from""" def __init__ (self, species, qty, country_code, order_type, tax): self.species = species self.qty = qty self.shipped = False self.order_type = order_type self.tax = tax self.country_code = country_code def get_base_price(self): random_price = randint(5, 9) base_price = random_price * 1.5 if self.species == 'Christmas' else random_price order_time = localtime() order_hour = order_time.tm_hour order_day = order_time.tm_wday # Rush hour is 8am to 11am, M-F if order_hour in range(8,12) and order_day in range(0,5): base_price += 4 return base_price def get_total(self): """Calculate price, including tax.""" base_price = self.get_base_price() total = (1 + self.tax) * self.qty * base_price if self.country_code != 'USA' and self.qty < 10: total += 3 return total def mark_shipped(self): """Record the fact than an order has been shipped.""" self.shipped = True def get_country_code(self): """Return the country code.""" return self.country_code class DomesticMelonOrder(AbstractMelonOrder): """A melon order within the USA.""" def __init__(self, species, qty): super().__init__(species, qty, country_code='USA', order_type='domestic', tax=0.08) class InternationalMelonOrder(AbstractMelonOrder): """An international (non-US) melon order.""" def __init__(self, species, qty, country_code): super().__init__(species, qty, country_code, order_type='international', tax=0.17) class GovernmentMelonOrder(AbstractMelonOrder): passed_inspection = False def __init__(self, species, qty): super().__init__(species, qty, country_code='USA', order_type='domestic', tax=0.00) def mark_inspection(self, passed): """Record the fact than an order has been inspected.""" self.passed_inspection = passed
485690bb8b3e6e85457b6a15234d2c9fd4cbdd50
[ "Python" ]
1
Python
k3llymariee/oo-melons
c0864005edc34ed5667c6e099438a8c57f335f3c
5e49f97f5e15e9e7f0856b47a73f3168e877cd82
refs/heads/main
<file_sep>#inculde <stdio.h> int main() { printf("helloword\n"); return 0; } <file_sep># mypro 远程仓测试使用 远程仓测试使用
cf73c8c9408ddf82076419cf7806e8b8d0b37b02
[ "Markdown", "C" ]
2
C
cq-RKO/mypro
34b4916022ca9f6edd26d4c2d5a4cdcd7e565135
e90716adee68f081c230faf32dfc4c3bb2b3686f
refs/heads/master
<repo_name>kamaroly/umuzika<file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', function () { return view('layouts.default'); }); $router->get('explore', function() { return view('tracks.item'); }); $router->get('/search',function(){ return view('tracks.search'); }); $router->get('/upload',function(){ return view('files.upload'); }); $router->get('/home',function(){ $songs = App\Models\File::all(); return view('layouts.default3',compact('songs')); }); Route::get('files/get/{filename?}', [ 'as' => 'files.get', 'uses' => 'UploadController@get']); Route::post('upload/music', ['as' => 'upload.music', 'uses' => 'UploadController@upload']); <file_sep>/app/Http/Controllers/UploadController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Http\Requests; use App\Models\File as FileModel; use Illuminate\Contracts\Filesystem\Factory as Storage; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Input; use Illuminate\Http\Response; class UploadController extends Controller { public $file; public $storage; function __construct(FileModel $file, Storage $storage) { $this->file = $file; $this->storage = $storage; } /** * Upload a file to the server * @param Request $request input * @return json */ public function upload() { if(Input::hasFile('file')) { //upload an image to the /img/tmp directory and return the filepath. $file = Input::file('file'); $extension = $file->getClientOriginalExtension(); $filename = time() . $file->getFilename(); $this->storage->disk('local')->put($filename . '.' . $extension, File::get($file)); $entry = $this->file; $entry->mime = $file->getClientMimeType(); $entry->original_filename = $filename; $entry->filename = $filename . '.' . $extension; $entry->save(); return response()->json(array('path'=> route('files.get',['filename' => $entry->filename])), 200); } else { return response()->json(false, 200); } } /** * Get file from the diesk * @param string $filename * @return file */ public function get($filename=null) { $entry = $this->file->where('filename', '=', $filename)->first(); // If we don't have a file, return this dumy path if (is_null($entry)) { return redirect(url('assets/dist/img/no-image.png')); } $file = $this->storage->disk('local')->get($entry->filename); return (new Response($file)) ->header('Content-Type', $entry->mime); } } <file_sep>/public/assets/js/umuzika.page.js $(function() { $("body").on("click", "a[rel='loadpage']", function(e) { // Get the link location that was clicked startLoadingBar(); pageurl = $(this).attr('href'); // Replace the path of the url from index to the path with raw content var custom = pageurl; var custom = custom.replace('index', 'page'); // Request the page $.ajax({url:custom,success: function(data) { // Show the content $('#content').html(data); // Stop the loading bar stopLoadingBar(); // Set the new title tag document.title = $('#page-title').html(); // Scroll the document at the top of the page $(document).scrollTop(0); // Reload functions reload(); }}); // Store the url to the last page accessed if(pageurl != window.location){ window.history.pushState({path:pageurl}, '', pageurl); } return false; }); }); // Override the back button to get the ajax content via the back content */ $(window).bind('popstate', function(ev) { if (navigator.userAgent.match(/(iPad|iPhone|iPod|Android)/g) && !window.history.ready && !ev.originalEvent.state) { return; // Work around for WebKit devices [prevent executing a popstate upon page load (The bug was fixed in Chrome 35+, but not on the mobile browser)] } if (navigator.userAgent.match(/AppleWebKit/) && !navigator.userAgent.match(/Chrome/) && !window.history.ready && !ev.originalEvent.state) { return; // Work around for WebKit devices [prevent executing a popstate upon page load (The bug was fixed in Chrome 35+, but not on the mobile browser)] } startLoadingBar(); // Replace the path of the url from index to the path with raw content var custom = location.href; // Check whether the page contains index.php or not, if it doens't then add one (prevent breaking when loading website without index.php if(custom.indexOf("index.php") == -1) { var custom = location.href + '/index.php'; } var custom = custom.replace('index', 'page'); // Request the page $.ajax({url:custom,success: function(data){ // Show the content $('#content').html(data); // Stop the loading bar stopLoadingBar(); // Set the new title tag document.title = $('#page-title').html(); // Scroll the document at the top of the page $(document).scrollTop(0); // Reload functions reload(); }}); }); $(document).ready(function() { // Set the player volume if(getCookie("volume") == "") { player_volume = 0.80; setCookie("volume", 0.80, "365"); } else { player_volume = getCookie("volume"); } $("#sound-player").jPlayer({ ready: function (event) { $(this).jPlayer("setMedia", { }); }, cssSelectorAncestor: '#sound-container', swfPath: "http://dev.umuzika.com/themes/sound/js", supplied: "mp3", wmode: "window", volume: player_volume, smoothPlayBar: true, keyEnabled: true }); }); function playSong(song, id) { // If the user is on a mobile device, open the track in a new tab rather than playing it on the page /*if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { window.location = 'http://dev.umuzika.com/uploads/tracks/'+song; return false; }*/ // Remove the current-song class (if any) $('.current-song').removeClass('current-song'); // Show the previously hidden Play button (if any) $('.current-play').show(); $('.current-play').removeClass('current-play'); // Remove the active player if exist and set the ghost player $('.current-seek').html($('#sound_ghost_player').html()); // Remove the active player class $('.current-seek').removeClass('current-seek'); // Escape the ID (contains dots) http://api.jquery.com/category/selectors/ var parsedId = song.replace('.', '\\.'); // Add the current song class $('#track'+id).addClass('current-song'); // Add current play class to the Play button and hide it $('#play'+id).addClass('current-play'); $('.current-play').hide(); // Get the current song name and url var trackUrl = $('#song-url'+id).attr('href'); var songName, shortSongName = songName = $('#song-name'+id).html(); if (songName.length > 30) { var shortSongName = $('#song-name'+id).html().substr(0, 30)+'...'; } $('#sw-song-name').html($('<a>', {text: shortSongName, href: trackUrl, title: songName, rel: 'loadpage'})); // Show the time holder when a song starts playing $('.jp-audio .jp-time-holder').show(); // Destroy the player if any is active $("#sound-player").jPlayer("destroy"); // Add the active player to the current song $("#song-controls"+id).html($("#seek-bar-song").html()); // Add the active player class to the current song $("#song-controls"+id).addClass('current-seek'); // Set the play/pause button position (this is needed for mobile view in order for the play/pause button to be at the same height with the initial play button) $('#track'+id+' .jp-play , #track'+id+' .jp-pause').css({ 'margin-top' : '-' + $('.song-top', '#track'+id).outerHeight() + 'px' }); // Get the track extension var ext = getExtension(song); // Determine prev next buttons prevnext(); $("#sound-player").jPlayer({ ready: function (event) { if(ext == 'mp3') { $(this).jPlayer("setMedia", { mp3: 'http://dev.umuzika.com/uploads/tracks/'+song }).jPlayer("play"); } else if(ext == 'm4a') { $(this).jPlayer("setMedia", { m4a: 'http://dev.umuzika.com/uploads/tracks/'+song }).jPlayer("play"); } }, cssSelectorAncestor: '#sound-container', ended: function () { $.ajax({ type: "POST", url: "http://dev.umuzika.com/requests/add_view.php", data: "id="+id, cache: false, success: function(html) { } }); // If repeat is not turned on, move to the next song if($('#repeat-song').html() == 0) { $('.current-seek').html($('#sound_ghost_player').html()); $('.current-play').show(); nextSong(id); } }, /*error: function() { // If the track fails to play for whatever reasons, hide it $('#track'+id).fadeOut(); nextSong(id); },*/ errorAlerts: true, swfPath: "http://dev.umuzika.com/themes/sound/js", supplied: ext, wmode: "window", volume: getCookie("volume"), smoothPlayBar: true, solution: "html, flash", keyEnabled: true }); };
66a4791c6efac07fb61c34aedf03a034da77b52e
[ "JavaScript", "PHP" ]
3
PHP
kamaroly/umuzika
f9d957067c919438d4b55fd91c68f8a8e882167a
bb7f36695e7d6770d8e73d19513cbdc52b7e3ed6
refs/heads/master
<file_sep># Ping pong server Very simple webserver implementation. Right now it only supports GET and POST request methods. Server response body, equals request body. Hence the name ;) Response code is dependent upon the route, for example '/200' will give you a 200 response code. ## Install bundle install ## Run the server ruby server.rb ## How to use Examples are using CURL : 1. `curl --verbose -X POST http://localhost:4567/200 -d '{"a":"b"}'` Will return {"a":"b"} with response code 200 2. `curl --verbose -X GET http://localhost:4567/500` Will return no body with 500 status <file_sep># server.rb require 'sinatra' require 'json' require 'httparty' before do content_type 'application/json' if request.body.size > 0 request.body.rewind @body = JSON.parse request.body.read end end get '/' do 'Welcome to PING-POING server! Get back what you requested!' end post '/' do 'Welcome to PING-POING server! Get back what you requested!' end HTTParty::Response::CODES_TO_OBJ.keys.each do |code| [:post, :get].each do |request_method| send(request_method, "/#{code}") do status code body do @body&.to_json || '' end end end end
4b0d46d864b9fc9acc938d30abeb3bbcc2781900
[ "Markdown", "Ruby" ]
2
Markdown
c0mrade/ping-pong-server
852456dda3127d86d9fe92ce2acf51a76a142b54
c282ebe8529fcd5c6ad60e72749fd0b54e72b380
refs/heads/master
<repo_name>vikasyadav18/NodeJs<file_sep>/index.js const fs=require("fs"); fs.writeFileSync("read.txt","hello friends"); fs.appendFileSync("read.txt","hello friend welcome"); const buf_data=fs.readFileSync("read.txt"); console.log(buf_data.toString()); // asynchronously creating folder and file-------------- // fs.mkdirSync("nfolder"); // fs.writeFile("nfolder/newfile.txt","hey brother",(err)=>{ // console.log("file created"); // }); fs.renameSync("updatedread.txt","read.txt");
dd8014fa1aa9d1560edb46483d064f464083ffbd
[ "JavaScript" ]
1
JavaScript
vikasyadav18/NodeJs
51e54b95399455ba9b87a0b8ff3bfced10ee532e
e756b6d8eee1ca8f8177d5a8756d1e0ab9232ad6
refs/heads/master
<file_sep>const students=[ {id: 12, name:'Manna'}, {id: 13, name:'banna'}, {id: 14, name:'kanna'}, {id: 15, name:'cjanna'}, ] const names = students.map(s => s.name); console.log(names)<file_sep>const age = 5; if(age>0){ console.log("condition is true") } else{ console.log("false") }
10894ae7c86d0808d64c7301228fb8ca0b571fa5
[ "JavaScript" ]
2
JavaScript
zabir1998/advance-js
350915b9709cce8109d29c7282f09fc61b3fb0e5
8bdc06af225228668ece0a6ce53b5e475c82e302
refs/heads/master
<repo_name>laofaqin/youduAdmin<file_sep>/precache-manifest.eddb78b3b49a741d82f046c7f34bb007.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "80de2b8b7b010f35022d8e41a9b034c4", "url": "./index.html" }, { "revision": "137137586eb44ee0876b", "url": "./static/css/2.f13a5d53.chunk.css" }, { "revision": "817428828f6686d49982", "url": "./static/css/main.0ab03794.chunk.css" }, { "revision": "137137586eb44ee0876b", "url": "./static/js/2.c5637ab0.chunk.js" }, { "revision": "817428828f6686d49982", "url": "./static/js/main.0b6749c9.chunk.js" }, { "revision": "fdbea2df0d7dd6bcae6d", "url": "./static/js/runtime~main.5545c9d3.js" } ]);
ac80b8b41303145ea39c671d23cb3ecb7de6ff1a
[ "JavaScript" ]
1
JavaScript
laofaqin/youduAdmin
0a521b343394a9bd0704f0efa6c6bca0fa4ef20d
fcf036e5cf56741ae57c91d8c6fcfcef033c5ada
refs/heads/master
<repo_name>arusdef/HFCrypto<file_sep>/data/main.py import time import returnOrderBook import returnTicker import returnLoanOrders import return24hVolume import returnCurrencies import githubParser while(True): actualTime = time.time() data = [] data.append(time.time()) with open('data.txt', 'a') as outfile: outfile.write(str(actualTime)) for i in returnOrderBook.returnResult(): outfile.write(str(i) + ',') for i in returnCurrencies.returnResult(): outfile.write(str(i) + ',') for i in return24hVolume.returnResult(): outfile.write(str(i) + ',') for i in returnLoanOrders.returnResult(): outfile.write(str(i) + ',') for i in returnTicker.returnResult(): outfile.write(str(i) + ',') for i in githubParser.returnResult(): outfile.write(str(i) + ',') outfile.write('\n') time.sleep(300 - (time.time() - actualTime))<file_sep>/data/githubParser.py import requests import sys import time from bs4 import BeautifulSoup url = 'https://github.com/gridcoin/Gridcoin-Research' response = requests.get(url) html = response.content soup = BeautifulSoup(html, 'html.parser') output = soup.find("span", {"class": "text-emphasized"}).get_text(strip=True) # sys.stdout = data.txt # print output.prettify() # time.sleep(300) def returnResult(): return(output)
ec239b3c3ac4ccb1c5abaaaa3638413a35dac22f
[ "Python" ]
2
Python
arusdef/HFCrypto
59fe3a5a065e3addf56df8b9bf7a7ea69413eec1
e3158ee7d1ca626ff7d290557c3cf86e9319c2af
refs/heads/master
<file_sep>$(function(){ $('.Toggle').click(function() {   $(this).toggleClass('active'); $('.btns').toggleClass('appear')  if ($(this).hasClass('active')) {   $('.NavMenu').addClass('active');   } else {   $('.NavMenu').removeClass('active');  }  }); });
eac7ce715748fa73c529b3f4099660075755248a
[ "JavaScript" ]
1
JavaScript
kyotocoaching/question
cf648a8c1a011799e9949c807dfb557bea3412fb
6a335cf4cfbc2b248ab0541e683c9756df5529dd
refs/heads/master
<file_sep>/** * Given a class of Box, which has attribute color which specifies the color * of the box, including red (0), white (1), black (2); Given an array of * box and sort the boxes by all red boxes first, then white, then black */ public class SortBox{ private class Box{ int color; public Box(int c){ this.color = c; } } public void sort(Box[] boxes){ if(boxes == null || 0 == boxes.length){ return; } int[] count = new int[3]; for(int i = 0; i < boxes.length; i++){ count[boxes[i].color]++; } count[1] += count[0]; count[2] += count[1]; Box[] newBoxes = new Box[boxes.length]; for(int i = 0; i < boxes.length; i++){ newBoxes[count[boxes[i].color]--] = boxes[i]; } boxes = newBoxes; } } <file_sep>import java.util.Arrays; public class MaxHeap<T extends Comparable<T>> extends Heap<T>{ @Override public void heapify(int i){ int left = left(i); int right = right(i); if(left < heap.size() && get(left).compareTo(get(i)) > 0){ swap(left, i); heapify(left); }else if(right < heap.size() && get(right).compareTo(get(i)) > 0){ swap(right, i); heapify(right); } } @Override public void increaseKey(int i, T key){ while(i > 0 && key.compareTo(get(parent(i))) > 0){ swap(i, parent(i)); i = parent(i); } } public static void main(String[] args){ MaxHeap<Integer> maxHeap = new MaxHeap<Integer>(); maxHeap.push(3); maxHeap.push(5); maxHeap.push(6); maxHeap.push(2); maxHeap.push(8); maxHeap.push(7); maxHeap.push(4); maxHeap.push(3); int size = maxHeap.size(); for(int i = 0; i < size; i++){ System.out.println(maxHeap.get(i)); } maxHeap.pop(); size = maxHeap.size(); for(int i = 0; i < size; i++){ System.out.println(maxHeap.get(i)); } } } <file_sep>import java.util.Set; import java.util.HashSet; import java.util.BinarySearchTree; public class Duplicate{ private class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int v){ this.val = v; } boolean static addAndCheck(TreeNode root, TreeNode node, int range){ if(node == null){ return true; } if(root == null){ root = node; return true; } int diff = Math.abs(node.val - this.val); if(diff < range){ return false; } if(node.val < root.val){ return addAndCheck(root.left, node, range); }else{ return addAndCheck(root.right, node, range); } } } public static boolean checkDuplicate(int[] input){ Set set = new HashSet<Integer>(); for(int one : input){ if(set.contains(one)){ return true; }else{ set.add(one); } } return false; } public static boolean checkDuplicateWithKIndices(int[] input, int k){ Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < input.length; i++){ if(i >= k){ set.remove(input[i - k]); } if(set.contains(input[i])){ return true; }else{ set.add(input[i]); } } return false; } public static boolean checkDupWithKIndLRange(int[] input, int k, int l){ Set<Integer> set = new HashSet<Integer>(); TreeNode root; for(int i = 0; i < input.length; i++){ if(root == null){ root = new TreeNode(input[i]); } } } } <file_sep>package ctci.chapter14; public class CircularArrayIterator<T> implements Iterator<T>{ private CircularArray array; private int index; public CircularArrayIterator(CircularArray array){ this.array = array; this.index = array.getHead(); } @Override public boolean hasNext(){ int indexBeforeHead = array.getHead() == 0 ? array.length - 1 : array.getHead() - 1; return index != indexBeforeHead; } @Override public T next(){ if(hasNext){ return array[index++]; }else{ return null; } } @Override public void remove(){ throw new UnsupportedOperationException(); } }<file_sep> import java.util.List; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Comparator; /** * Given an array and an integer k, find the maximum for each and * every contiguous subarray of size k * */ public class MaximumOfK{ static List<Integer> maximumOfK(int[] array, int k){ List<Integer> ret = new ArrayList<Integer>(); Comparator<Integer> comparator = new Comparator<Integer>(){ public int compare(Integer i1, Integer i2){ return i2 - i1; } }; PriorityQueue<Integer> heap = new PriorityQueue<Integer>(k, comparator); for(int i = 0; i < array.length; i++){ if(i < k){ heap.offer(array[i]); }else{ ret.add(heap.peek()); heap.remove(array[i - k]); heap.offer(array[i]); } } ret.add(heap.peek()); return ret; } //more efficient way use a double-ended queue static List<Integer> maximumDequeue(int[] array, int k){ } public static void main(String[] args){ int[] a = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; List<Integer> ret1 = maximumOfK(a, 3); for(int i : ret1){ System.out.print( i + " "); } System.out.println(); int[] b = new int[]{9, 2, 3, 8, 5, 3, 7, 3, 9}; ret1 = maximumOfK(b, 2); for(int i : ret1){ System.out.print( i + " "); } System.out.println(); } } <file_sep>package ctci.chapter09; import java.util.Set; import java.util.HashSet; /* * Implement an algorithm to print all valid(ie. properly opened and closed) * combinations of n-pairs of parentheses */ public class Parentheses{ public Set<String> allParentheses(int num){ Set<String> results = new HashSet<String>(); if(num == 0){ results.add(""); } // remove the situation which could get from the following condition /*else if(num == 1){ results.add("()"); }*/ else{ Set<String> former = allParentheses(num - 1); for(String single:former){ for(int i = 0; i < single.length(); i++){ if(single.charAt(i) == '('){ results.add(parentheseFromIndex(single, i)); } } results.add("()" + single); } } return results; } private String parentheseFromIndex(String str, int index){ StringBuilder sb = new StringBuilder(); sb.append(str.substring(0, index + 1)); sb.append("()"); sb.append(str.substring(index + 1)); return sb.toString(); } public static void main(String[] args){ Parentheses pr = new Parentheses(); Set<String> results = pr.allParentheses(2); for(String result:results){ System.out.println(result); } } }<file_sep>import java.io.*; /*Babai is standing in the top left cell (1,1) of an N*M table. The table has N rows and M columns. Initially he is facing its right cell. He moves in the table in the following manner: He moves one step forward He turns to its right If moving forward makes him exit the boundaries of the table, or causes him to reach a visited cell, he turns to its right. He moves around the table and visits as many cells as he can. Your task is to find out the number of cells that he visits before he stops. Here's a sample of Babai's steps on a 9x9 grid. The value at each cell denotes the step number. 1 2 55 54 51 50 47 46 45 4 3 56 53 52 49 48 43 44 5 6 57 58 79 78 77 42 41 8 7 60 59 80 75 76 39 40 9 10 61 62 81 74 73 38 37 12 11 64 63 68 69 72 35 36 13 14 65 66 67 70 71 34 33 16 15 20 21 24 25 28 29 32 17 18 19 22 23 26 27 30 31 Input: The input contains two integers N and M separated by a line. N and M are between 1 and 100. Output: Print a single integer which is the answer to the test-case Sample input #00: 3 3 Sample output #00: 9 Sample input #01: 7 4 Sample output #01: 18 */ public class SquareVisitedCells{ public static int steps(int n, int m){ if(m == 0 || n == 0){ return 0; } if(m == 1 && n == 1){ return 1; } if(n % 2 == 1){ return 2 * n + steps(m - 2, n); }else{ return 2 * n; } } public static void main(String args[] ) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int m = Integer.parseInt(br.readLine()); System.out.println(steps(n, m)); } }<file_sep>/** * Suppose that you have a dictionary of words and a collection of letters * Find all of the longest words in the dictionary that you can form using letters in your collection: */ public class LongestWordInDic{ } <file_sep>import java.util.Arrays; public class BubbleSort{ private static int[] array; public static void bubbleSort(){ int len = array.length; for(int i = len - 1; i >= 0; i--){ for(int j = 0; j < i; j++){ if(array[j] > array[j + 1]){ swap(j, j + 1); } } } } public static void swap(int i, int j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void main(String[] args){ array = new int[]{2,4,7,3,1,7,4,5,0,6}; bubbleSort(); System.out.println(Arrays.toString(array)); } } <file_sep>/** * Triangle * By starting at the top of the triangle and moving to adjacent numbers on the row below, * the maximum total from top to bottom is 27 * 5 * 9 6 * 4 6 8 * 0 7 1 5 * resutl 5 + 9 + 6 + 7 = 27 * Write a program in a language of your choice to find the maximum total from top to bottom * */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; import java.util.Arrays; public class Triangle{ private static int line = 100; private static int[][] triangle = new int[line][line]; private static int[][] result = new int[line][line]; private static void readFile(){ BufferedReader br = null; String line; Scanner sc = null; try{ br = new BufferedReader(new FileReader("triangle.txt")); int lineNo = 0; while((line = br.readLine()) != null){ sc = new Scanner(line); int index = 0; while(sc.hasNextInt()){ triangle[lineNo][index++] = sc.nextInt(); } lineNo++; } }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(br != null){ br.close(); } }catch(IOException ex){ ex.printStackTrace(); } } } private static int maxSum(){ result[0][0] = triangle[0][0]; int max = Integer.MIN_VALUE; for(int i = 1; i < line; i++){ result[i][0] = result[i - 1][0] + triangle[i][0]; for(int j = 1; j <= i; j++){ result[i][j] = Math.max(result[i - 1][j - 1], result[i - 1][j]) + triangle[i][j]; if(i == line - 1){ max = Math.max(max, result[i][j]); } } } return max; } public static void main(String[] args){ readFile(); //System.out.println(Arrays.deepToString(triangle)); System.out.println("___________________"); int max = maxSum(); System.out.println(max); } } <file_sep>#include<stdio.h> class Wrapper{ public: Wrapper(int i = 0){ dig = i; } int & getDig(){ return dig; } private: int dig; }; void mul(int & a ){ a = 2 * a; } int main(){ Wrapper w(1); mul(w.getDig()); printf("%d\n", w.getDig()); return 0; } <file_sep> import java.util.Random; public class ShortestPath{ boolean[][] matrix; Random random; public ShortestPath(int len, int wid){ this.matrix = new boolean[len][wid]; this.random = new Random(); } public void generateMatrix(){ for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[0].length; j++){ int rand = random.nextInt(5); if(rand > 0){ matrix[i][j] = true; }else{ matrix[i][j] = false; } } } } /** * This solution suppose can only move left or down */ public int shortestPath(int x, int y){ if(x >= matrix[0].length || x >= matrix.length){ throw new IllegalArgumentException(); } int[][] dp = new int[y][x]; for(int i = 0; i < y; i++){ for(int j = 0; j < x; j++){ if(!matrix[i][j]){ dp[i][j] = 0; continue; } if(i == 0 && j == 0){ dp[i][j] = 0; }else if(i == 0){ dp[i][j] = matrix[i][j - 1] ? dp[i][j - 1] + 1 : 0; }else if(j == 0){ dp[i][j] = matrix[i - 1][j] ? dp[i - 1][j] + 1 : 0; }else{ int temp = Integer.MAX_VALUE; if(matrix[i - 1][j]){ temp = Math.min(temp, dp[i - 1][j]); } if(matrix[i][j - 1]){ temp = Math.min(temp, dp[i][j - 1]); } if(temp == 0){ dp[i][j] = 0; }else{ dp[i][j] = temp + 1; } } } } return dp[y - 1][x - 1]; } public static void main(String[] args){ ShortestPath sp = new ShortestPath(5, 6); sp.generateMatrix(); for(int i = 0; i < 5; i++){ for(int j = 0; j < 6; j++){ System.out.print(sp.matrix[i][j] + " "); } System.out.println(); } System.out.println("Path to 3, 3 = " + sp.shortestPath(3, 3)); } } <file_sep>import java.util.ArrayList; import java.util.List; public abstract class Heap<T extends Comparable<? super T>>{ protected List<T> heap; public Heap(){ heap = new ArrayList<T>(); } public void push(T item){ heap.add(item); increaseKey(heap.size() - 1, item); } public T pop(){ T top = getFirst(); swap(0, heap.size() - 1); heap.remove(heap.size() - 1); heapify(0); return top; } public T getFirst(){ return heap.get(0); } public T get(int index){ return heap.get(index); } public int size(){ return heap.size(); } protected int parent(int i){ if(i == 0){ throw new IllegalArgumentException("can not find the parent of the root"); } return (i - 1) / 2; } protected int left(int i){ return 2 * i + 1; } protected int right(int i){ return 2 * i + 2; } protected void swap(int i, int j){ T itemAtI = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, itemAtI); } public void buildHeap(){ int size = heap.size(); int middle = size / 2 - 1; for(int i = middle; i >= 0; i--){ heapify(i); } } public abstract void heapify(int i); public abstract void increaseKey(int i, T key); } <file_sep> import java.util.Queue; import java.util.LinkedList; /** * 数据结构设计题,给你一个黑匣子,匣子里面有很多sorted的数,支持get()和next()函数,类似于pop()跟peek()的区别, * 都是取得最小数,不过一个删数一个不删数,叫你设计一个数据结构,除了这两个函数之外还要支持add(int)这个函数,你不能对黑匣子进行修改 */ public class BoxImpl implements Box{ private Box box; private int temp; private boolean isTempNull; public BoxImpl(Box box){ this.box = box; this.temp = 0; this.isTempNull = true; } @Override public int get(){ if(isTempNull){ return box.get(); }else{ int curr = box.get(); if(curr > temp){ return temp; }else{ return curr; } } } @Override public int next(){ if(isTempNull){ return box.next(); }else{ int curr = box.get(); if(curr > temp){ int ret = temp; temp = 0; isTempNull = true; return ret; }else{ return box.next(); } } } void add(int x){ if(isTempNull){ isTempNull = false; temp = box.next() + temp + x; }else{ temp += x; } } public static void main(String[] args){ final Queue<Integer> queue = new LinkedList<Integer>(); queue.add(1); queue.add(2); queue.add(3); queue.add(4); queue.add(5); queue.add(7); Box box = new Box(){ public int get(){ return queue.peek(); } public int next(){ return queue.poll(); } }; BoxImpl addBox = new BoxImpl(box); System.out.println(addBox.get()); System.out.println(addBox.next()); addBox.add(4); System.out.println(addBox.next()); System.out.println(addBox.next()); System.out.println(addBox.next()); System.out.println(addBox.next()); System.out.println(addBox.next()); } }<file_sep>import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; public class SquareGoodNode { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ArrayList<Node> nodeList = new ArrayList<Node>(); int totalNumber = Integer.parseInt(br.readLine()); for(int i=0; i<totalNumber; i++){ nodeList.add(new Node()); } for(int i=0; i<totalNumber; i++){ nodeList.get(i).next = nodeList.get(Integer.parseInt(br.readLine())-1); } System.out.println(minChangeToGood(nodeList)); } public static int minChangeToGood(ArrayList<Node> list){ HashSet<Node> set = new HashSet<Node>(); Node node1 = list.get(0); int count = 0; for(int i=0; i<list.size(); i++){ Node node = list.get(i); if(set.contains(node)){ continue; }else{ HashSet<Node> subset = new HashSet<Node>(); while(!subset.contains(node)){ subset.add(node); node = node.next; } if(!subset.contains(node1)) count++; set.addAll(subset); } } return count; } } <file_sep>public class List<T>{ public ListNode<T> reverseRecursive(ListNode<T> node){ if(node == null){ return null; } if(node.next == null){ return node; } ListNode<T> second = node.next; node.next = null; ListNode<T> after = reverseRecursive(second); second.next = node; return after; } public ListNode<T> reverseIterative(ListNode<T> node){ if(node == null){ return null; } ListNode<T> prev = null; ListNode<T> curr = node; ListNode<T> next = null; while(curr != null){ next = curr.next; curr.next = prev; prev = curr; curr = next; } return prev; } private void print(ListNode<T> node){ ListNode<T> tmp = node; while(tmp != null){ System.out.println(tmp.value); tmp = tmp.next; } } public static void main(String[] args){ ListNode<Integer> node = new ListNode<Integer>(1); node.next = new ListNode<Integer>(2); node.next.next = new ListNode<Integer>(3); List<Integer> list = new List<Integer>(); ListNode<Integer> after = list.reverseRecursive(node); list.print(after); ListNode<Integer> another = list.reverseIterative(after); list.print(another); } } <file_sep>package edu.nyu.zhaohui.amazon; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Windows { public static List<Integer> calculateWindowsSums(List<Integer> list, int windowSize){ if(null == list){ throw new IllegalArgumentException("list should not be null"); } List<Integer> ret = new ArrayList<Integer>(); if(list.size() == 0 || windowSize <= 0){ return ret; } int total = 0; for(int i = 0; i < list.size(); i++){ if(i < windowSize){ total += list.get(i); }else{ ret.add(total); total -= list.get(i - windowSize); total += list.get(i); } } ret.add(total); return ret; } public static void main(String[] args){ Integer[] one = new Integer[]{4, 2, 73, 11, -5}; List<Integer> input = new ArrayList<Integer>(Arrays.asList(one)); List<Integer> ret = calculateWindowsSums(input, 2); List<Integer> ret2 = calculateWindowsSums(input, 3); for(Integer i : ret){ System.out.print(i + " "); } for(Integer i : ret2){ System.out.print(i + " "); } } } <file_sep> public class WiredOrderPrint{ public static void print(int[] array){ int len = array.length; boolean smallThanLater = true; for(int i = 1; i < len; i++){ if(smallThanLater){ if(array[i - 1] > array[i]){ change(array, i - 1, i); } }else{ if(array[i - 1] < array[i]){ change(array, i - 1, i); } } smallThanLater = smallThanLater ? false : true; } for(int i = 0; i < len; i++){ System.out.print(array[i] + " "); } System.out.println(); } private static void change(int[] array, int x, int y){ int temp = array[x]; array[x] = array[y]; array[y] = temp; } public static void main(String[] args){ int[] a = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; print(a); int[] b = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1}; print(b); int[] c = new int[]{5, 2, 8, 4, 6, 2, 9, 3, 5}; print(c); int[] d = new int[]{ 3, 6, 3, 1, 9, 6, 8, 2, 5, 6, 4, 2, 1}; print(d); } } <file_sep>package edu.nyu.zhaohui.amazon; import java.util.HashMap; import java.util.Map; public class MostFrequentNumber { public static int mostFrequent(int[] array){ if(null == array || 0 == array.length){ throw new IllegalArgumentException(); } int ret = 0; int freq = Integer.MIN_VALUE; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int num : array){ if(!map.containsKey(num)){ map.put(num, 1); }else{ int oldFreq = map.get(num); map.put(num, oldFreq + 1); if(oldFreq + 1 > freq){ freq = oldFreq + 1; ret = num; } } } return ret; } public static void main(String[] args){ int[] array = new int[]{1, 3, -4, 0, 9, 0, -4, 3, -4, 10000, -398}; System.out.println(mostFrequent(array)); } } <file_sep>package ctci.chapter08.4thedition; /** * Write a method to generate the nth Fibonacci number * Both Recursive and Iterative way used */ public class Fibonacci{ // Recursive public static int fibonacciRecursive(int n){ if(n < 0){ throw new IllegalArgumentException("Argument cannot be negative: " + n); } if(n == 0){ return 0; } if(n == 1){ return 1; } return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); } // First Attempt: This method has a bug, will outOfIndex if n = 0; public static int fibonacciIterative_old(int n){ int[] result = new int[n]; for(int i = 0; i < n; i++){ if(i == 0 || i == 1){ result[i] = 1; }else{ result[i] = result[i - 1] + result[i - 2]; } } return result[n - 1]; } // THis method is not an effient, since //we do not need to use array to save all the data public static int fibonacciIterative_again(int n){ if(n < 0){ throw new IllegalArgumentException("Argument cannot be negative: " + n); } if(n == 0){ return 0; } int[] resultSet = new int[n]; for(int i = 0; i < n; i++){ if(i == 0 || i == 1){ resultSet[i] = 1; }else{ resultSet[i] = resultSet[i - 1] + resultSet[i - 2]; } } return resultSet[n - 1]; } // Iterative public static int fibonacciIterative(int n){ if(n < 0){ throw new IllegalArgumentException("Argument cannot be negative: " + n); } if(n == 0){ return 0; } int a = 1, b = 1; int c = 0; for(int i = 3; i <=n; i++){ c = a + b; a = b; b = c; } return b; } public static void main(String[] args){ System.out.println(fibonacciRecursive(0)); //System.out.println(fibonacciIterative_old(0)); System.out.println(fibonacciIterative_again(0)); System.out.println(fibonacciIterative(0)); } }<file_sep>package edu.nyu.zhaohui.amazon; public class NotifyCustomers { public static ListNode<Integer> notify(ListNode<Integer> head, int k){ ListNode<Integer> fast = head; while(k > 0){ fast = fast.next; k--; } ListNode<Integer> slow = head; while(fast != null){ fast = fast.next; slow = slow.next; } return slow; } public static void main(String[] args){ ListNode<Integer> node1 = new ListNode<Integer>(1); ListNode<Integer> node2 = new ListNode<Integer>(8); ListNode<Integer> node3 = new ListNode<Integer>(4); ListNode<Integer> node4 = new ListNode<Integer>(2); ListNode<Integer> node5 = new ListNode<Integer>(7); ListNode<Integer> node6 = new ListNode<Integer>(13); ListNode<Integer> node7 = new ListNode<Integer>(3); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6; node6.next = node7; System.out.println(notify(node1, 2).val); } } <file_sep>package edu.nyu.zhaohui.amazon; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Intersection { public List<Integer> intersec(List<Integer> list1, List<Integer> list2){ if(list1 == null || list2 == null){ return null; } List<Integer> ret = new ArrayList<Integer>(); if(list1.size() == 0 || list2.size() == 0){ return ret; } Map<Integer, Boolean> map = new HashMap<Integer, Boolean>(); for(int i : list1){ map.put(i, false); } for(int j : list2){ if(map.containsKey(j)){ map.put(j, true); } } for(int one : map.keySet()){ if(map.get(one)){ ret.add(one); } } return ret; } public static void main(String[] args){ Integer[] array1 = new Integer[]{4, 2, 73, 11, 9}; Integer[] array2 = new Integer[]{-5, 73, -1, 9, 9, 4, 7}; Intersection intersection = new Intersection(); List<Integer> ret = intersection.intersec(Arrays.asList(array1), Arrays.asList(array2)); System.out.println(ret.toString()); } } <file_sep>package com.ask.interview.second; /** * This class can be used to build of a graph * and perform some basic operations on it. * * The graph is constructed by calling the * addEdge or addEdges methods. The Strings * to define an edge will contain 2 characters, * each character being the label for the * node. After these 2 characters, there will * be an integer value that represents the * distance or length on the edge between * the nodes. The edges are directional. In * other words "AB" implies that you can * traverse from A to B but not from B to A. * You would have to have anther edge added * "BA" in order to go the other direction. * * There are several methods available to * get details about the graph. * */ public class Graph { /** * The format of the string is * 1st Character = starting node name * 2nd Character = ending node name * Integer = edge length * * For example, the String "AB5" should * create 2 nodes, each labeled "A" and * "B" respectively with a distance between * them of 5 units. */ public void addEdge(String edge) { throw new RuntimeException("Implement Me!!!"); } /** * Just like addEdge() but it does * more than one at a time. */ public void addEdges(String... edges) { throw new RuntimeException("Implement Me!!!"); } /** * Each character in the String represents an edge * traversal over which the sum of the edge lengths * is to be accumulated. * * The route is defined by providing a sequence of * characters that represent the nodes of the path. * * For example, if a graph had been created as * "AB5", "BC2" then the return value for various * paths would be: * * "AB" --> 5 * "BC" --> 2 * "ABC" --> 7 * "ABCB" --> 9 */ public int calculateRouteDistance(String routeToTake) { throw new RuntimeException("Implement Me!!!"); } /** * The format of the fromTo input string is * 1st Character = starting node name * 2nd Character = ending node name * * Any single shortest path from the starting node * name to the ending node dame. If the graph had * been created as "AB5", "BC2", "AD2", "DC5", and * this method was called with "AC" then both paths * "ABC7" and "ADC7" are of length 7 and either * would be a valid return value. * * The return value should be the node names followed * by the length of the path. */ public String calculateShortestRoute(String fromTo) { throw new RuntimeException("Implement Me!!!"); }; /** * The format of the string is * 1st Character = starting node name * 2nd Character = ending node name * * As each edge is traversed, the length of the edge * should be accumulated to create a total distance * for that route. * * All unique paths that go from the starting node to the * ending node which are shorter than the maximumDistance * should be counted. * * For example, if the graph is constructed as "AB5", "BC2", * "CD3", "BD6", "AC1", "AD9", then some valid paths for "AD" * are "ABCD10", "ABD11", "ACD4", "AD9". * * If the maximumDistance is set above 11, all 4 should be * returned. If set below 4, then nothing should be returned. * If set to 4, then "ACD4" should be returned, and so on. */ public String[] getPaths(String fromTo, int maximumDistance) { throw new RuntimeException("Implement Me!!!"); } } <file_sep> public class Shouda{ } <file_sep>package edu.nyu.zhaohui.amazon; public class FindLoop<T> { public boolean hasLoop(ListNode<T> head){ if(head == null){ return false; } ListNode<T> fast = head; ListNode<T> slow = head; while(fast != null && fast.next == null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ return true; } } return false; } } <file_sep>package edu.nyu.zhaohui.amazon; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; public class KClosest { private final static int K = 5; public List<Point> findKClosest(List<Point> points){ PriorityQueue<Point> heap = new PriorityQueue<Point>(); for(Point point : points){ if(heap.size() < K){ heap.add(point); }else{ if(heap.peek().compareTo(point) < 0){ heap.poll(); heap.offer(point); } } } return new ArrayList<Point>(heap); } } <file_sep> /** * Given a set of numbers, find the length of the longest arithmetic progression(LAP) in it * 1) all the numbers in LAP should be continuous * Example: * {1, 2, 3, 5, 4} * output = 3 * The lap is {1, 2, 3} * * 2) what if we do not care about the position * Example: * {1, 7, 10, 15, 27, 29} * output = 3 * The longest arithmetic progression is {1, 15, 29} * */ public class LongestArithmeticProgression{ public static int getLengthLAPContinues(int[] array){ int len = array.length; if(null == array || 0 == len){ return 0; } if(1 == len){ return 1; } int ret = 2; int maxSofar = 2; int diff = 0; for(int i = 1; i < len; i++){ int currDiff = array[i] - array[i - 1]; if(currDiff == diff){ maxSofar++; }else{ ret = Math.max(ret, maxSofar); diff = currDiff; maxSofar = 2; } } ret = Math.max(ret, maxSofar); return ret; } public static int getLengthLAP(int[] array){ } public static void main(String[] args){ int[] array = new int[]{1, 2, 4, 6, 7, 8, 10}; System.out.println(getLengthLAPContinues(array)); } } <file_sep> /** * * 给一个text file, 里面是按行分割的各种单词,让找到频率第k大的那个单词。尽可能的优化 */ public class TextWordCount{ } <file_sep>public interface Box{ int get(); int next(); }<file_sep>code interview ============= Prepare for the code interview, including my solutions to crack the code interview and Leetcode <file_sep>import java.util.Arrays; public class InsertSort{ private static int[] array; public static void insertSort(){ for(int i = 1; i < array.length; i++){ for(int j = 0; j < i; j++){ if(array[j] > array[i]){ int temp = array[i]; for(int k = i; k > j; k--){ array[k] = array[k - 1]; } array[j] = temp; break; } } } } public static void insertSortSwap(){ for(int i = 1; i < array.length; i++){ for(int j = i; j > 0; j--){ if(array[j] < array[j - 1]){ swap(j, j - 1); }else{ break; } } } } public static void swap(int i, int j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void main(String[] args){ array = new int[]{2,4,7,3,1,7,4,5,0,6}; insertSortSwap(); System.out.println(Arrays.toString(array)); } } <file_sep>package ctci.chapter09; import java.util.ArrayList; import java.util.Arrays; /** * Write an algorithm to print all ways of arranging eight queens * on a 8, * chess board */ public class EightQueens{ private static final int GRID_SIZE = 8; public static void placeQueens(int row, Integer[] colums, ArrayList<Integer[]> results){ if(row == GRID_SIZE){ results.add(colums.clone()); }else{ for(int colum = 0; colum < GRID_SIZE; colum++){ if(isValid(colum, row, colums)){ colums[row] = colum; placeQueens(row + 1, colums, results); } } } } public static boolean isValid(int colum, int row, Integer[] colums){ for(int i = 0; i < row; i++){ if(colums[i] == colum){ return false; } int columDiff = Math.abs(colums[i] - colum); int rowDiff = Math.abs(i - row); if(columDiff == rowDiff){ return false; } } return true; } public static ArrayList<Integer[]> getEightQueensPosition(){ ArrayList<Integer[]> results = new ArrayList<Integer[]>(); Integer[] test = new Integer[GRID_SIZE]; System.out.println("TEST" + test[0]); placeQueens(0, test, results); return results; } public static void main(String[] args){ ArrayList<Integer[]> results = getEightQueensPosition(); int count = 0; for(Integer[] result:results){ System.out.println(Arrays.toString(result)); count++; } System.out.println(count); } }<file_sep>import java.io.FileReader; import java.io.IOException; import java.io.BufferedReader; import java.util.HashMap; /** * This class simulates the process of Cosine Similarity Score of two queries * Input file as parameters of the class, please run this program use: * java CosineSimilarityScore file1 file2 * I assume the cosine similarity score calculated like the following: * If there is multiple scores under one ID, just add them together; * If there is ID1 in query1 but not in query2, use value 0 instead; * Then calculate the score using Euclidean dot product formula listed in Wikipedia */ public class CosineSimilarityScore{ private static class Query{ public String name; public HashMap<String, Integer> scores; public Query(String n, HashMap<String, Integer> s){ name = n; scores = s; } } private static Query query1; private static Query query2; private static String readFile(String inputName) throws IOException { BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { String line; br = new BufferedReader(new FileReader(inputName)); while((line = br.readLine()) != null){ sb.append(line); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (br != null) { br.close(); } } return sb.toString(); } private static Query parseString(String str){ String[] temp = str.split("\\t"); String name = temp[0]; String other = temp[1]; String[] values = other.split(","); int num = Integer.parseInt(values[0]); HashMap<String, Integer> scores = new HashMap<String, Integer>(); for(int i = 0; i < num; i++){ String key = values[2 * i + 1]; int score = Integer.parseInt(values[2 * i + 2]); if(scores.containsKey(key)){ scores.put(key, scores.get(key) + score); }else{ scores.put(key, score); } } return new Query(name, scores); } private static double calCosine(){ int dotMul = 0; int a = 0; int b = 0; for(String k : query1.scores.keySet()){ if(query2.scores.containsKey(k)){ dotMul += query1.scores.get(k) * query2.scores.get(k); a += query1.scores.get(k) * query1.scores.get(k); b += query2.scores.get(k) * query2.scores.get(k); query2.scores.remove(k); }else{ a += query1.scores.get(k) * query1.scores.get(k); } } for(String k: query2.scores.keySet()){ b += query2.scores.get(k) * query2.scores.get(k); } double ret = (double)dotMul / (Math.sqrt(a) * Math.sqrt(b)); // System.out.println(ret); return ret; } public static void main(String[] args) throws IOException{ String str1 = readFile(args[0]); String str2 = readFile(args[1]); query1 = parseString(str1); query2 = parseString(str2); double cosine = calCosine(); System.out.println(query1.name + "\t" + query2.name + "\t" + cosine); } }<file_sep>#include<stdio.h> char * strcpy(char * dst, const char * src){ char * ptr; ptr = dst; while((*ptr++ = *src++) != '\0') ; return dst; } char * strcpy2(char dst[], const char source[]){ int i = 0; while(source[i] != '\0'){ dst[i] = source[i]; i++; } dst[i] = '\0'; return dst; } int main(){ char str[] = "october"; char dst[40]; char dst2[40]; strcpy(dst, str); strcpy2(dst2, str); printf("dst: %s dst2: %s\n", dst, dst2); return 0; } <file_sep>package ctci.chapter09; import java.util.ArrayList; /** * Write a method to return all subsets of a set */ public class SubSet{ // Recursion method public ArrayList<ArrayList<Integer>> getAllSubSetsRecursion(ArrayList<Integer> set){ int size = set.size(); return getAllSubSetsRecursion(set, size - 1); } public ArrayList<ArrayList<Integer>> getAllSubSetsRecursion(ArrayList<Integer> set, int index){ ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); if(index <= 0){ results.add(new ArrayList<Integer>()); }else{ ArrayList<ArrayList<Integer>> tmp = getAllSubSetsRecursion(set, index - 1); results.addAll(tmp); for(ArrayList<Integer> curr:tmp){ ArrayList<Integer> cache = curr; cache.add(set.get(index)); results.add(cache); } } return results; } // Combinatorics Method public ArrayList<ArrayList<Integer>> getAllSubSets(ArrayList<Integer> set){ int num = set.size(); int compator = 1 << num; ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>> (); for(int i = 0; i < compator; i++){ ArrayList<Integer> current = getSubSetFromCompator(set, i, num); result.add(current); } return result; } public ArrayList<Integer> getSubSetFromCompator(ArrayList<Integer> set, int compator, int num){ ArrayList<Integer> result = new ArrayList<Integer>(); for(int i = 0; i < num; i++){ if((compator & (1<<i)) != 0){ result.add(set.get(i)); } } return result; } public static void main(String[] args){ ArrayList<Integer> test = new ArrayList<Integer>(); test.add(1); test.add(2); test.add(3); SubSet ss = new SubSet(); ArrayList<ArrayList<Integer>> results = ss.getAllSubSetsRecursion(test); for(ArrayList<Integer> result:results){ for(int i = 0; i < result.size(); i++){ System.out.print(result.get(i)); } System.out.println(); } } }<file_sep>package edu.nyu.zhaohui.amazon; import java.util.Arrays; public class AdjancentValue { private class Combination implements Comparable<Combination>{ public int index; public int value; public Combination(int ind, int val){ this.index = ind; this.value = val; } @Override public int compareTo(Combination another) { return this.value - another.value; } } public int minumDistance(int[] array){ int len = array.length; Combination[] comb = new Combination[len]; for(int i = 0; i < len; i++){ comb[i] = new Combination(i, array[i]); } Arrays.sort(comb); int ret = Integer.MAX_VALUE; int last = comb[0].index; boolean firstDifferent = false; for(int i = 1; i < len; i++){ if(comb[i].value != comb[i - 1].value){ ret = Math.min(ret, Math.abs(comb[i].index - comb[i - 1].index)); last = comb[i].index - 1; firstDifferent = true; }else if(firstDifferent){ ret = Math.min(ret, Math.abs(comb[i].index - last)); } } last = comb[len - 1].index; firstDifferent = false; for(int i = len - 1; i > 0; i--){ if(comb[i].value != comb[i - 1].value){ ret = Math.min(ret, Math.abs(comb[i].index - comb[i - 1].index)); last = comb[i].index; firstDifferent = true; }else if(firstDifferent){ ret = Math.min(ret, Math.abs(comb[i].index - last)); } } return ret; } public static void main(String[] args){ int[] a = {0, 3, 3, 7, 5, 3, 11,1}; int[] b = {1, 4, 7, 3, 3, 5, 6}; AdjancentValue av = new AdjancentValue(); System.out.println(av.minumDistance(a)); System.out.println(av.minumDistance(b)); } } <file_sep>package edu.nyu.zhaohui.amazon; public class StudentResult { int studentId; String data; int testScore; public StudentResult(int id, String data, int score){ this.studentId = id; this.data = data; this.testScore = score; } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getData() { return data; } public void setData(String data) { this.data = data; } public int getTestScore() { return testScore; } public void setTestScore(int testScore) { this.testScore = testScore; } }
ff4ae902d4cac402ebe06f142fa49c2db4db0f75
[ "Markdown", "Java", "C", "C++" ]
37
Java
rjsikarwar/interview
82a8a82d11841f887444589535847ba166fefaef
85f08861639dddd0d8c84883d11b286651600541
refs/heads/master
<repo_name>AlexeyMagdich/OOP<file_sep>/Person.h // основной модуль, содержит класс 'Person', который в свою очередь содержит остальные классы #pragma once #include "stdafx.h" #include "Name.h" #include "Address.h" // 'дефайны' для перечисления 'Sex' #define M Person::Sex::MALE #define F Person::Sex::FEMALE #define U Person::Sex::UNKNOWN class Person { public: enum Sex { MALE, FEMALE, UNKNOWN }; static int size; private: const int number; Name name; Address address; Sex sex; public: Person(); Person(std::string fn, std::string ln); Person(std::string fn, std::string ln, std::string c, std::string r); Person(const Name& n, const Address& a, Sex s); Person(const Name* n, const Address* a, Sex s); Person(const Person& p); ~Person() { size--; }; void SetName(std::string fn, std::string ln); void SetName(const Name& n); void SetAddress(std::string c, std::string r); void SetAddress(const Address& a); void SetSex(Sex s); void PrintBasicInfo() const; void PrintSex() const; static void ShowSize(); Person& operator=(const Person& p); };<file_sep>/Performer.cpp #include "stdafx.h" #include "Performer.h" /* ----- КОНСТРУКТОРЫ ----- */ Performer::Performer() : Firstdate(), Lastdate(), Jobtitle("") { }; Performer::Performer(const Date& fd, const Date& ld, const std::string j) : IsOk(CheckPerformer(fd, ld, j)), Firstdate(fd), Lastdate(ld), Jobtitle(j) { }; Performer::Performer(const Performer& p) : IsOk(CheckPerformer(p.Firstdate, p.Lastdate, p.Jobtitle)), Firstdate(p.Firstdate), Lastdate(p.Lastdate), Jobtitle(p.Jobtitle) { }; /* ----- МЕТОДЫ ----- */ void Performer::SetFirstdate(const Date d) { Firstdate = d; }; void Performer::SetLastdate(const Date d) { Lastdate = d; }; void Performer::SetJobtitle(std::string j) { Jobtitle = j; }; void Performer::SetPerformInfo(const Date& fd, const Date& ld, const std::string j) { Firstdate = fd; Lastdate = ld; Jobtitle = j; }; void Performer::PrintPerformInfo() { std::cout << "Дата устройства: " << Firstdate.dd << "." << Firstdate.mm << "." << Firstdate.yyyy << std::endl; std::cout << "Дата увольнения: " << Lastdate.dd << "." << Lastdate.mm << "." << Lastdate.yyyy << std::endl; std::cout << "Специализация: " << Jobtitle << std::endl; };<file_sep>/Person.cpp #include "stdafx.h" #include "Person.h" int Person::size = 0; // инициализация статического свойства /* ----- КОНСТРУКТОРЫ ------ */ Person::Person() : name(), address(), sex(UNKNOWN), number(size++) { }; Person::Person(std::string fn, std::string ln) : name(fn, ln), address("", ""), sex(UNKNOWN), number(size++) { }; Person::Person(std::string fn, std::string ln, std::string c, std::string r) : name(fn, ln), address(c, r), sex(UNKNOWN), number(size++) { }; Person::Person(const Person& p) : name(p.name), address(p.address), sex(UNKNOWN), number(size++) { }; Person::Person(const Name& n, const Address& a, Sex s) : name(n), address(a), sex(s), number(size++) { }; Person::Person(const Name* n, const Address* a, Sex s) : name(*n), address(*a), sex(s), number(size++) { }; /* ----- МЕТОДЫ ----- */ void Person::SetName(std::string fn, std::string ln) { this->name.SetName(fn, ln); this->sex = UNKNOWN; }; void Person::SetName(const Name& n) { this->name.SetName(n); }; void Person::SetAddress(std::string c, std::string r) { this->address.SetAddress(c, r); }; void Person::SetAddress(const Address& a) { this->address.SetAddress(a); }; void Person::SetSex(Sex s) { this->sex = s; }; void Person::PrintSex() const { std::cout << "Пол: "; if (sex == MALE) std::cout << "МУЖ"; else if (sex == FEMALE) std::cout << "ЖЕН"; std::cout << std::endl; }; void Person::PrintBasicInfo() const { this->name.PrintName(); this->PrintSex(); if (this->address.IsEmptyAddress() == false) { this->address.PrintAddress(); }; std::cout << std::endl; }; void Person::ShowSize() { std::cout << "Размер = " << size << std::endl; }; Person& Person::operator=(const Person& p) { this->name = p.name; this->address = p.address; this->sex = p.sex; return *this; };<file_sep>/OOP.cpp #include "stdafx.h" #include "Employee.h" #include "Error.h" int main() { setlocale(LC_ALL, "Russian"); try { Employee e1; e1.SetName("Лёша", "Магдич"); e1.SetAddress("Беларусь", "Минск"); e1.SetSex(M); e1.SetFirstdate(*(new Performer::Date(1,7, 2013))); e1.SetLastdate(*(new Performer::Date(9, 7, 2016))); e1.SetJobtitle("Программист"); e1.PrintBasicInfo(); e1.PrintPerformInfo(); Employee e2( 2, (new Name("Артём", "Синица")), (new Address("Беларусь", "Минск")), M, *(new Performer::Date(16, 11, 2014)), *(new Performer::Date(17, 3, 2016)), "Разработчик" ); std::cout << std::endl << " ---------- " << std::endl << std::endl; e2.PrintBasicInfo(); e2.PrintPerformInfo(); std::cout << std::endl; } catch (Error e) { std::cout << "ОШИБКА #" << e.code << " - " << e.message << std::endl; }; return 0; }; <file_sep>/Name.h class Name { private: std::string Firstname; std::string Lastname; public: Name(); Name(std::string fn, std::string ln); Name(const Name& n); ~Name() { }; void SetName(std::string fn, std::string ln); void SetName(const Name& n); void PrintName() const; private: bool IsOk; // необходима для метода CheckName (инициализируется этим методом) bool CheckName(std::string fn, std::string ln); // проверяет аргмента на наличие ошибок, если успех - генерирует исключение };<file_sep>/Name.cpp #include "stdafx.h" #include "Name.h" /* ----- CONSTRUCTORS ----- */ Name::Name() : Firstname(""), Lastname("") { }; // перед инициализацией при создании объекта, в первую очередь инициализируется переменная IsOk, // причём её значение будет true, если в методе CheckName() или CheckAddress() не будут обнаружены // критические ошибки, которые повлекут за собой генерацию исключения (см. модуль Error) Name::Name(std::string fn, std::string ln) : IsOk(CheckName(fn, ln)), Firstname(fn), Lastname(ln) { }; Name::Name(const Name& n) : IsOk(CheckName(n.Firstname, n.Lastname)), Firstname(n.Firstname), Lastname(n.Lastname) { }; /* ----- МЕТОДЫ ----- */ void Name::SetName(std::string fn, std::string ln) { Firstname = fn; Lastname = ln; }; void Name::SetName(const Name& n) { Firstname = n.Firstname; Lastname = n.Lastname; }; void Name::PrintName() const { std::cout << "Имя: " << Firstname << std::endl; std::cout << "Фамилия: " << Lastname << std::endl; };<file_sep>/Error.h // модуль содержит в себе класс 'Error', необходимый для генерации исключений, где // исключение порождает объект класса 'Error', причём объект конструируется в момент // генерации (throw). Объект ошибки включает в себя код (отсчёт от ERROR_CODE == 0) ошибки // информативное сообщение (причина), а также указатель на "аварийный" объект #define ERROR_CODE 0 #define INCORRECT_SYMBOLS "0123456789" #define ERROR_MSG_COUNTRY "Некорретное название страны" #define ERROR_MSG_REGION "Некорретное название региона" #define ERROR_MSG_FIRSTNAME "Неккоретное имя" #define ERROR_MSG_LASTNAME "<NAME>" #define ERROR_MSG_DAY "Некорректная дата (число)" #define ERROR_MSG_MONTH "Некорреткная дата (месяц)" #define ERROR_MSG_YEAR "Некорректная дата (год)" #define ERROR_MSG_JOBTITLE "Некорректное название работы" // сообщаем о том, что будут использваться классы 'Address' и 'Name' class Address; class Name; class Performer; class Error { public: const static int ERROR_COUNTRY = ERROR_CODE + 1; const static int ERROR_REGION = ERROR_CODE + 2; const static int ERROR_FIRSTNAME = ERROR_CODE + 3; const static int ERROR_LASTNAME = ERROR_CODE + 4; const static int ERROR_DAY = ERROR_CODE + 5; const static int ERROR_MONTH = ERROR_CODE + 6; const static int ERROR_YEAR = ERROR_CODE + 7; const static int ERROR_JOBTITLE = ERROR_CODE + 8; int code; std::string message; const Address* erraddress; const Name* errname; const Performer* errperformer; Error(int c, std::string msg, const Address* ea); Error(int c, std::string msg, const Name* en); Error(int c, std::string msg, const Performer* ep); };<file_sep>/Employee.cpp #include "stdafx.h" #include "Employee.h" /* ----- КОНСТРУКТОРЫ ----- */ Employee::Employee(const Name* n, const Address* a, Sex s) : Person::Person(n, a, s) { }; Employee::Employee(const Employee& e) : Person::Person(e) { }; Employee::Employee( int id, const Name* n, const Address* a, Sex s, const Performer::Date& fd, const Performer::Date& ld, std::string j) : ID(id), Person(n, a, s), Performer(fd, ld, j) { }; /* ----- МЕТОДЫ ----- */ void Employee::SetID(int id) { this->ID = id; }; void Employee::SetFirstdate(const Date d) { Performer::SetFirstdate(d); }; void Employee::SetLastdate(const Date d) { Performer::SetLastdate(d); }; void Employee::SetJobtitle(std::string j) { Performer::SetJobtitle(j); }; void Employee::PrintPerformInfo() { std::cout << "ID: " << size << std::endl; this->Performer::PrintPerformInfo(); };<file_sep>/Employee.h #pragma once #include "Person.h" #include "Performer.h" class Employee : public Person, protected Performer { public: Employee() { }; Employee(const Name* n, const Address* a, Sex s); Employee(const Employee& e); Employee( int id, const Name* n, const Address* a, Sex s, const Performer::Date& fd, const Performer::Date& ld, std::string j); ~Employee() { }; private: int ID; public: void SetID(int id); void SetFirstdate(const Date d); void SetLastdate(const Date d); void SetJobtitle(std::string j); void PrintPerformInfo(); }; <file_sep>/Address.cpp #include "stdafx.h" #include "Address.h" /* ----- КОНСТРУКТОРЫ ----- */ Address::Address() : Country(""), Region("") { }; Address::Address(std::string c, std::string r) : IsOk(CheckAddress(c, r)), Country(c), Region(r) { }; Address::Address(const Address& a) : IsOk(CheckAddress(a.Country, a.Region)), Country(a.Country), Region(a.Region) { }; /* ----- МЕТОДЫ ----- */ void Address::SetAddress(std::string c, std::string r) { Country = c; Region = r; }; void Address::SetAddress(const Address& a) { SetAddress(a.Country, a.Region); }; void Address::PrintAddress() const { std::cout << "Страна: " << this->Country << std::endl; std::cout << "Город: " << this->Region << std::endl; }; bool Address::IsEmptyAddress() const { return (Country.empty() || Region.empty()) ? true : false; };<file_sep>/Error.cpp #include "stdafx.h" #include "Error.h" #include "Person.h" #include "Performer.h" /* ----- КОНСТРУКТОРЫ ------ */ Error::Error(int c, std::string msg, const Address* ea) : code(c), erraddress(ea) { this->message = msg; }; Error::Error(int c, std::string msg, const Name* en) : code(c), errname(en) { this->message = msg; }; Error::Error(int c, std::string msg, const Performer* ep) : code(c), errperformer(ep) { this->message = msg; }; /* ------ МЕТОДЫ ------- */ bool Name::CheckName(std::string fn, std::string ln) { bool rc = true; for (int i = 0; i < 10; i++) { if (fn.find(INCORRECT_SYMBOLS[i]) != std::string ::npos) throw Error(Error::ERROR_FIRSTNAME, ERROR_MSG_FIRSTNAME, this); if (ln.find(INCORRECT_SYMBOLS[i]) != std::string ::npos) throw Error(Error::ERROR_LASTNAME, ERROR_MSG_LASTNAME, this); }; return rc; }; bool Address::CheckAddress(std::string c, std::string r) { bool rc = true; for (int i = 0; i < 10; i++) { if (c.find(INCORRECT_SYMBOLS[i]) != std::string ::npos) throw Error(Error::ERROR_COUNTRY, ERROR_MSG_COUNTRY, this); if (r.find(INCORRECT_SYMBOLS[i]) != std::string ::npos) throw Error(Error::ERROR_REGION, ERROR_MSG_REGION, this); }; return rc; }; bool Performer::CheckPerformer(const Date& fd, const Date& ld, const std::string j) { bool rc = true; if (fd.dd < 0 || fd.dd > 31 || ld.dd < 0 || ld.dd > 31) { throw Error(Error::ERROR_DAY, ERROR_MSG_DAY, this); } else if (fd.mm < 0 || fd.mm > 12 || ld.mm < 0 || ld.mm > 12) { throw Error(Error::ERROR_MONTH, ERROR_MSG_MONTH, this); } else if (fd.yyyy < 1940 || fd.yyyy > 2016 || ld.yyyy < 1940 || ld.yyyy > 2016) { throw Error(Error::ERROR_YEAR, ERROR_MSG_YEAR, this); } else { for (int i = 0; i < 10; i++) { if (j.find(INCORRECT_SYMBOLS[i]) != std::string::npos) throw Error(Error::ERROR_JOBTITLE, ERROR_MSG_JOBTITLE, this); }; }; return rc; }; <file_sep>/Address.h // модуль содержит в себе вспомогательную информацию об объекте // в модуле определён класс Address с набором необходимых конструкторов методов и свойств // наибольший интерес - bool-переменная IsOk и метод CheckAddress() class Address { private: std::string Country; std::string Region; public: Address(); Address(std::string c, std::string r); Address(const Address& a); ~Address() { }; void SetAddress(std::string c, std::string r); void SetAddress(const Address& a); void PrintAddress() const; bool IsEmptyAddress() const; private: bool IsOk; // необходима для метода CheckAddress (инициализируется этим методом) bool CheckAddress(std::string c, std::string r); // проверяет аргмента на наличие ошибок, если успех - генерирует исключение };<file_sep>/Performer.h class Performer { public: struct Date { int dd; int mm; int yyyy; Date(int dd = 0, int mm = 0, int yyyy = 0) { this->dd = dd; this->mm = mm; this->yyyy = yyyy; }; Date(const Date& d) { this->dd = d.dd; this->mm = d.mm; this->yyyy = d.yyyy; }; }; private: Date Firstdate; // первый день работы Date Lastdate; // последний день работы std::string Jobtitle; // должность protected: void SetFirstdate(const Date d); void SetLastdate(const Date d); void SetJobtitle(std::string j = ""); public: Performer(); Performer(const Date& fd, const Date& ld, const std::string j); Performer(const Performer& p); ~Performer() { }; private: bool IsOk; bool CheckPerformer(const Date& fd, const Date& ld, const std::string j); public: void SetPerformInfo(const Date& fd, const Date& ld, const std::string j); void PrintPerformInfo(); };<file_sep>/README.md Это репозиторий, хранящий в себе мою хронологию изучения объектно-ориентированного программирования на основе языка C++, а также процесс освоения Git'a и GitHub'a.
c1c3165a18e27e472a9abbbb2e10dc29fb565184
[ "Markdown", "C++" ]
14
C++
AlexeyMagdich/OOP
86691468249bc01a49cffae4c64e34be30c49250
de8dd7a52565cb66f5ce7da0f99de97b7cacb891
refs/heads/master
<repo_name>skshbjj/BMI-Calculator-Android-App<file_sep>/app/src/main/java/com/sakshibajaj/bmicalculator/SecondActivity.java package com.sakshibajaj.bmicalculator; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class SecondActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks { TextView tvWelcome, tvLocation; public TextView tvTemp; Spinner sFeet, sInches; Button btnView, btnCalculate; EditText etWeight; GoogleApiClient gac; Location loc; static DBHandler db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); tvWelcome = findViewById(R.id.tvWelcome); sFeet = findViewById(R.id.sFeet); sInches = findViewById(R.id.sInches); btnCalculate = findViewById(R.id.btnCalculate); btnView = findViewById(R.id.btnView); etWeight = findViewById(R.id.etWeight); tvLocation = findViewById(R.id.tvLocation); tvTemp = findViewById(R.id.tvTemp); db = new DBHandler(this); final ArrayList<String> height = new ArrayList<String>(); height.add("1"); height.add("2"); height.add("3"); height.add("4"); height.add("5"); height.add("6"); height.add("7"); ArrayAdapter<String> heightAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, height); sFeet.setAdapter(heightAdapter); sFeet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int i, long id) { String f = parent.getItemAtPosition(i).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); final ArrayList<String> Inches = new ArrayList<String>(); Inches.add("1"); Inches.add("2"); Inches.add("3"); Inches.add("4"); Inches.add("5"); Inches.add("6"); Inches.add("7"); Inches.add("8"); Inches.add("9"); Inches.add("10"); Inches.add("11"); Inches.add("12"); ArrayAdapter<String> InchesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, Inches); sInches.setAdapter(InchesAdapter); sInches.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int i2, long id) { String i1 = parent.getItemAtPosition(i2).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); final Intent i = getIntent(); final String name = i.getStringExtra("n"); final SharedPreferences sp = getSharedPreferences("MyP", Context.MODE_PRIVATE); tvWelcome.setText("Welcome " + sp.getString("n", name)); btnCalculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos1 = sFeet.getSelectedItemPosition(); int pos2 = sInches.getSelectedItemPosition(); int feet = Integer.parseInt(height.get(pos1)); int inch = Integer.parseInt(Inches.get(pos2)); String we = etWeight.getText().toString(); if (we.length() == 0) etWeight.setError("Please enter your weight"); else { double w = Double.parseDouble(we); double h = (feet * 0.3048 + inch * 0.0254); double bmi = w / (h * h); SharedPreferences.Editor editor = sp.edit(); editor.putString("bmi", String.valueOf(bmi)); editor.apply(); Toast.makeText(SecondActivity.this, "Submitted successfully", Toast.LENGTH_SHORT).show(); etWeight.setText(""); Intent i3 = new Intent(SecondActivity.this, ThirdActivity.class); i3.putExtra("bmi", bmi); startActivity(i3); } } }); btnView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(SecondActivity.this, HistoryActivity.class); startActivity(i); } }); GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this); builder.addApi(LocationServices.API); builder.addConnectionCallbacks(this); builder.addOnConnectionFailedListener(this); gac = builder.build(); gac.connect(); } @Override public void onBackPressed() { SharedPreferences sp = getSharedPreferences("MyP",Context.MODE_PRIVATE); if(sp.getBoolean("c",false)==true){ new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Attention!") .setMessage("Are you sure you want to exit?").setCancelable(true).setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finishAffinity(); } }).setNegativeButton("No",null).show(); } else{} } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.m1, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.about) { Toast.makeText(this, "Created by <NAME>", Toast.LENGTH_SHORT).show(); } if (item.getItemId() == R.id.website) { Intent w = new Intent(Intent.ACTION_VIEW); w.setData(Uri.parse("http://" + "www.stackoverflow.com")); startActivity(w); } return super.onOptionsItemSelected(item); } @Override protected void onStart() { super.onStart(); if (gac != null) gac.connect(); } @Override protected void onStop() { super.onStop(); if (gac != null) gac.disconnect(); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Toast.makeText(this, "Connection failed", Toast.LENGTH_SHORT).show(); } @Override public void onConnected(Bundle bundle) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } if(ActivityCompat.checkSelfPermission(this,Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){ return; } loc = LocationServices.FusedLocationApi.getLastLocation(gac); if(loc!=null){ double lat = loc.getLatitude(); double lon = loc.getLongitude(); Geocoder g = new Geocoder(SecondActivity.this, Locale.ENGLISH); try { List<Address> addressList = g.getFromLocation(lat,lon,1); Address address = addressList.get(0); String add = address.getLocality()+", "+address.getSubAdminArea()+", "+address.getAdminArea()+", "+address.getPostalCode(); tvLocation.setText(add); String web = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+lon+"&units=metric"; //String que = "&q=" + address.getLocality(); String api = "&APPID=<KEY>"; String info = web + api; new MyTask(tvTemp).execute(info); } catch (IOException e) { e.printStackTrace(); } } else Toast.makeText(this, "Please enable GPS/Use in open area to get Location", Toast.LENGTH_SHORT).show(); } @Override public void onConnectionSuspended(int i) { Toast.makeText(this, "Connection suspended", Toast.LENGTH_SHORT).show(); } } class MyTask extends AsyncTask<String,Void,Double> { double temp; private TextView msg; public MyTask(TextView msg) { this.msg = msg; } @Override protected Double doInBackground(String... strings) { String json ="", line = ""; try { URL url = new URL(strings[0]); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.connect(); InputStreamReader isr = new InputStreamReader(con.getInputStream()); BufferedReader br = new BufferedReader(isr); while ((line = br.readLine()) !=null){ json = json + line + "\n"; } JSONObject o = new JSONObject(json); JSONObject p = o.getJSONObject("main"); temp = p.getDouble("temp"); } catch (Exception e) { e.printStackTrace(); } return temp; } @Override protected void onPostExecute(Double aDouble) { super.onPostExecute(aDouble); msg.setText("Temp:"+temp+"C"); } } <file_sep>/app/src/main/java/com/sakshibajaj/bmicalculator/DBHandler.java package com.sakshibajaj.bmicalculator; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; public class DBHandler extends SQLiteOpenHelper { SQLiteDatabase db; Context context; DBHandler(Context context){ super(context, "bmi_db", null,1); this.context = context; db = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { String sql = "create table bmi(date text primary key," + "bmi text)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public void add(String date, double bmi) { ContentValues cv = new ContentValues(); cv.put("date",date); cv.put("bmi",bmi); long rid = db.insert("bmi",null,cv); if(rid<0) Toast.makeText(context, "Already exists", Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Record saved", Toast.LENGTH_SHORT).show(); } public String view() { Cursor cursor = db.query("bmi", null,null,null,null,null,null); StringBuffer sb = new StringBuffer(); cursor.moveToFirst(); if(cursor.getCount()>0) { do { String date = cursor.getString(0); String bmi = String.valueOf(cursor.getDouble(1)); sb.append("Date: "+date+"\nBMI:"+bmi+"\n\n"); }while (cursor.moveToNext()); } return sb.toString(); } }
e95f7f42c7e118c0d933ee57e3d1c0e2cb3e8a68
[ "Java" ]
2
Java
skshbjj/BMI-Calculator-Android-App
9ada4eee6aa1abbeadbd7da107e51c6e2959a0f2
1543d87b216545806a993e5a3a13381755a866ee
refs/heads/master
<file_sep>#include<iostream> using namespace std; const float MILLION = 1.0e6; int main() { cout.setf(ios_base::fixed, ios_base::floatfield); float num = 10.0 / 3.0; cout << num << " ,multiply million: " << MILLION*num << endl; return 0; }
0ca6455b736ab8af4e5c68911f1148f541c3c284
[ "C++" ]
1
C++
GlambertsQY/Elementary
ee04be529220ea50f2b23ec699de4de6c2a6855e
2e069412ba36dd52a829203799d5f1b06be8415e
refs/heads/master
<repo_name>adamgiebl/Python-CSV<file_sep>/merged/withoutmenu.py import csv # adds the module that is needed for parsing the CSV file from time import process_time def parsing(): # defines the below part as a function, so it can be run anytime, easily with open('data.csv', 'r') as csv_file: # opens the CSV file as a readable csv_reader = csv.DictReader(csv_file,delimiter = ',') # uses a function from the CSV module to assign the data from the file to dictionaries with the correct headers for row in csv_reader: print(row) # uses a for loop to print out the dictionaries parsing() def avrg_speed(): # defines the below part as a function, so it can be run anytime, easily sum1 = 0 sum2 = 0 # creates variables that will be used later date = [] time = [] location = [] dwnld = [] upld = [] # creates empty lists with open('data.csv', 'r', encoding="utf8") as csv_file: # opens the CSV file as a readable csv_reader = csv.reader(csv_file,delimiter = ',') for row in csv_reader: date.append(row[0]) time.append(row[1]) location.append(row[2]) dwnld.append(row[3]) upld.append(row[4]) # uses a for loop and list function to assign the date from the CSV file to the empty lists t = process_time() all_loc = [i for i, x in enumerate(location) if x == "Fanø"] # counts all the locations which are named Fano, then assigns it to a variable aug_date = [i for i, x in enumerate(date) if "2018-08" in x] # counts all the dates which begin with 2018-08, then assigns it to a variable sep_date = [i for i, x in enumerate(date) if "2018-09" in x] # counts all the dates which begin with 2018-09, then assigns it to a variable aug_set = (set(all_loc) & set(aug_date)) # gets the intersection between Fano and August and puts them into a set sep_set = (set(all_loc) & set(sep_date)) # gets the intersection between Fano and September and puts them into a set aug_list = list(aug_set) sep_list = list(sep_set) # converts the sets to lists len_aug = len(aug_list) len_sep = len(sep_list) # counts how many elemnts are in the lists for t1 in range(len_aug): # uses a for loop combined with the range function, it basically counts until the list's length sum1 = sum1 + float(dwnld[aug_list[t1]]) # converts the August list's index numbers to the download speed data and adds them together for t2 in range(len_sep): # uses a for loop combined with the range function, it basically counts until the list's length sum2 = sum2 + float(dwnld[sep_list[t2]]) # converts the September list's index numbers to the download speed data and adds them together num1 = sum1 + sum2 # adds the sums of August and September num2 = len_aug + len_sep # adds the number of elemts together avrg = num1 / num2 # divides the sums by the number of elements, therefeore counts average print(avrg) time_elapsed = round(process_time() - t, 5) print(time_elapsed) avrg_speed() <file_sep>/TDC_Case_Report_Group_23.py import matplotlib.pyplot as plt # plotting data from termcolor import colored # print colored messages in the terminal import colorama # makes termcolor work on windows from os import path # working with file path import datetime as dt # parsing and formatting date from time import process_time # measuring execution time of code import csv # reading csv files from pprint import pprint as pp # prettyfied printing, easier debugging # ------------------------------------------------------ # To find program exectuion, go to the end of this file. # ------------------------------------------------------ class Parser: """This is a class for parsing and retrieving CSV data.""" # default utf8 encoding to be able to read special characters like Ø def __init__(self, encoding="utf8"): """ Args: encoding (str, optional): Specify which encoding should be used in reading the file. """ self.encoding = encoding def get_path(self): """Method that asks a user for a path and returns it. Provides simple validation if file doesn't exists or user has put in a file that is not a csv. Returns: String if successful, None otherwise. """ path_csv = input("Enter path to your csv file: ") if path.exists(path_csv): # splits path into file name and file extension # with [1] we get only the extension extension = path.splitext(path_csv)[1] if extension == ".csv": return path_csv else: print(colored("File is not a csv", "red")) return None else: print(colored("File doesn't exist", "red")) print( colored( """If you don't know how to write a path, try putting the file in the same directory as your program""", "red", ) ) print( colored( """Path has to come from the directory you ran the program in, which is not necessarily a directory of the python program.""", "red", ) ) return None def get_data(self, separator): """Method for reading csv contents and parsing it into a list of dictionaries. Uses the csv module. Method can handle data with x amount of columns and will automatically assign correct headers. Args: separator (str): Defines how are values separated in a csv file. Returns: List of ditionaries if successful, None otherwise. """ path_csv = self.get_path() if path_csv is None: return # start counting time elapsed t = process_time() data = [] # opens a file in read mode and reads it with the correct encoding with open(path_csv, encoding=self.encoding) as file: # gets all of the lines in the file reader = csv.reader(file, delimiter=separator) # get headers from the first line # skips the first line and saves it in a list headers = next(reader) # loop over remaining lines and put them into list of dictionaries for line in reader: # continue parsing only if the data is correct # (same number of items as headers) if len(line) == len(headers): values = [] for i in range(len(headers)): values.append(line[i]) # connecting values with headers and creating a dictionary data.append(dict(zip(headers, values))) if not data: print(colored("There was no data parsed, try again.", "red")) return # getting result of time elapsed time_elapsed = round(process_time() - t, 5) print(colored("CSV successfully parsed with csv module", "green")) print(colored(f"Time to read and parse: {time_elapsed}s", "white")) return data def check_data(func): """Decorator function to check if the data exists before user tries to use functions that require it.""" def inner(*args, **kwargs): # checking if first argument (data) is empty if args[0]: func(*args, **kwargs) else: print(colored("There is no data to work with.", "red")) print("Try parsing the file first.") input("Click ENTER to continue...") return inner def filter_by_city(city, data): """Filters data by city name. Args: city (str): City name. data (list of dict): Data to be filtered. Returns: list: List of ditionaries. """ # filter that compares location using a lambda operator return list(filter(lambda x: x["location"] == city, data)) def get_date_object(string_date): """Returns a date object from a string. Args: string_date (str): Date in plain string. Returns: datetime: Object with useful methods for working with date. """ return dt.datetime.strptime(string_date, "%Y-%m-%d") def get_average_from_list(list): """Calculates the average from a list. Args: list (list): List of numbers. Returns: int: Average of a list. """ # calculate the average return sum(list) / len(list) def ask_user(menu): """Prints out a menu and asks for users input accordingly. Args: menu (str): Text that defines the menu. Returns: String if input is text, Int if input is a number. """ print(menu) res = input() if res.isdigit(): return int(res) else: return res.lower() def get_average_speed_per_months(city, data): """Calculates average speed per each month in a specified city. Args: city (str): City name. data (list of dict): Data to be used. Returns: dict: { 'x': (list): Months, 'y': (list): Average speeds. } """ city = filter_by_city(city, data) months_dict = {} for dict in city: temp_list = [] month = get_date_object(dict["date"]).month if month in months_dict: months_dict[month].append(float(dict["download"])) else: temp_list.append(float(dict["download"])) months_dict[month] = temp_list avg_dict = {} for k, v in months_dict.items(): avg_dict[int(k)] = get_average_from_list(v) items = avg_dict.items() tuples = sorted(items) # asterisk takes tuples out of a list and spreads them out # (positional expansion) # e.g. [1,2,3,4] > 1, 2, 3, 4 # zip pairs items from lists together # e.g. [1, 2, 3], ["a", "b", "c"] > [[1, "a"], [2, "b"], [3, "c"]] x, y = zip(*tuples) return {"x": x, "y": y} def get_speeds_per_month(selected_month, data): """Returns all the speeds for a selected month. Args: selected_month (str): Full month name. data (list of dict): Data to be used. Returns: list: List of all speeds. """ speeds = [] # parses a month name into a month number month_number = str(dt.datetime.strptime(selected_month, "%B").month) for dict in data: # formats a date string into a month number temp_month = get_date_object(dict["date"]).strftime("%m").lstrip("0") if month_number == temp_month: speeds.append(float(dict["download"])) return speeds def get_plot_config(label_x="x", label_y="y", ticks=10): """Sets desired plot config. Args: label_x (str): Name of an x label. label_y (str): Name of a y label. ticks (int): Number of ticks. """ plt.tight_layout() plt.xlabel(label_x) plt.ylabel(label_y) plt.xticks(ticks) plt.legend(loc="best") plt.show() def get_plot_theme(): """Returns a correct plot style accrording to the state of dark mode. Returns: str: Plot style. """ global dark_mode if dark_mode: return "dark_background" else: return "ggplot" def parse_data(): """Uses Parser class to parse data into a global variable.""" # use variable data from the global scope global data data = parser.get_data(separator=",") input("Click ENTER to continue...") def toggle_dark_mode(): """Toggles a dark mode state.""" global dark_mode dark_mode ^= True print("Dark mode is:", end=" ") if dark_mode: print(colored("ON", "green")) print("Open a graph to see the results.") else: print(colored("OFF", "red")) input("Click ENTER to continue...") menu = """ | —MENU— | Enter a number to select the function you want to perform: | 1. Parse the CSV file. | 2. Print average download speed for Fanø in August and September. | 3. Plot monthly average download speed for Copenhagen and Ballerup. | 4. Create a bar plot of the upload speed per date for Lolland Commune | 5. Toggle dark mode | Press Q to quit """ colorama.init() """Makes colored terminal output work on Windows""" parser = Parser("utf8") """Parser: Instance of the Parser class.""" data = [] """List: Used as a container for the parsed data.""" choice = ask_user(menu) """String: Getting and storing users input.""" dark_mode = False """Boolean: Keeps track if DarkMode is ON or OFF""" @check_data def function2(data): first_month = "August" second_month = "September" city = "Fanø" city_data = filter_by_city(city, data) august_speeds = get_speeds_per_month(first_month, city_data) september_speeds = get_speeds_per_month(second_month, city_data) print( f"Average download speed for {first_month} and {second_month} in {city} is:" ) print( colored( get_average_from_list(august_speeds + september_speeds), "green" ) ) input("Click ENTER to continue...") @check_data def function3(data): average_speed_ballerup = get_average_speed_per_months("Ballerup", data) average_speed_copenhagen = get_average_speed_per_months("Copenhagen", data) # plots the data with a correct theme with plt.style.context(get_plot_theme()): plt.plot( average_speed_ballerup["x"], average_speed_ballerup["y"], "red", label="Ballerup", ) plt.plot( average_speed_copenhagen["x"], average_speed_copenhagen["y"], "blue", label="Copenhagen", ) get_plot_config( label_x="Month", label_y="Avg. Download speed", # getting the number of months from dictionary ticks=average_speed_ballerup["x"], ) @check_data def function4(data): city = "Lolland" average_speed = get_average_speed_per_months(city, data) # plots the data with a correct theme with plt.style.context(get_plot_theme()): plt.bar(average_speed["x"], average_speed["y"], label=city) get_plot_config( label_x="Month", label_y="Avg. Download speed", ticks=average_speed["x"], ) # selecting a function based on a users choice while choice != "q": if choice == 1: parse_data() elif choice == 2: function2(data) elif choice == 3: function3(data) elif choice == 4: function4(data) elif choice == 5: toggle_dark_mode() choice = ask_user(menu)
1e327d23dee810e214252e4d5d77adbfb1838866
[ "Python" ]
2
Python
adamgiebl/Python-CSV
3e2a49f46968e2dc72b5e73e975d473bad6e36bb
281d1594e84a14a6be2d6e7c8125fe4ea4559d55
refs/heads/master
<repo_name>sissokho/basics-frontend-components-collections<file_sep>/README.md # Basics Frontend Components Collections ⚡ This is a large collections of some basics frontend components crafted with HTML, CSS & JavaScript only, ready to be used 🛠 ## Contributing 🌍 If you want to contribute, feel free to Fork this repo and help out on this project. If you also find an Issues, do not hesitate to let me know **[here](https://github.com/daoodaba975/basics-frontend-components-collections/issues)** ### Contact 📬 I'am always avaible on **[Twitter](https://twitter.com/daoodaba975)** 🐦 to discuss. > You can buy me a coffee ☕ 👇🏽 <a href="https://www.buymeacoffee.com/daoodaba975" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/lato-orange.png" alt="Buy Me A Coffee" style="height: 51px !important;width: 217px !important; border-radius: 10px;" ></a> #### License 🎫 📌 This code is released under the **[MIT License](LICENSE)** ✔ > **Enjoy!** 🙏🏾 <file_sep>/loaders/bash/script.js function init(){ const out=document.getElementById("output"); const chars=['\\','|','/','—']; let index=0; let count=0; let n=0; function animate(){ n=parseInt((count/10)%10); out.innerHTML="["+("#").repeat(n)+("-").repeat(10-n)+"]"+chars[index]+"<br>"+parseInt(count)+"%"; index++; count++; count%=100; index%=4; setTimeout(animate,100); } setTimeout(animate,100); }
39203bb1553e8de647fb64f293d2d047edb124cf
[ "Markdown", "JavaScript" ]
2
Markdown
sissokho/basics-frontend-components-collections
d10637cd2882fa1185d24e9f0a56d2ee4566a4d9
80c5a6df8ada57366884f6384a4aa9ac8736655d
refs/heads/master
<file_sep># coding=utf-8 from TimeIt import timeit ''' Задача 3. Наибольший простой делитель Простые делители числа 13195 - это 5, 7, 13 и 29. Каков самый большой делитель числа 600851475143, являющийся простым числом? ''' @timeit def get_greatest_divisor(): max_simple_digit = 0 result = 0 super_num = 600851475143 test = 10000 for num in range(test): if num%2 == 0 or num % 5 == 0 or num % 3 == 0: continue else: result = num for digit in range(1, num): if digit != num and digit != 1 and num % digit == 0: result = 0 else: if max_simple_digit < result: max_simple_digit = result print(max_simple_digit) get_greatest_divisor() #5244.12 ms (отвратительно) <file_sep># coding=utf-8 from TimeIt import timeit """ Задача 4. Наибольшее произведение-палиндром Число-палиндром с обеих сторон (справа налево и слева направо) читается одинаково. Самое большое число-палиндром, полученное умножением двух двузначных чисел – 9009 = 91 × 99. Найдите самый большой палиндром, полученный умножением двух трехзначных чисел. """ def is_poly(num): start = str(num) end = len(start) - 1 for i in range(0, end): if start[i] != start[end - i]: return False return True @timeit def poly_detected(): max = 0 for i in range(1000, 100, -1): for j in range(1000, 100, -1): tmp = i * j if tmp > max and is_poly(tmp): max = tmp return max print(poly_detected()) # 193.76 ms <file_sep># coding=utf-8 from TimeIt import timeit ''' Задача 1. Числа, кратные 3 или 5 Если выписать все натуральные числа меньше 10, кратные 3 или 5, то получим 3, 5, 6 и 9. Сумма этих чисел - 23. Найдите сумму всех чисел меньше 1000, кратных 3 или 5. ''' @timeit def sum1000(): sum = 0 for number in range(1000): if number % 3 == 0 or number % 5 == 0: sum += number return sum print(sum1000()) #0.43 ms <file_sep># coding=utf-8 from TimeIt import timeit ''' Задача 2. Четные числа Фибоначчи Каждый следующий элемент ряда Фибоначчи получается при сложении двух предыдущих. Начиная с 1 и 2, первые 10 элементов будут: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Найдите сумму всех четных элементов ряда Фибоначчи, которые не превышают четыре миллиона. ''' @timeit def sumFib(): first = 0 second = 1 sum = 0 while sum < 4000000: tmp = first + second first = second second = tmp if second % 2 == 0: sum += second return sum print(sumFib()) #0.03 ms
7d44438638f22f8143afaee35d650126e4954a2a
[ "Python" ]
4
Python
tim64/EulerProject
6a5ff63c4046c4a38fa9e38f7615cbafdb51da46
24131c6d9420170eb1cc56a389b239da796e591a
refs/heads/master
<file_sep>using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Muter { public partial class Form1 : Form { private bool skipFirstOnEvent = true; private AudioManager audio = null; private bool muted = false; public Form1() { InitializeComponent(); audio = new AudioManager(); RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); registryKey.SetValue("Muter", Application.ExecutablePath); } private void MonitorOff() { if (!audio.GetMute()) { audio.SetMute(true); muted = true; } } private void MonitorOn() { if (muted) { audio.SetMute(false); muted = false; } } private void notifyIcon1_Click(object sender, EventArgs e) { } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); e.Cancel = true; } private void toolStripMenuIExit_Click(object sender, EventArgs e) { this.Close(); Application.Exit(); Application.ExitThread(); } private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { } private IntPtr unRegPowerNotify = IntPtr.Zero; protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); var settingGuid = new NativeMethods.PowerSettingGuid(); Guid powerGuid = IsWindows8Plus() ? settingGuid.ConsoleDisplayState : settingGuid.MonitorPowerGuid; unRegPowerNotify = NativeMethods.RegisterPowerSettingNotification(this.Handle, ref powerGuid, NativeMethods.DEVICE_NOTIFY_WINDOW_HANDLE); } private bool IsWindows8Plus() { var version = Environment.OSVersion.Version; if (version.Major > 6) return true; // Windows 10+ if (version.Major == 6 && version.Minor > 1) return true; // Windows 8+ return false; // Windows 7 or less } protected override void WndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WM_POWERBROADCAST: if (m.WParam == (IntPtr)NativeMethods.PBT_POWERSETTINGCHANGE) { var settings = (NativeMethods.POWERBROADCAST_SETTING)m.GetLParam(typeof(NativeMethods.POWERBROADCAST_SETTING)); switch (settings.Data) { case 0: Console.WriteLine("Monitor Power Off"); this.MonitorOff(); break; case 1: //SKIP FIRST EVENT Console.WriteLine("Monitor Power On"); if (this.skipFirstOnEvent) { this.skipFirstOnEvent = false; } else { this.MonitorOn(); } break; case 2: Console.WriteLine("Monitor Dimmed"); break; } } m.Result = (IntPtr)1; break; } base.WndProc(ref m); } protected override void OnFormClosing(FormClosingEventArgs e) { // NativeMethods.UnregisterPowerSettingNotification(unRegPowerNotify); base.OnFormClosing(e); } private void Form1_Shown(object sender, EventArgs e) { this.Hide(); } private void Form1_Load(object sender, EventArgs e) { } } }
53d4d3fbedad48a09a69da271e2305f69abd5fcd
[ "C#" ]
1
C#
crosma/Muter
b560b91506977b603e5f5afd2af12556defc457d
ca2066d39cfb00f10b3af6f2d800d1b3abb2b043
refs/heads/master
<file_sep>#!/usr/bin/python2.7 # Este script es para probar que onda. import sys, os import openbabel, pybel from itertools import chain from os.path import basename import numpy as np ################################################################ ####################auxiliary programs########################## ################################################################ def center_of_mass(Vx, Vy, Vz, mass): cgx = np.sum(Vx*mass)/np.sum(mass) cgy = np.sum(Vy*mass)/np.sum(mass) cgz = np.sum(Vz*mass)/np.sum(mass) return (cgx, cgy, cgz) ################################################################ ####################pdbqt parser##################### ################################################################ class PDBQT(): def __init__(self, line): self._parse_common(line) # used here (PDB) and in PDBQT self._parse_specific(line) # differs in PDBQT def getline(self): txt = self._print_common() # no \n; PDB + PDBQT txt += self._print_specific() # differs in PDBQT return txt def _parse_common(self, line): """Common to PDB and PDBQT formats""" self.keyword = line [ 0: 6] # ATOM or HETATM self.serial = int(line [ 6:11]) # atom id # [11:12] self.name = line [12:16] # atom name self.altLoc = line [16:17] # Alternate location self.resName = line [17:20] # Residue name # [20:21] self.chain = line [21:22] # chain self.resNum = int(line [22:26]) # Residue number self.icode = line [26:27] # ??? # [27:30] self.x = float(line[30:38]) # X self.y = float(line[38:46]) # Y self.z = float(line[46:54]) # Z self.occupancy = float(line[54:60]) # Occupancy self.bfact = float(line[60:66]) # Temperature factor def _parse_specific(self, line): """ PDBQT characters [68:79] """ self.charge = float(line[68:76]) # Charge self.atype = line [77:79] # Atom type self.atype = self.atype.strip().upper() def _print_common(self): """ Characters [0:68]""" linestr = '' linestr += '%6s' % (self.keyword) linestr += '%5d' % (self.serial) linestr += ' ' linestr += '%4s' % (self.name) linestr += '%1s' % (self.altLoc) linestr += '%3s' % (self.resName) linestr += ' ' linestr += '%1s' % (self.chain) linestr += '%4d' % (self.resNum) linestr += '%1s' % (self.icode) linestr += ' ' * 3 linestr += '%8.3f' % (self.x) linestr += '%8.3f' % (self.y) linestr += '%8.3f' % (self.z) linestr += '%6.2f' % (self.occupancy) linestr += '%6.2f' % (self.bfact) return linestr def _print_specific(self): """ PDBQT characters [68:79] """ linestr = ' ' * 2 # [66:68] linestr += '%8.3f' % (self.charge) # [68:76] linestr += ' ' * 1 # [76:77] linestr += '%-2s' % (self.atype) # [77:79] #linestr += '\n' return linestr ################################################################################ ########### routine to find rings and return a dict of root member idx, CM, etc# ################################################################################ def ring_finder(filename): """Create a dictionary objects with ring information""" #Setting a new object to be manipulated. mol = openbabel.OBMol() obConversion = openbabel.OBConversion() # imput and output be the same. obConversion.SetInAndOutFormats("sdf", "pdbqt") obConversion.ReadString(mol, filename) # Set the output variable out = [] #iterate over the rings contador =0 for r in mol.GetSSSR(): if r.IsAromatic(): contador+=1 Vx = np.array([]) Vy = np.array([]) Vz = np.array([]) mass = np.array([]) for obatom in openbabel.OBMolAtomIter(mol): if r.IsInRing(obatom.GetIdx()): Vxcurrent=np.array([obatom.GetX()]) Vx=np.concatenate((Vx,Vxcurrent)) Vycurrent=np.array([obatom.GetY()]) Vy=np.concatenate((Vy,Vycurrent)) Vzcurrent=np.array([obatom.GetZ()]) Vz=np.concatenate((Vz,Vzcurrent)) mass_current=np.array([obatom.GetAtomicMass()]) mass=np.concatenate((mass,mass_current)) root_serial=obatom.GetIdx() #return Aromatic center to the current ring. center = center_of_mass(Vx,Vy,Vz,mass) # Save information in a dictionary. element = {'ring_number' : contador, 'root_atom': int(root_serial), 'Type': str(r.GetType()), 'center': center, 'NumAtoms': mol.NumAtoms()} out.append(element) return out def mod_pdbqt(inputfile,name,ring_list): """Creates a list of PDBQT atom objects""" #abro el archivo a modificar f = inputfile.split("\n") # Defino la lista de anillos. #ring_list = ring_finder(inputfile) # si no encuentro aromaticos entonces devuelvo el mismo archivo. if len(ring_list)==0: # out variable out = [] print "WARNING: the input file ", name, " does not contain aromatic rings" for line in f: out.append(str(line) + "\n") else: current_dummy_serial = ring_list[0]['NumAtoms'] #itero sobre los anillos. for element in ring_list: # out variable out = [] #itero sobre las lineas del archivo. for line in f: if line.startswith('ATOM ') or line.startswith('HETATM'): #Defino un objeto parseable con las propiedades del atomo. atom = PDBQT(line) # defino el index del root del anillo. #the index for the root atom. O for furan, S for thiazole, N for pyrrole. For 6 membered aromatic rings, the first non carbon atom is used for root. For 5 members rings the O, S or N (BOSum=3, valence=3) will be used for root root_serial = element['root_atom'] # Si encuentro el root en el archivo if int(root_serial)==int(atom.serial): # Defino el centro de masa el anillo. ring_CM = element['center'] #Genero una nueva linea para el CM. new_line = atom.getline() add_line = PDBQT(new_line) # Modificar coordenadas con las del CM. current_dummy_serial = int(current_dummy_serial) + 1 add_line.serial = current_dummy_serial add_line.x = ring_CM[0] add_line.y = ring_CM[1] add_line.z = ring_CM[2] # Modifico propiedades del CM. add_line.name = str('CM ') add_line.resNum = atom.resNum add_line.atype = 'E' add_line.charge = float(0.00) # Imprimo la linea root y CM. out.append(str(atom.getline())) out.append(str(add_line.getline())) #imprimo las lineas hayan o no sido modificadas. else: out.append(str(atom.getline())) else: #imprimo las lineas relacionadas con los REMARKS o torsiones ENDS etc. out.append(str(line)) # defino el archivo f como el nuevo con las modificaciones. f=out return f def add_dummy(input_filename, outfilename): # Defino el nombre del archivo y la extension. filename, file_extension = os.path.splitext(input_filename) if (file_extension==".sdf" or file_extension==".sd"): #molecule number N=0 for mymol in pybel.readfile(file_extension.strip("."), input_filename): # Send file to a variable. mol=mymol.write("pdbqt") # nombre de la molecula N. N+=1 outfilename_base = mymol.title + "_" + str(N) #abro el archivo de salida out = open(outfilename_base + '_dum.pdbqt', 'w') # Hago las cosas. ring_list = ring_finder(mymol.write("sdf")) coordinates= mod_pdbqt(mol,outfilename_base + '_dum.pdbqt',ring_list) # Escribo en disco. out.writelines(["%s\n" % item for item in coordinates[:-1]]) #out.write(coordinates) out.close() if (file_extension==".pdb"): #defino el nombre de salida salida = outfilename #en caso de no haber dado archivo de salida seteamos el default if salida is None: salida = os.path.splitext(basename(filename))[0]+"_dum.pdbqt" for mymol in pybel.readfile(file_extension.strip("."), input_filename): # Send file to a variable. mol=mymol.write("pdbqt") print(mol) # nombre de la molecula N. #abro el archivo de salida out = open(salida, 'w') # Hago las cosas. ring_list = ring_finder(mymol.write("sdf")) coordinates= mod_pdbqt(mol,salida,ring_list) # Escribo en disco. out.writelines(["%s\n" % item for item in coordinates[:-1]]) #out.write(coordinates) out.close() if file_extension==".pdbqt": #defino el nombre de salida salida = outfilename #en caso de no haber dado archivo de salida seteamos el default if salida is None: salida = os.path.splitext(basename(filename))[0]+"_dum.pdbqt" with open(input_filename, 'r') as f: fileContents = f.read() #read entire file mol=fileContents out = open(salida, 'w') # Hago las cosas. mymol = pybel.readfile("pdbqt",input_filename).next() ring_list = ring_finder(mymol.write("sdf")) coordinates= mod_pdbqt(mol,salida,ring_list) # Escribo en disco. out.writelines(["%s\n" % item for item in coordinates[:-1]]) #out.write(coordinates) out.close() ############## #####MAIN##### ############## if __name__ == '__main__': import sys import getopt def usage(): "Print helpful, accurate usage statement to stdout." print "Usage: prepare_dummies.py -l filename" print print " Description of command..." print " -l ligand_filename (.pdbqt, .pdb or .sdf format)" print " Optional parameters:" print " [-o pdbqt_filename] (default output filename is ligand_filename_stem + _dum + .pdbqt)" print " In sdf files the output name will be taken from the title section.\n" print " Developed by <NAME> (2017) contact:<EMAIL>\n" # process command arguments try: opt_list, args = getopt.getopt(sys.argv[1:], 'l:o:') except getopt.GetoptError, msg: print 'prepare_dummies.py: %s' %msg usage() sys.exit(2) # initialize required parameters #-l: ligand ligand_filename = None # optional parameters #-o outputfilename outputfilename = None #'l:vo:d:A:CKU:B:R:MFI:Zgs' for o, a in opt_list: #print "o=", o, " a=", a if o in ('-l', '--l'): ligand_filename = a if o in ('-o', '--o'): outputfilename = a if o in ('-h', '--'): usage() sys.exit() if not ligand_filename: print 'prepare_aromatic_center: ligand filename must be specified.' usage() sys.exit() else: # ejecuto el programa propiamente dicho. add_dummy(ligand_filename, outputfilename) <file_sep>Notas acerca de prepare_aromatic_center.py Este programa tiene la capacidad de devolver uno o más archivos pdbqts junto con los nuevos centros de masa de cada anillo aromático. Antes de empezar deberá tener instalado open babel, pybel y numpy. para instalar pybel (ubuntu/debian) apt-get install python-openbabel SE RECOMIENDA FUERTEMENTE EL EMPLEO DE ARCHIVOS SDF QUE CUENTAN CON MUCHAS MAS INFORMACION QUE LOS ARCHIVOS PDQBTs. El modo de ejecución es el siguiente: $ ./prepare_aromatic_center.py -l loratadine.pdbqt -o loratadine_dummy.pdbqt si no especificamos la salida por defecto escribe "filename" + _dummy.pdbqt. Por otra parte si el archivo de entrada es un sdf, toma el nombre de cada molécula de salida de la sección "title", y el nombre de salida es similar al descripto anteriormente. El script usted lo puede obtener File:Prepare aromatic center.zip aqui junto con un sdf de prueba. Al ejecutar el archivo de prueba obtendrá: $ ./prepare_aromatic_center.py -l SMILES.sdf WARNING: the input file azulene_dummy.pdbqt does not contain aromatic rings WARNING: the input file ciclopropene_dummy.pdbqt does not contain aromatic rings
3683f0c29e5cd5745ae774f83173077dc4b3d780
[ "Markdown", "Python" ]
2
Python
biodatasciencearg/prepare_aromatic_center
53329e310d6781f3aebecd817d5847b54041f4f0
070179785fe0a337372c9a533463d4edeb331f29
refs/heads/master
<repo_name>bekorn/betterweb<file_sep>/app/Http/Controllers/MonoScheduleController.php <?php namespace App\Http\Controllers; use App\Models\MonoSchedule; use App\Repositories\MonoScheduleRepository; use Illuminate\Http\Request; class MonoScheduleController extends Controller { protected $mono_schedule_repo; function __construct(MonoScheduleRepository $mono_schedule_repository) { $this->mono_schedule_repo = $mono_schedule_repository; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response * @internal param MonoSchedule $mono_schedule */ public function show(int $id) { return $this->mono_schedule_repo->with('users_liked', 'courses')->find( $id ); } /** * Show the form for editing the specified resource. * * @param \App\Models\MonoSchedule $mono_schedule * @return \Illuminate\Http\Response */ public function edit(\App\Models\MonoSchedule $mono_schedule) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\MonoSchedule $mono_schedule * @return \Illuminate\Http\Response */ public function update(Request $request, \App\Models\MonoSchedule $mono_schedule) { // } /** * Remove the specified resource from storage. * * @param \App\Models\MonoSchedule $mono_schedule * @return \Illuminate\Http\Response */ public function destroy(MonoSchedule $mono_schedule) { // } } <file_sep>/Project Plan/Pages & Use Cases.md ## Pages #### Main Page Landing Page with a short explanation of the site and links to [registration](#registration) and [login](#login). + ##### Registration > User will use their Google Account associated with their Sabancı Mail to sign up. + ##### Login > ___ #### Profile Page Students can track their courses, degrees programs and see their weekly program. + ##### Active Program > A list of required, area elective and free elective courses of the Active Program. > User can see their progress on finishing the program + ##### Active Schedule > User can see their currently active schedule in a weekly time table, sync it with their Google Calender or take an Excel or PNG export. + ##### Finished Courses > A list of courses user took and passed. This will make possible to [filter courses with requirements](#search-schedule). > Also from this section user can add a course as finished. ___ #### Program Page User can look through all programs offered by Sabancı University. + ##### Set an Active Program > If user finds a schedule applicable, they can set it as their [Active Program](#active-program). This will help user to pick the right courses for their program. ___ #### Course Search Page Look for courses opened this semester + ##### Search Course > User can search courses with parameters for term, title, code, CDN, faculty, instructor. > User also can look through specific groups of courses like recommended, [available (took all courses on restrictions)](#finished-courses) or their program's required, area elective or free electives. ___ #### Schedule Search Page User can find any schedule here. + ##### Search Schedule > User can search semester schedules or long term schedules with parameters for term, title, faculty, CDN, rate. + ##### Set an Active Schedule > If user finds a schedule applicable, they can set it as their [Active Schedule](#active-schedule). ___ #### Schedule Creation Page User can create any schedule here, for one semester or more. + ##### Create a Semester Schedule > User will search and pick courses to form a schedule for a semester. + ##### Create a Long Term Schedule > User will search and pick Semester Schedules to form a schedule over multiple semesters.<file_sep>/database/migrations/2017_01_04_192341_create_meetings_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMeetingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('meetings', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->enum('day', ['M', 'T', 'W', 'R', 'F']); $table->time('start_time'); $table->time('end_time'); $table->string('type'); $table->date('start_date'); $table->date('end_date'); $table->string('schedule_type'); $table->unsignedInteger('course_id')->index(); $table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('meetings'); } } <file_sep>/database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $size = 30; function get_range( $size = 30 ) { // global $size; $min = mt_rand(1, $size); $max = mt_rand($min, $size); return range( $min, $max ); }; function get_random( $size = 30 ) { // global $size; return mt_rand( 1, $size ); }; factory( App\Models\User::class, $size )->create(); // ->each( function ($u) { // $u->mono_schedules()->saveMany( factory( App\Models\MonoSchedule::class, mt_rand(0, 3) ) ); // }); factory( App\Models\Instructor::class, $size )->create(); factory( App\Models\Requirement::class, $size )->create(); factory( App\Models\Course::class, $size )->create() ->each( function ($c) { $c->completed_users()->attach( get_range() ); $c->instructors()->sync( [get_random() => ['primary' => false], get_random() => ['primary' => false], get_random() => ['primary' => false], get_random() => ['primary' => true]] ); foreach ( factory( App\Models\Meeting::class, 3 )->make() as $m ) { $c->meetings()->save( $m ); $m->instructors()->attach( get_random() ); } foreach ( factory( App\Models\Review::class, rand(0, 3) )->make() as $r) { $r['user_id'] = get_random(); $r['instructor_id'] = get_Random(); $r['course_id'] = get_Random(); $c->reviews()->save( $r ); $r->users_liked()->attach( get_range() ); } }); foreach ( factory( App\Models\MonoSchedule::class, $size )->make() as $ms ) { App\Models\User::find( get_random() )->mono_schedules()->save( $ms ); $ms->courses()->sync( [get_random(), get_random(), get_random()] ); $ms->users_applied()->attach( get_range(), ['active' => false] ); $ms->users_liked()->attach( get_range() ); } foreach ( factory( App\Models\PolySchedule::class, $size )->make() as $ps ) { App\Models\User::find( get_random() )->poly_schedules()->save( $ps ); $ps->mono_schedules()->sync( [get_random(), get_random(), get_random()] ); $ps->users_applied()->attach( get_range(), ['active' => false] ); $ps->users_liked()->attach( get_range() ); } } } <file_sep>/app/Http/Controllers/CourseController.php <?php namespace App\Http\Controllers; use App\Repositories\CourseRepository; use Illuminate\Http\Request; class CourseController extends Controller { protected $course_repo; public function __construct (CourseRepository $course_repository) { $this->course_repo = $course_repository; } public function show (int $id) { return $this->course_repo->find($id); } public function index () { $courses = $this->course_repo->with('instructors', 'meetings', 'requirements')->paginate(12); return view('courses.index', ['courses' => $courses] ); } } <file_sep>/database/migrations/2017_01_05_114443_create_instructor_meeting_pivot_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInstructorMeetingPivotTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('instructor_meeting', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->unsignedInteger('instructor_id')->index(); $table->foreign('instructor_id')->references('id')->on('instructors')->onDelete('cascade'); $table->unsignedInteger('meeting_id')->index(); $table->foreign('meeting_id')->references('id')->on('meetings')->onDelete('cascade'); $table->primary(['instructor_id', 'meeting_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('instructor_meeting'); } }<file_sep>/app/Http/Controllers/Auth/LoginController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Repositories\UserRepository; use Laravel\Socialite\Facades\Socialite; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { protected $user_repo; public function __construct(UserRepository $user_repository) { $this->user_repo = $user_repository; } public function loginPage() { return view('auth.login'); } /** * Redirect the user to the Google authentication page. * * @return Response */ public function redirectToProvider() { return Socialite::driver('google')->redirect(); } /** * Obtain the user information from Google. * * @return Response */ public function handleProviderCallback() { $user = Socialite::driver('google')->stateless()->user(); if( Arr::get($user->user, 'domain') != 'sabanciuniv.edu' ) { return redirect('/login')->withErrors('Invalid email domain. Only @sabanciuniv.edu users can login this system.'); } $my_user = $this->user_repo->where('email', $user->email)->first(); if( is_null($my_user) ) { $my_user = $this->user_repo->create([ 'given_name' => $user->user['name']['givenName'], 'family_name' => $user->user['name']['familyName'], 'email' => $user->email, 'google_token' => $user->token, 'avatar_url' => $user->avatar_original, ]); } Auth::login($my_user); return redirect('/home'); } public function logout() { Auth::logout(); return redirect('home'); } }<file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/home', 'HomeController@index')->name('home'); Route::get('/', function () { return view('welcome'); }); Route::namespace('Auth')->group( function () { Route::prefix('/login')->group( function () { Route::get('/', 'LoginController@loginPage')->name('login'); Route::get('/google-auth-redirect', 'LoginController@redirectToProvider')->name('google-auth'); Route::get('/google-auth-callback', 'LoginController@handleProviderCallback'); }); Route::get('/logout', 'LoginController@logout')->name('logout'); }); Route::prefix('user')->group( function () { Route::get('{user}', 'UserController@show')->name('user'); }); Route::prefix('course')->group( function () { Route::get('/', 'CourseController@index')->name('courses'); Route::get('{course}', 'CourseController@show')->name('course'); Route::get('{course}/requirement', 'RequirementController@show')->name('requirement'); }); Route::prefix('instructor')->group( function () { Route::get('/', 'InstructorController@index')->name('instructors'); Route::get('/{instructor}', 'InstructorController@show')->name('instructor'); }); Route::prefix('mono-schedule')->group( function () { Route::get('{mono_schedule}', 'MonoScheduleController@show'); }); Route::prefix('poly-schedule')->group( function () { Route::get('{poly_schedule}', 'PolyScheduleController@show'); });<file_sep>/app/Models/Meeting.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Meeting extends Model { public $timestamps = null; public function course() { return $this->belongsTo(Course::class); } public function instructors() { return $this->belongsToMany(Instructor::class); } } <file_sep>/app/Models/PolySchedule.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class PolySchedule extends Model { public function user() { return $this->belongsTo(User::class); } public function users_liked() { return $this->belongsToMany(User::class, 'poly_schedule_likes', 'poly_schedule_id', 'user_id'); } public function mono_schedules() { return $this->belongsToMany(MonoSchedule::class, 'poly_has_mono', 'poly_schedule_id', 'mono_schedule_id'); } public function users_applied() { return $this->belongsToMany(User::class, 'poly_schedule_applied', 'poly_schedule_id', 'user_id')->withPivot('active'); } public function active_users() { return $this->users_applied()->where('active', '=', true); } } <file_sep>/app/Models/MonoSchedule.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class MonoSchedule extends Model { // protected $with = ['courses']; public function user() { return $this->belongsTo(User::class); } public function users_liked() { return $this->belongsToMany(User::class, 'mono_schedule_likes', 'mono_schedule_id', 'user_id'); } public function courses() { return $this->belongsToMany(Course::class, 'mono_has_courses', 'mono_schedule_id', 'course_id'); } public function users_applied() { return $this->belongsToMany(User::class, 'mono_schedule_applied', 'mono_schedule_id', 'user_id')->withPivot('active'); } public function active_users() { return $this->users_applied()->where('active', '=', true); } } <file_sep>/app/Repositories/RequirementRepository.php <?php namespace App\Repositories; use App\Models\Course; use App\Models\Requirement; class RequirementRepository extends Repository { public function model() { return Requirement::class; } // public function show (int $course_id) // { // $course = Course::find( $course_id ); // // if( empty( $course ) ) // { // throw new \Exception('Course not found'); // } // // $requirements = $course->required_courses; // return $requirements; // } }<file_sep>/database/migrations/2017_00_00_110915_create_courses_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCoursesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('courses', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->unsignedInteger('cdn'); $table->string('term'); $table->string('code'); $table->string('title'); $table->string('section'); $table->string('type'); $table->string('faculty'); $table->unsignedTinyInteger('ECTS'); $table->unsignedTinyInteger('su_credit'); $table->unsignedSmallInteger('capacity'); $table->unsignedSmallInteger('remaining'); $table->string('catalog_entry_link')->nullable(); $table->string('detailed_information_link')->nullable(); $table->decimal('rating', 9, 8)->nullable()->default(null); $table->unsignedMediumInteger('number_of_ratings')->default( 0 ); $table->unique(['cdn', 'term']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('courses'); } } <file_sep>/README.md # BetterWeb Schedules __An app that makes creating schedules easy, for SU BannerWeb.__ :notebook_with_decorative_cover: Create your schedule for a semester. :books: Combine multiple schedules to plan your courses over years. :busts_in_silhouette: Help others by sharing them!<file_sep>/app/Http/Controllers/InstructorController.php <?php namespace App\Http\Controllers; use App\Repositories\InstructorRepository; use Illuminate\Http\Request; class InstructorController extends Controller { protected $instructor_repo; function __construct(InstructorRepository $instructor_repository) { $this->instructor_repo = $instructor_repository; } public function index() { return 'all instructors'; } public function show(int $id) { return $this->instructor_repo->find($id); } } <file_sep>/Project Plan/Database.sql -- This file contains all tables, views, triggers and procedures used in this project. -- sqlizer.io is used to convert JSON files (scrapped data) into SQL statements SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT ; SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS; SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION; SET NAMES utf8mb4; -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `students` ( `s_id` INT(11) NOT NULL, `name` VARCHAR(255) COLLATE utf8_unicode_520_ci NOT NULL, `surname` VARCHAR(255) COLLATE utf8_unicode_520_ci NOT NULL, `mail` VARCHAR(255) COLLATE utf8_unicode_520_ci NOT NULL, `password` VARCHAR(255) COLLATE utf8_unicode_520_ci NOT NULL, PRIMARY KEY (`s_id`), UNIQUE (`mail`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `students` (`s_id`, `name`, `surname`, `mail`, `password`) VALUES (1, 'Your Friendly', 'Neighborhood Senior', '<EMAIL>', '$2y$10$qr0jkdEQyWtpzw9aZR4vYOaaKIgfVEp3aZM4QTvZ3A.gH4LECBw1u'), (11111, 'ramazan', 'gidiyor', '<EMAIL>', '$2y$10$I/4IM6oSF8OMQrM4uN2zte.ymv57kMsDRGx4dvJF1Sp5rE515iWdu'), (11311, 'Ayse', 'Karabaş', '<EMAIL>', 'Buncuk9'), (12385, 'Mehmet', 'Okur', '<EMAIL>', 'UtahJazZz1'), (13856, '<NAME>', 'Erimçağ', '<EMAIL>', 'MemCan2186'), (15130, 'Mehmet', 'Balibaşa', '<EMAIL>', 'MemBal3'), (15381, 'Kaan', 'Akyıldız', '<EMAIL>', 'Reis1995'), (15896, 'Ahmet', 'Hıdırellez', '<EMAIL>', 'Hido123'), (17679, 'Berke', 'Koçulu', '<EMAIL>', 'KediKopek8956'), (17891, 'Ceyla', 'Cerenoğlu', '<EMAIL>', 'PrensesCey3'), (19131, 'Şeyma', 'Subaşı', '<EMAIL>', 'AcunAsk1'), (20638, 'Seren', 'Serengil', '<EMAIL>', 'aBjKaa8139a3'), (20813, 'çık', 'çığk', '<EMAIL>', '$2y$10$DKgwwUihLle2y022DNu.6u1QOLcSFSo7FBtG/8HWYJxB/Y/BPOBLq'), (20948, 'Ramazan', 'Geliyor', '<EMAIL>', '$2y$10$0pecMiatoN6Qv3g1lUpOZeXOCZLfr09LYCB9tawa32XrmyE4kGeAe'),(20960, 'Berk', 'Canlı', '<EMAIL>', '$2y$10$gD6MnbJgPZAJDor9/WBwJuPXQq2bCavRqlcDX2QVEiccrcWMd0wf6'); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `courses` ( `cdn` INT NOT NULL, `term` VARCHAR(16) NOT NULL, `code` VARCHAR(16) NOT NULL, `title` VARCHAR(100) NOT NULL, `section` VARCHAR(4) NOT NULL, `type` VARCHAR(20) NOT NULL, `faculty` VARCHAR(4) NOT NULL, `ECTS` INT NOT NULL, `su_credit` INT NOT NULL, `capacity` INT NOT NULL, `remaining` INT NOT NULL, `catalog_entry_link` VARCHAR(195), `detailed_information_link` VARCHAR(120), `rating` float NULL, `number_of_ratings` INT(6) NOT NULL, PRIMARY KEY (`cdn`, `term`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `courses` (`catalog_entry_link`, `term`, `faculty`, `ECTS`, `su_credit`, `type`, `title`, `cdn`, `code`, `section`, `detailed_information_link`, `capacity`, `remaining`) VALUES ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Introduction to Financial Accounting and Reporting',10001,'ACC 201','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10001',51,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Introduction to Financial Accounting and Reporting',10002,'ACC 201','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10002',50,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Introduction to Financial Accounting and Reporting',10003,'ACC 201','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10003',51,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Introduction to Financial Accounting and Reporting',10977,'ACC 201R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10977',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Introduction to Financial Accounting and Reporting',10978,'ACC 201R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10978',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Introduction to Financial Accounting and Reporting',10979,'ACC 201R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10979',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Introduction to Financial Accounting and Reporting',10980,'ACC 201R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10980',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Introduction to Financial Accounting and Reporting',10981,'ACC 201R','C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10981',27,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Introduction to Financial Accounting and Reporting',10982,'ACC 201R','C2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10982',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Managerial Accounting',10004,'ACC 301','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10004',50,11), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Managerial Accounting',10005,'ACC 301R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10005',50,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=403&sel_crse_end=403&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Auditing',10006,'ACC 403','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10006',50,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Financial Accounting and Reporting',11162,'ACC 501','YPY','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11162',55,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Financial Accounting and Reporting',11194,'ACC 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11194',50,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=901&sel_crse_end=901&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,2,'Course','Financial Reporting',11185,'ACC 901','DA','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11185',40,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ACC&sel_crse_strt=901&sel_crse_end=901&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,2,'Course','Financial Reporting',11184,'ACC 901','TU','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11184',50,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=501E&sel_crse_end=501E&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,0,'Course','Academic Practices and Development',11297,'GR 501E','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11297',100,38), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=501M&sel_crse_end=501M&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',7,0,'Course','Academic Practices and Development',11137,'GR 501M','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11137',15,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=501S&sel_crse_end=501S&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',7,0,'Course','Academic Practices and Development',10137,'GR 501S','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10137',100,27), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=502E&sel_crse_end=502E&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,0,'Course','Academic Practices and Development 2',11298,'GR 502E','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11298',100,56), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=502M&sel_crse_end=502M&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',7,0,'Course','Academic Practices and Development 2',11138,'GR 502M','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11138',5,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=502S&sel_crse_end=502S&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',7,0,'Course','Academic Practices and Development 2',10138,'GR 502S','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10138',100,33), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=503E&sel_crse_end=503E&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,0,'Course','Academic Practices and Development 3',11299,'GR 503E','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11299',100,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=503S&sel_crse_end=503S&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',7,0,'Course','Academic Practices and Development 3',10139,'GR 503S','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10139',50,47), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=555E&sel_crse_end=555E&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,0,'Course','Scientific and Technical Communication',11146,'GR 555E','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11146',50,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=555E&sel_crse_end=555E&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,0,'Course','Scientific and Technical Communication',11147,'GR 555E','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11147',50,21), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GR&sel_crse_strt=555E&sel_crse_end=555E&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,0,'Course','Scientific and Technical Communication',11148,'GR 555E','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11148',50,31), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic Arabic I',11015,'ARA 110','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11015',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic Arabic I',11016,'ARA 110','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11016',9999,9977), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Arabic I',11019,'ARA 110D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11019',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Arabic I',11020,'ARA 110D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11020',9999,9977), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=130&sel_crse_end=130&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Intermediate Arabic I',11023,'ARA 130','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11023',9999,9989), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=130D&sel_crse_end=130D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Intermediate Arabic I',11025,'ARA 130D','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11025',9999,9989), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',10,3,'Course','Basic Arabic I',11017,'ARA 510','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11017',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',10,3,'Course','Basic Arabic I',11018,'ARA 510','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11018',9999,9977), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=510D&sel_crse_end=510D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Arabic I',11021,'ARA 510D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11021',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=510D&sel_crse_end=510D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Arabic I',11022,'ARA 510D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11022',9999,9977), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=530&sel_crse_end=530&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',10,3,'Course','Intermediate Arabic I',11024,'ARA 530','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11024',9999,9989), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ARA&sel_crse_strt=530D&sel_crse_end=530D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Intermediate Arabic I',11026,'ARA 530D','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11026',9999,9989), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BP&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Brand Management',11728,'BP 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11728',50,23), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BP&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Consumer Behaviour',11730,'BP 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11730',50,23), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BP&sel_crse_strt=512&sel_crse_end=512&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',3,1,'Course','International Marketing I',11731,'BP 512','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11731',50,23), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BP&sel_crse_strt=521&sel_crse_end=521&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Big Picture in Marketing',11727,'BP 521','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11727',50,23), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BP&sel_crse_strt=531&sel_crse_end=531&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',3,1,'Course','Economics and Practice of Finance',11737,'BP 531','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11737',50,23), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BAN&sel_crse_strt=500&sel_crse_end=500&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',10,3,'Course','Introduction to Business Analytics',11152,'BAN 500','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11152',15,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BAN&sel_crse_strt=502&sel_crse_end=502&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',10,3,'Course','Introduction to Decision Making',11153,'BAN 502','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11153',15,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=BAN&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',3,0,'Course','Graduate Seminar',11238,'BAN 599','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11238',15,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CHEM&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Inorganic Chemistry',10387,'CHEM 301','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10387',30,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CHEM&sel_crse_strt=301L&sel_crse_end=301L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Inorganic Chemistry',11122,'CHEM 301L','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11122',30,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CHEM&sel_crse_strt=405&sel_crse_end=405&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Electrochemistry',10389,'CHEM 405','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10389',9999,9977), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CHEM&sel_crse_strt=505&sel_crse_end=505&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Electrochemistry',10390,'CHEM 505','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10390',9999,9977), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',4,0,'Course','Civic Involvement Projects I',10847,'CIP 101','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10847',350,148), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',4,0,'Course','Civic Involvement Projects I',10848,'CIP 101','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10848',350,114), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( OtizmliÇocuklar EğitMerkezi )',11564,'CIP 101P','P01','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11564',8,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( İşitme Engelli )',11565,'CIP 101P','P02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11565',9,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( ÖğrenmeGüçlüğüÇekenÇocuklar )',11566,'CIP 101P','P03','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11566',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( İşaret Dili )',11567,'CIP 101P','P04','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11567',15,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Zihinsel Engelli Çocuklar )',11568,'CIP 101P','P05','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11568',8,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Çocuklara İnsan Hakları )',11571,'CIP 101P','P06','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11571',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Çocuklarla İngilizce )',11572,'CIP 101P','P07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11572',21,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( İ<NAME> - Çevre Çocuk )',11574,'CIP 101P','P08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11574',11,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Akıl Oyunları - Çocuk )',11576,'CIP 101P','P09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11576',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Özgüven - Çocuk )',11577,'CIP 101P','P10','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11577',14,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( İknaEdenKazansın - ÇocukMünazara )',11578,'CIP 101P','P11','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11578',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Suriyeli Çocuklar )',11580,'CIP 101P','P12','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11580',13,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Çayırova Sevgi Evleri )',11581,'CIP 101P','P13','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11581',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Huzurevi - 1 )',11582,'CIP 101P','P14','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11582',8,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Huzurevi - 2 )',11583,'CIP 101P','P15','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11583',12,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Huzurevi - 3 )',11584,'CIP 101P','P16','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11584',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Huzurevi - 4 )',11585,'CIP 101P','P17','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11585',8,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Mülteciler için Eğitim Hakkı )',11586,'CIP 101P','P18','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11586',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( İnsan Hakları )',11587,'CIP 101P','P19','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11587',11,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Hayvan Hakları 1 )',11588,'CIP 101P','P20','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11588',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Hayvan Hakları 2 )',11589,'CIP 101P','P21','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11589',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Kentsel Tarım )',11590,'CIP 101P','P22','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11590',8,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Toplumsal Cinsiyet Projesi )',11591,'CIP 101P','P23','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11591',16,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11592,'CIP 101P','P24','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11592',8,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11593,'CIP 101P','P25','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11593',7,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11594,'CIP 101P','P26','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11594',9,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11595,'CIP 101P','P27','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11595',9,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11596,'CIP 101P','P28','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11596',16,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11597,'CIP 101P','P29','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11597',15,11), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Okullarda Çocuk Projesi )',11598,'CIP 101P','P30','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11598',9,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Çocuklarla İngilizce - II )',11609,'CIP 101P','P31','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11609',5,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Animal Rights in Shelters )',11732,'CIP 101P','P32','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11732',15,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Primary School - I )',11733,'CIP 101P','P33','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11733',13,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Primary School - II )',11734,'CIP 101P','P34','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11734',12,11), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Game Rights for children )',11735,'CIP 101P','P35','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11735',16,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CIP&sel_crse_strt=101P&sel_crse_end=101P&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','CIAD',0,0,'Course','Civic Involvement Projects ( Urban Agriculture )',11736,'CIP 101P','P36','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11736',12,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Computing',10916,'CS 201','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10916',389,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10917,'CS 201R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10917',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10918,'CS 201R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10918',23,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10919,'CS 201R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10919',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10920,'CS 201R','A4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10920',22,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10921,'CS 201R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10921',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10922,'CS 201R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10922',23,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10923,'CS 201R','B3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10923',23,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10924,'CS 201R','B4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10924',23,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',11703,'CS 201R','B5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11703',27,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10925,'CS 201R','C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10925',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10926,'CS 201R','C2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10926',22,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10927,'CS 201R','C3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10927',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10928,'CS 201R','C4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10928',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10929,'CS 201R','D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10929',24,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10930,'CS 201R','D2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10930',23,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10931,'CS 201R','D3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10931',24,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computing',10932,'CS 201R','D4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10932',23,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Advanced Programming',10933,'CS 204','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10933',90,18), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=204L&sel_crse_end=204L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Advanced Programming',10934,'CS 204L','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10934',22,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=204L&sel_crse_end=204L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Advanced Programming',10935,'CS 204L','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10935',23,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=204L&sel_crse_end=204L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Advanced Programming',10936,'CS 204L','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10936',22,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=204L&sel_crse_end=204L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Advanced Programming',10937,'CS 204L','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10937',23,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=300&sel_crse_end=300&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Data Structures',10391,'CS 300','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10391',90,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=300R&sel_crse_end=300R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Data Structures',10392,'CS 300R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10392',90,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=302&sel_crse_end=302&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Formal Languages and Automata Theory',10393,'CS 302','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10393',42,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Formal Languages and Automata Theory',11126,'CS 302R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11126',42,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303&sel_crse_end=303&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,4,'Course','Logic and Digital System Design',10394,'CS 303','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10394',130,21), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303L&sel_crse_end=303L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Logic and Digital System Design',10395,'CS 303L','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10395',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303L&sel_crse_end=303L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Logic and Digital System Design',10396,'CS 303L','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10396',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303L&sel_crse_end=303L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Logic and Digital System Design',10397,'CS 303L','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10397',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303L&sel_crse_end=303L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Logic and Digital System Design',10398,'CS 303L','D','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10398',22,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303L&sel_crse_end=303L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Logic and Digital System Design',10399,'CS 303L','E','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10399',21,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303L&sel_crse_end=303L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Logic and Digital System Design',10400,'CS 303L','G','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10400',21,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=303R&sel_crse_end=303R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Logic and Digital System Design',10401,'CS 303R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10401',130,21), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=307&sel_crse_end=307&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Operating Systems',10402,'CS 307','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10402',80,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=307R&sel_crse_end=307R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Operating Systems',10403,'CS 307R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10403',80,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=400&sel_crse_end=400&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Logic in Computer Science',10404,'CS 400','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10404',9999,9970), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=402&sel_crse_end=402&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Compiler Design',10406,'CS 402','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10406',20,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=405&sel_crse_end=405&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Computer Graphics',10407,'CS 405','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10407',50,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=405L&sel_crse_end=405L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Computer Graphics',10408,'CS 405L','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10408',50,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=408&sel_crse_end=408&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Computer Networks',10409,'CS 408','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10409',85,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=408L&sel_crse_end=408L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Computer Networks',10410,'CS 408L','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10410',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=408L&sel_crse_end=408L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Computer Networks',10411,'CS 408L','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10411',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=408L&sel_crse_end=408L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Computer Networks',10412,'CS 408L','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10412',35,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=500&sel_crse_end=500&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Logic in Computer Science',10405,'CS 500','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10405',9999,9970), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=505&sel_crse_end=505&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Numerical Methods',11697,'CS 505','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11697',15,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=506&sel_crse_end=506&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Cognitive Robotics',10413,'CS 506','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10413',15,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Formal Methods for Reliable Digital Systems',10414,'CS 510','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10414',20,15), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=525&sel_crse_end=525&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Data Mining',10415,'CS 525','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10415',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=535&sel_crse_end=535&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Wireless Network Security',10416,'CS 535','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10416',20,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=543&sel_crse_end=543&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Computer Graphics and Visualization',10417,'CS 543','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10417',20,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=551&sel_crse_end=551&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',1,0,'Course','Graduate Seminar I',11556,'CS 551','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11556',50,43), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=560&sel_crse_end=560&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Automated Debugging',10418,'CS 560','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10418',10,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11354,'CS 590','01','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11354',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11364,'CS 590','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11364',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11365,'CS 590','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11365',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11367,'CS 590','09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11367',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11371,'CS 590','12','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11371',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11379,'CS 790','02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11379',10,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11381,'CS 790','03','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11381',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11383,'CS 790','04','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11383',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11384,'CS 790','05','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11384',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11393,'CS 790','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11393',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11394,'CS 790','09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11394',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CS&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11395,'CS 790','10','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11395',10,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Introduction to Conflict Analysis and Resolution',10043,'CONF 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10043',25,15), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Culture and Conflict',10044,'CONF 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10044',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=512&sel_crse_end=512&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Research Methods',10045,'CONF 512','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10045',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=531&sel_crse_end=531&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Conflict Resolution Practice',10046,'CONF 531','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10046',25,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=593&sel_crse_end=593&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',5,0,'Course','Directed Reading',10048,'CONF 593','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10048',20,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10059,'CONF 599','10','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10059',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10051,'CONF 599','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10051',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10052,'CONF 599','3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10052',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10053,'CONF 599','4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10053',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10054,'CONF 599','5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10054',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10056,'CONF 599','7','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10056',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CONF&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',30,0,'Course','Master Thesis',10057,'CONF 599','8','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10057',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=322&sel_crse_end=322&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Youth Culture',10064,'CULT 322','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10064',9999,9965), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=361&sel_crse_end=361&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Oral History',10066,'CULT 361','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10066',9999,9971), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=432&sel_crse_end=432&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Modernism/Postmodernism',10068,'CULT 432','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10068',9999,9983), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=442&sel_crse_end=442&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Gendered Memories of War and Political Violence',10070,'CULT 442','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10070',9999,9974), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=500&sel_crse_end=500&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Core Issues in Cultural Studies',10074,'CULT 500','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10074',20,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=502&sel_crse_end=502&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Epistemological Foundations of Cultural Analysis',10075,'CULT 502','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10075',20,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=522&sel_crse_end=522&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Youth Culture',10065,'CULT 522','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10065',9999,9965), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=532&sel_crse_end=532&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Modernism/Postmodernism',10069,'CULT 532','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10069',9999,9983), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=542&sel_crse_end=542&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Gendered Memories of War and Political Violence',10071,'CULT 542','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10071',9999,9974), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=561&sel_crse_end=561&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Oral History',10067,'CULT 561','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10067',9999,9971), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',5,0,'Course','Pro - thesis Seminar',10077,'CULT 590','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10077',20,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=598&sel_crse_end=598&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Independent Study',11255,'CULT 598','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11255',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10078,'CULT 599','1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10078',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10079,'CULT 599','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10079',10,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10080,'CULT 599','3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10080',10,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10082,'CULT 599','5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10082',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10083,'CULT 599','6','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10083',10,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=CULT&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10087,'CULT 599','9','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10087',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=DA&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Data Analytics',11559,'DA 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11559',35,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=DA&sel_crse_strt=503&sel_crse_end=503&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Applied Statistics',11560,'DA 503','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11560',35,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=DA&sel_crse_strt=505&sel_crse_end=505&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Data Modeling and Processing',11561,'DA 505','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11561',35,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=DA&sel_crse_strt=507&sel_crse_end=507&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Modeling and Optimization',11562,'DA 507','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11562',35,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=DA&sel_crse_strt=580&sel_crse_end=580&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Special Topics in Data Analytics I',11725,'DA 580','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11725',35,34), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=DA&sel_crse_strt=592&sel_crse_end=592&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',30,0,'Course','Term Project',11563,'DA 592','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11563',35,34), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Games and Strategies',10965,'ECON 201','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10965',45,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Games and Strategies',10966,'ECON 201','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10966',45,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Games and Strategies',10967,'ECON 201','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10967',45,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Games and Strategies',10991,'ECON 201R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10991',45,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Games and Strategies',10992,'ECON 201R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10992',45,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=201R&sel_crse_end=201R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Games and Strategies',10993,'ECON 201R','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10993',45,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=202&sel_crse_end=202&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Macroeconomics',10968,'ECON 202','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10968',60,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=202&sel_crse_end=202&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Macroeconomics',10969,'ECON 202','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10969',60,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=202&sel_crse_end=202&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Macroeconomics',10970,'ECON 202','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10970',60,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=202R&sel_crse_end=202R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Macroeconomics',10994,'ECON 202R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10994',60,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=202R&sel_crse_end=202R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Macroeconomics',10995,'ECON 202R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10995',60,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=202R&sel_crse_end=202R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Macroeconomics',10996,'ECON 202R','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10996',60,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Microeconomics',10971,'ECON 204','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10971',46,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Microeconomics',10972,'ECON 204','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10972',46,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Microeconomics',10973,'ECON 204','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10973',53,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=204R&sel_crse_end=204R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Microeconomics',10997,'ECON 204R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10997',46,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=204R&sel_crse_end=204R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Microeconomics',10998,'ECON 204R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10998',46,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=204R&sel_crse_end=204R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Microeconomics',10999,'ECON 204R','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10999',53,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Econometrics',10088,'ECON 301','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10088',9999,9967), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Econometrics',11000,'ECON 301R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11000',9999,9967), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=320&sel_crse_end=320&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Public Economics',10090,'ECON 320','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10090',45,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=340&sel_crse_end=340&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','International Economics',10092,'ECON 340','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10092',60,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=370&sel_crse_end=370&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Advanced Microeconomics',10093,'ECON 370','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10093',31,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=399&sel_crse_end=399&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Independent Study',10094,'ECON 399','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10094',20,15), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=401&sel_crse_end=401&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Applied Econometrics',10095,'ECON 401','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10095',9999,9986), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=405&sel_crse_end=405&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Law and Economics',10097,'ECON 405','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10097',30,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=423&sel_crse_end=423&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Economics of the Welfare State',10098,'ECON 423','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10098',9999,9964), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=481&sel_crse_end=481&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',8,4,'Course','Advanced Microeconomic Theory I',10101,'ECON 481','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10101',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=481R&sel_crse_end=481R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Advanced Microeconomic Theory I',11009,'ECON 481R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11009',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=485&sel_crse_end=485&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',8,4,'Course','Advanced Quantitative Methods',10105,'ECON 485','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10105',9999,9974), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=485R&sel_crse_end=485R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Advanced Quantitative Methods',11013,'ECON 485R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11013',9999,9974), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Microeconomics I',10100,'ECON 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10100',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=501R&sel_crse_end=501R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Microeconomics I',11010,'ECON 501R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11010',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=503&sel_crse_end=503&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Macroeconomics I',10102,'ECON 503','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10102',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=503R&sel_crse_end=503R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Macroeconomics I',11012,'ECON 503R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11012',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=505&sel_crse_end=505&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Quantitative Methods',10104,'ECON 505','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10104',9999,9974), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=505R&sel_crse_end=505R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Recitation','Quantitative Methods',11014,'ECON 505R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11014',9999,9974), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=523&sel_crse_end=523&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Economics of the Welfare State',10099,'ECON 523','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10099',9999,9964), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=591&sel_crse_end=591&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',1,0,'Course','Seminar I',11256,'ECON 591','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11256',20,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=604&sel_crse_end=604&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Applied Econometrics',10096,'ECON 604','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10096',9999,9986), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=607&sel_crse_end=607&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Game Theory',10107,'ECON 607','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10107',16,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=691&sel_crse_end=691&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',1,0,'Course','Seminar III',11257,'ECON 691','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11257',20,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10109,'ECON 699','1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10109',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10110,'ECON 699','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10110',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10111,'ECON 699','3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10111',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10112,'ECON 699','4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10112',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10113,'ECON 699','5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10113',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10114,'ECON 699','6','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10114',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10115,'ECON 699','7','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10115',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10116,'ECON 699','8','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10116',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=799&sel_crse_end=799&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',169,0,'Course','PhD Dissertation',10122,'ECON 799','1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10122',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=799&sel_crse_end=799&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',169,0,'Course','PhD Dissertation',10123,'ECON 799','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10123',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ECON&sel_crse_strt=799&sel_crse_end=799&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',169,0,'Course','PhD Dissertation',10126,'ECON 799','4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10126',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=303&sel_crse_end=303&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Analog Integrated Circuits',10419,'EE 303','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10419',35,16), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=303R&sel_crse_end=303R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Analog Integrated Circuits',10420,'EE 303R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10420',35,16), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=307&sel_crse_end=307&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Semiconductor Physics and Devices',10421,'EE 307','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10421',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=307R&sel_crse_end=307R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Semiconductor Physics and Devices',10422,'EE 307R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10422',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=311&sel_crse_end=311&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Signal Processing and Information Systems',10423,'EE 311','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10423',50,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=311R&sel_crse_end=311R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Signal Processing and Information Systems',10424,'EE 311R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10424',50,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=313&sel_crse_end=313&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Communication Systems',10425,'EE 313','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10425',30,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=313R&sel_crse_end=313R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Communication Systems',10426,'EE 313R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10426',30,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=401&sel_crse_end=401&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,3,'Course','Very Large Scale Integrated System Design I',10427,'EE 401','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10427',20,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=401L&sel_crse_end=401L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','VLSI Systems Design I',10428,'EE 401L','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10428',20,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=403&sel_crse_end=403&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Optoelectronics',10429,'EE 403','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10429',10,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=403R&sel_crse_end=403R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Optoelectronics',10430,'EE 403R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10430',10,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=407&sel_crse_end=407&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Microelectronic Fabrication',10431,'EE 407','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10431',9999,9992), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=407R&sel_crse_end=407R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Microelectronic Fabrication',10433,'EE 407R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10433',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=409&sel_crse_end=409&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Microwaves',10434,'EE 409','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10434',20,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=409R&sel_crse_end=409R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Microwaves',10435,'EE 409R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10435',20,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=413&sel_crse_end=413&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Wireless Communications',10436,'EE 413','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10436',10,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=413R&sel_crse_end=413R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Wireless Communications',10437,'EE 413R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10437',10,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=414&sel_crse_end=414&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Multimedia Communication',10438,'EE 414','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10438',10,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=414R&sel_crse_end=414R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Multimedia Communication',10439,'EE 414R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10439',10,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=417&sel_crse_end=417&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,3,'Course','Computer Vision',10440,'EE 417','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10440',9999,9952), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=417L&sel_crse_end=417L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Computer Vision',10441,'EE 417L','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10441',50,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=533&sel_crse_end=533&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Semiconductor Process Technology',10432,'EE 533','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10432',9999,9992), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=534&sel_crse_end=534&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Integrated Sensors',10447,'EE 534','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10447',14,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=537&sel_crse_end=537&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Advanced Topics in VLSI Design',10448,'EE 537','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10448',10,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=551&sel_crse_end=551&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',1,0,'Course','Graduate Seminar I',11540,'EE 551','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11540',50,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=552&sel_crse_end=552&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',1,0,'Course','Graduate Seminar II',11541,'EE 552','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11541',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=569&sel_crse_end=569&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','3D Vision',10450,'EE 569','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10450',9999,9952), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=573&sel_crse_end=573&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Biomedical Instrumentation',10443,'EE 573','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10443',10,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11398,'EE 590','03','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11398',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11405,'EE 590','06','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11405',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11406,'EE 590','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11406',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11408,'EE 590','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11408',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11409,'EE 590','09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11409',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=627&sel_crse_end=627&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Advanced Motion Control',10451,'EE 627','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10451',15,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=628&sel_crse_end=628&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Force Control and Bilateral Teleoperation',10452,'EE 628','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10452',15,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=68000&sel_crse_end=68000&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Special Topics in EE: Advances in Radar Imaging',11710,'EE 68000','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11710',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11412,'EE 790','01','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11412',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11414,'EE 790','02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11414',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11416,'EE 790','03','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11416',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11417,'EE 790','04','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11417',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11418,'EE 790','05','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11418',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11421,'EE 790','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11421',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11422,'EE 790','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11422',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11427,'EE 790','11','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11427',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=EE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D.Dissertation',11739,'EE 790','13','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11739',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ETM&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',9,3,'Course','Energy: Economy and Politics',11604,'ETM 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11604',35,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ETM&sel_crse_strt=507&sel_crse_end=507&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',9,3,'Course','Technology and Innovation Management in Energy',11607,'ETM 507','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11607',35,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ETM&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',9,3,'Course','Energy Systems and Technologies',11606,'ETM 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11606',35,16), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ETM&sel_crse_strt=513&sel_crse_end=513&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',9,3,'Course','Fundamental Skills in Energy Studies',11605,'ETM 513','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11605',35,16), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=202&sel_crse_end=202&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Thermodynamics',10886,'ENS 202','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10886',88,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=202R&sel_crse_end=202R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Thermodynamics',10887,'ENS 202R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10887',88,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=203&sel_crse_end=203&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,3,'Course','Electronic Circuits I',10986,'ENS 203','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10986',175,20), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=203R&sel_crse_end=203R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Electronic Circuits I',10987,'ENS 203R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10987',45,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=203R&sel_crse_end=203R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Electronic Circuits I',10988,'ENS 203R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10988',44,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=203R&sel_crse_end=203R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Electronic Circuits I',10989,'ENS 203R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10989',44,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=203R&sel_crse_end=203R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Electronic Circuits I',10990,'ENS 203R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10990',43,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Mechanics',10888,'ENS 204','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10888',150,52), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=204R&sel_crse_end=204R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Mechanics',10889,'ENS 204R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10889',150,52), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205&sel_crse_end=205&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Materials Science I',10890,'ENS 205','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10890',300,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10891,'ENS 205R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10891',23,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10892,'ENS 205R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10892',22,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10893,'ENS 205R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10893',22,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10894,'ENS 205R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10894',22,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10895,'ENS 205R','C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10895',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10896,'ENS 205R','C2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10896',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10897,'ENS 205R','D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10897',21,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10898,'ENS 205R','D2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10898',21,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10899,'ENS 205R','E1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10899',21,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10900,'ENS 205R','E2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10900',21,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10901,'ENS 205R','F1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10901',21,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10902,'ENS 205R','F2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10902',21,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10903,'ENS 205R','G1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10903',21,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=205R&sel_crse_end=205R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Materials Science',10904,'ENS 205R','G2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10904',21,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208&sel_crse_end=208&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Industrial Engineering',10876,'ENS 208','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10876',170,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208&sel_crse_end=208&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Industrial Engineering',10877,'ENS 208','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10877',161,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10878,'ENS 208R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10878',43,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10879,'ENS 208R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10879',41,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10880,'ENS 208R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10880',41,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10881,'ENS 208R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10881',42,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10882,'ENS 208R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10882',42,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10883,'ENS 208R','B3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10883',42,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10884,'ENS 208R','C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10884',40,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=208R&sel_crse_end=208R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Industrial Engineering',10885,'ENS 208R','C2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10885',41,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209&sel_crse_end=209&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Computer Aided Drafting and Solid Modeling',10905,'ENS 209','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10905',150,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209&sel_crse_end=209&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Computer Aided Drafting and Solid Modeling',11233,'ENS 209','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11233',64,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',10906,'ENS 209L','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10906',30,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',10907,'ENS 209L','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10907',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',10908,'ENS 209L','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10908',30,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',10909,'ENS 209L','A4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10909',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',10910,'ENS 209L','A5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10910',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',11234,'ENS 209L','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11234',34,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209L&sel_crse_end=209L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Introduction to Computer Aided Drafting and Solid Modeling',11235,'ENS 209L','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11235',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',10911,'ENS 209R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10911',30,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',10912,'ENS 209R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10912',30,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',10913,'ENS 209R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10913',30,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',10914,'ENS 209R','A4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10914',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',10915,'ENS 209R','A5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10915',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',11236,'ENS 209R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11236',30,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=209R&sel_crse_end=209R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Introduction to Computer Aided Drafting and Solid Modeling',11237,'ENS 209R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11237',34,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=211&sel_crse_end=211&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Signals',10874,'ENS 211','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10874',170,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=211R&sel_crse_end=211R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Signals',11150,'ENS 211R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11150',40,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=211R&sel_crse_end=211R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Signals',11151,'ENS 211R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11151',40,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=211R&sel_crse_end=211R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Signals',11704,'ENS 211R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11704',10,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=211R&sel_crse_end=211R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Signals',10875,'ENS 211R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10875',40,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=211R&sel_crse_end=211R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Signals',11149,'ENS 211R','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11149',40,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11664,'ENS 491','02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11664',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11665,'ENS 491','03','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11665',50,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11669,'ENS 491','04','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11669',50,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11671,'ENS 491','06','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11671',50,46), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11672,'ENS 491','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11672',50,48), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11620,'ENS 491','09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11620',50,41), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11621,'ENS 491','10','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11621',50,42), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11622,'ENS 491','11','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11622',50,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11623,'ENS 491','12','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11623',50,38), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11624,'ENS 491','13','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11624',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11625,'ENS 491','14','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11625',50,43), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11626,'ENS 491','15','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11626',50,38), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11628,'ENS 491','17','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11628',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11630,'ENS 491','19','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11630',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11632,'ENS 491','21','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11632',50,37), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11635,'ENS 491','23','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11635',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11636,'ENS 491','24','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11636',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11643,'ENS 491','31','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11643',50,47), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11646,'ENS 491','34','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11646',50,46), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11647,'ENS 491','35','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11647',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11648,'ENS 491','36','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11648',50,46), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11650,'ENS 491','38','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11650',50,46), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11652,'ENS 491','40','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11652',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11653,'ENS 491','41','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11653',50,37), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11655,'ENS 491','43','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11655',50,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11657,'ENS 491','45','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11657',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11658,'ENS 491','46','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11658',50,42), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11659,'ENS 491','47','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11659',50,42), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11660,'ENS 491','48','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11660',50,34), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11662,'ENS 491','50','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11662',50,43), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11674,'ENS 491','51','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11674',50,37), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11675,'ENS 491','52','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11675',50,46), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11677,'ENS 491','54','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11677',50,38), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11678,'ENS 491','55','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11678',50,38), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11679,'ENS 491','56','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11679',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11680,'ENS 491','57','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11680',50,42), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11681,'ENS 491','58','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11681',50,47), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11682,'ENS 491','59','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11682',50,42), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11683,'ENS 491','60','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11683',50,23), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11684,'ENS 491','61','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11684',50,42), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11685,'ENS 491','62','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11685',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11686,'ENS 491','63','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11686',50,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11687,'ENS 491','64','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11687',50,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11688,'ENS 491','65','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11688',50,44), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11689,'ENS 491','66','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11689',50,35), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11690,'ENS 491','67','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11690',50,31), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11698,'ENS 491','70','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11698',50,48), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11718,'ENS 491','72','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11718',50,48), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11719,'ENS 491','73','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11719',50,47), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11720,'ENS 491','74','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11720',50,31), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11722,'ENS 491','75','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11722',50,48), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11724,'ENS 491','76','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11724',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491&sel_crse_end=491&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Graduation Project (Design)',11738,'ENS 491','77','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11738',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491R&sel_crse_end=491R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Course','Graduation Project: Case Study Session',11693,'ENS 491R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11693',400,190), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=491R&sel_crse_end=491R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Course','Graduation Project: Case Study Session',11694,'ENS 491R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11694',400,238), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11300,'ENS 492','01','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11300',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11301,'ENS 492','02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11301',30,27), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11303,'ENS 492','04','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11303',30,27), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11304,'ENS 492','05','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11304',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11305,'ENS 492','06','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11305',30,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11306,'ENS 492','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11306',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11307,'ENS 492','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11307',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11308,'ENS 492','09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11308',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11309,'ENS 492','10','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11309',30,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11310,'ENS 492','11','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11310',30,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11311,'ENS 492','12','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11311',30,27), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11312,'ENS 492','13','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11312',30,25), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11313,'ENS 492','14','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11313',30,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11314,'ENS 492','15','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11314',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11315,'ENS 492','16','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11315',30,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11316,'ENS 492','17','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11316',30,27), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11317,'ENS 492','18','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11317',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11318,'ENS 492','19','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11318',30,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11319,'ENS 492','20','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11319',30,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11320,'ENS 492','21','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11320',30,25), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11321,'ENS 492','22','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11321',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11322,'ENS 492','23','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11322',30,21), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11323,'ENS 492','24','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11323',30,24), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11324,'ENS 492','25','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11324',30,24), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11325,'ENS 492','26','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11325',30,27), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11326,'ENS 492','27','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11326',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11327,'ENS 492','28','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11327',30,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11328,'ENS 492','29','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11328',30,25), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11329,'ENS 492','30','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11329',30,22), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11330,'ENS 492','31','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11330',30,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11603,'ENS 492','32','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11603',30,29), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11721,'ENS 492','33','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11721',30,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=492&sel_crse_end=492&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,3,'Course','Graduation Project (Implementation)',11723,'ENS 492','34','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11723',30,28), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=499&sel_crse_end=499&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',2,1,'Course','Special Studies II',11745,'ENS 499','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11745',1,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Engineering Optimization',10454,'ENS 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10454',30,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENS&sel_crse_strt=521&sel_crse_end=521&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Hydrogen Energy System',10455,'ENS 521','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10455',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0001&sel_crse_end=0001&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 1',10238,'ENG 0001','1A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10238',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0001&sel_crse_end=0001&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 1',10239,'ENG 0001','1B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10239',20,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0001&sel_crse_end=0001&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 1',10242,'ENG 0001','1C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10242',20,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10251,'ENG 0002','2A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10251',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10253,'ENG 0002','2B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10253',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10255,'ENG 0002','2C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10255',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10258,'ENG 0002','2D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10258',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10264,'ENG 0002','2E1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10264',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10265,'ENG 0002','2F1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10265',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0002&sel_crse_end=0002&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 2',10267,'ENG 0002','2G1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10267',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10290,'ENG 0003','3A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10290',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10292,'ENG 0003','3B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10292',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10293,'ENG 0003','3C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10293',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10295,'ENG 0003','3D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10295',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10296,'ENG 0003','3E1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10296',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10297,'ENG 0003','3F1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10297',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10298,'ENG 0003','3G1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10298',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10299,'ENG 0003','3H1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10299',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10300,'ENG 0003','3J1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10300',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0003&sel_crse_end=0003&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 3',10301,'ENG 0003','3K1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10301',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10304,'ENG 0004','4A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10304',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10305,'ENG 0004','4B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10305',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10306,'ENG 0004','4C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10306',20,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10307,'ENG 0004','4D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10307',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10308,'ENG 0004','4E1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10308',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10309,'ENG 0004','4F1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10309',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10310,'ENG 0004','4G1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10310',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10313,'ENG 0004','4H1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10313',20,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10315,'ENG 0004','4J1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10315',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10316,'ENG 0004','4K1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10316',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10318,'ENG 0004','4L1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10318',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10320,'ENG 0004','4M1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10320',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',10322,'ENG 0004','4N1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10322',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',11600,'ENG 0004','4O1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11600',20,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',11601,'ENG 0004','4P1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11601',20,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=0004&sel_crse_end=0004&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',24,0,'Course','English Route 4',11602,'ENG 0004','4Q1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11602',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10585,'ENG 101','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10585',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10586,'ENG 101','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10586',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10587,'ENG 101','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10587',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10588,'ENG 101','A4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10588',25,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10589,'ENG 101','A5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10589',25,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10590,'ENG 101','A6','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10590',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10591,'ENG 101','A7','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10591',25,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10592,'ENG 101','A8','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10592',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10593,'ENG 101','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10593',22,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10594,'ENG 101','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10594',22,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10595,'ENG 101','B3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10595',22,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10596,'ENG 101','B4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10596',22,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10597,'ENG 101','B5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10597',22,16), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10598,'ENG 101','B6','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10598',22,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10599,'ENG 101','B7','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10599',22,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10600,'ENG 101','B8','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10600',22,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10601,'ENG 101','C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10601',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10602,'ENG 101','C2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10602',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10603,'ENG 101','C3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10603',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10604,'ENG 101','C4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10604',25,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10605,'ENG 101','C5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10605',25,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10606,'ENG 101','C6','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10606',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10607,'ENG 101','C7','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10607',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10608,'ENG 101','C8','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10608',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10609,'ENG 101','D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10609',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10610,'ENG 101','D2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10610',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10611,'ENG 101','D3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10611',25,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10612,'ENG 101','D4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10612',25,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10613,'ENG 101','D5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10613',25,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10614,'ENG 101','D6','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10614',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10615,'ENG 101','D7','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10615',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',10616,'ENG 101','D8','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10616',25,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=101&sel_crse_end=101&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English I',11713,'ENG 101','X','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11713',21,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10623,'ENG 102','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10623',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10624,'ENG 102','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10624',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10625,'ENG 102','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10625',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10620,'ENG 102','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10620',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10621,'ENG 102','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10621',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10622,'ENG 102','B3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10622',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10626,'ENG 102','C1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10626',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10627,'ENG 102','C2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10627',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10628,'ENG 102','C3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10628',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',11280,'ENG 102','C4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11280',26,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10617,'ENG 102','D1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10617',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10618,'ENG 102','D2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10618',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=102&sel_crse_end=102&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',4,3,'Course','Freshman English II',10619,'ENG 102','D3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10619',26,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=300&sel_crse_end=300&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',6,3,'Course','Professional Communication Skills in English',11027,'ENG 300','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11027',23,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=300&sel_crse_end=300&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',6,3,'Course','Professional Communication Skills in English',11028,'ENG 300','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11028',24,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ENG&sel_crse_strt=300&sel_crse_end=300&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',6,3,'Course','Professional Communication Skills in English',11029,'ENG 300','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11029',23,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ES&sel_crse_strt=500&sel_crse_end=500&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',5,0,'Course','Pro - Thesis Seminar',10127,'ES 500','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10127',20,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ES&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master Thesis',10130,'ES 599','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10130',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Financial Management',10007,'FIN 301','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10007',55,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Financial Management',10008,'FIN 301','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10008',51,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Financial Management',10009,'FIN 301R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10009',54,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',0,0,'Recitation','Financial Management',10010,'FIN 301R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10010',52,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=401&sel_crse_end=401&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Corporate Finance',10011,'FIN 401','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10011',50,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=402&sel_crse_end=402&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Investments',10012,'FIN 402','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10012',9999,9910), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=405&sel_crse_end=405&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',6,3,'Course','Corporate Mergers & Acquisitions',10014,'FIN 405','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10014',50,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FIN&sel_crse_strt=621&sel_crse_end=621&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',10,3,'Course','PhD Seminar in Finance V: Research Paper I',11129,'FIN 621','PHD','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11129',5,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=500&sel_crse_end=500&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Financial Accounting and Reporting',11217,'MFIN 500','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11217',25,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Principles of Finance',11218,'MFIN 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11218',25,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=502&sel_crse_end=502&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Corporate Finance',11219,'MFIN 502','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11219',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=504&sel_crse_end=504&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Statistics',11220,'MFIN 504','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11220',25,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=506&sel_crse_end=506&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Modeling in Excel',11221,'MFIN 506','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11221',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Financial Statement Analysis',11177,'MFIN 510','YPE','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11177',25,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Financial Statement Analysis',11222,'MFIN 510','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11222',25,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Portfolio Theory',11223,'MFIN 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11223',25,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=513&sel_crse_end=513&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Money & Banking 1',11224,'MFIN 513','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11224',25,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=514&sel_crse_end=514&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Financial Econometrics',11225,'MFIN 514','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11225',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=520&sel_crse_end=520&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Valuation',11226,'MFIN 520','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11226',25,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=522&sel_crse_end=522&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Derivative Securities',11227,'MFIN 522','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11227',25,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=530&sel_crse_end=530&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',5,1,'Course','Economics for Financial Managers',11228,'MFIN 530','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11228',25,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=591&sel_crse_end=591&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',1,0,'Course','Finance Practicum 1',11229,'MFIN 591','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11229',25,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=MFIN&sel_crse_strt=596&sel_crse_end=596&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FMAN',3,1,'Course','Managerial Skills Development',11230,'MFIN 596','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11230',9999,9943), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FRE&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic French I',11030,'FRE 110','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11030',21,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FRE&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic French I',11031,'FRE 110','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11031',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FRE&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic French I',11032,'FRE 110D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11032',21,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=FRE&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic French I',11033,'FRE 110D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11033',20,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GER&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic German I',11036,'GER 110','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11036',23,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GER&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic German I',11037,'GER 110','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11037',22,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GER&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic German I',11038,'GER 110D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11038',20,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=GER&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic German I',11039,'GER 110D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11039',21,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HART&sel_crse_strt=234&sel_crse_end=234&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Classical Mythology in Art',10140,'HART 234','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10140',66,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HART&sel_crse_strt=292&sel_crse_end=292&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','From Modern to Contemporary Art',10141,'HART 292','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10141',55,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HART&sel_crse_strt=311&sel_crse_end=311&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Renaissance Art',10142,'HART 311','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10142',9999,9951), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HART&sel_crse_strt=414&sel_crse_end=414&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Post 60 Turkish Art',10144,'HART 414','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10144',9999,9954), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HART&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Renaissance Art',10143,'HART 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10143',9999,9951), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HART&sel_crse_strt=514&sel_crse_end=514&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Post 60 Turkish Art',10145,'HART 514','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10145',9999,9954), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=191&sel_crse_end=191&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',4,2,'Course','Principles of Atatürk and the History of the Turkish Revolution I',10629,'HIST 191','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10629',380,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=191&sel_crse_end=191&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',4,2,'Course','Principles of Atatürk and the History of the Turkish Revolution I',10630,'HIST 191','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10630',380,57), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=191&sel_crse_end=191&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',4,2,'Course','Principles of Atatürk and the History of the Turkish Revolution I',10631,'HIST 191','Y','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10631',100,45), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=192&sel_crse_end=192&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',4,2,'Course','Principles of Atatürk and the History of the Turkish Revolution II',10633,'HIST 192','Y','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10633',25,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=192&sel_crse_end=192&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',4,2,'Course','Principles of Atatürk and the History of the Turkish Revolution II',10632,'HIST 192','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10632',210,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=205&sel_crse_end=205&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','History of the Twentieth Century',10146,'HIST 205','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10146',65,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=245&sel_crse_end=245&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Men, Ships and the Sea',11253,'HIST 245','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11253',45,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=331&sel_crse_end=331&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Early Islamic History : A Survey',11118,'HIST 331','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11118',9999,9988), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=349&sel_crse_end=349&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Diplomatic History of the Modern Era II (1945 - 2004)',10147,'HIST 349','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10147',40,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=489&sel_crse_end=489&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','From Empire to Republic : Turkish Nationalism and the Nation - State',10148,'HIST 489','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10148',9999,9973), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=500&sel_crse_end=500&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,0,'Course','M.A. Pro - Seminar',10150,'HIST 500','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10150',20,13), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Explorations in World History I',10151,'HIST 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10151',16,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=517&sel_crse_end=517&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Introduction to Orientalism and Oriental Studies',11125,'HIST 517','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11125',16,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=531&sel_crse_end=531&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Early Islamic History: A Survey',11119,'HIST 531','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11119',9999,9988), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=572&sel_crse_end=572&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Sources and Methods for 17th and 18th century Ottoman History',11120,'HIST 572','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11120',16,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=589&sel_crse_end=589&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','From Empire to Republic : Turkish Nationalism and the Nation - State',10149,'HIST 589','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10149',9999,9973), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=595&sel_crse_end=595&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',20,0,'Course','MA Term Project',10155,'HIST 595','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10155',5,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10157,'HIST 599','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10157',10,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10158,'HIST 599','3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10158',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10159,'HIST 599','4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10159',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=599&sel_crse_end=599&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',35,0,'Course','Master''s Thesis',10160,'HIST 599','5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10160',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=613&sel_crse_end=613&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Readings in Ottoman Legal Culture',11121,'HIST 613','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11121',16,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',119,0,'Course','PhD Thesis',10163,'HIST 699','1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10163',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',119,0,'Course','PhD Thesis',10164,'HIST 699','2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10164',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=699&sel_crse_end=699&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',119,0,'Course','PhD Thesis',10165,'HIST 699','3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10165',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HIST&sel_crse_strt=715&sel_crse_end=715&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Literature Survey: From the Age of Revolution',11755,'HIST 715','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11755',2,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Literature - Myths and Archetypes',10634,'HUM 201','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10634',32,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Literature - Myths and Archetypes',10635,'HUM 201','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10635',32,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202&sel_crse_end=202&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Western Art',10636,'HUM 202','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10636',153,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202D&sel_crse_end=202D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Western Art',10637,'HUM 202D','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10637',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202D&sel_crse_end=202D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Western Art',10638,'HUM 202D','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10638',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202D&sel_crse_end=202D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Western Art',10639,'HUM 202D','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10639',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202D&sel_crse_end=202D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Western Art',10641,'HUM 202D','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10641',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202D&sel_crse_end=202D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Western Art',10642,'HUM 202D','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10642',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=202D&sel_crse_end=202D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Western Art',10643,'HUM 202D','B3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10643',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=203&sel_crse_end=203&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Ottoman Culture',10645,'HUM 203','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10645',51,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=203D&sel_crse_end=203D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Ottoman Culture',10646,'HUM 203D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10646',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=203D&sel_crse_end=203D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Ottoman Culture',10647,'HUM 203D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10647',25,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Classical Music',10648,'HUM 204','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10648',104,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204&sel_crse_end=204&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Classical Music',10649,'HUM 204','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10649',51,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204D&sel_crse_end=204D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Classical Music',10650,'HUM 204D','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10650',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204D&sel_crse_end=204D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Classical Music',10651,'HUM 204D','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10651',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204D&sel_crse_end=204D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Classical Music',10652,'HUM 204D','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10652',28,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204D&sel_crse_end=204D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Classical Music',10653,'HUM 204D','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10653',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204D&sel_crse_end=204D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Classical Music',10654,'HUM 204D','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10654',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=204D&sel_crse_end=204D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Classical Music',10655,'HUM 204D','D','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10655',25,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=206&sel_crse_end=206&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Drama',10656,'HUM 206','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10656',28,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=206&sel_crse_end=206&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Drama',10657,'HUM 206','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10657',27,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=211&sel_crse_end=211&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of 20th Century Literature',10658,'HUM 211','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10658',52,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=211&sel_crse_end=211&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of 20th Century Literature',10659,'HUM 211','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10659',52,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=212&sel_crse_end=212&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Modern Art',10660,'HUM 212','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10660',104,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=212D&sel_crse_end=212D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Modern Art',10661,'HUM 212D','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10661',27,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=212D&sel_crse_end=212D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Modern Art',10662,'HUM 212D','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10662',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=212D&sel_crse_end=212D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Modern Art',10663,'HUM 212D','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10663',26,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=212D&sel_crse_end=212D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of Modern Art',10664,'HUM 212D','B2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10664',25,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=214&sel_crse_end=214&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of the Opera',10665,'HUM 214','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10665',51,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=214D&sel_crse_end=214D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of the Opera',10666,'HUM 214D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10666',26,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=214D&sel_crse_end=214D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','Major Works of the Opera',10667,'HUM 214D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10667',25,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=231&sel_crse_end=231&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Poetry',10668,'HUM 231','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10668',30,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=241&sel_crse_end=241&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Short Fiction',10669,'HUM 241','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10669',51,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=HUM&sel_crse_strt=241&sel_crse_end=241&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Major Works of Short Fiction',10670,'HUM 241','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10670',52,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,4,'Course','Deterministic Models in Operations Research',10938,'IE 301','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10938',90,62), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,4,'Course','Deterministic Models in Operations Research',10939,'IE 301','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10939',90,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Deterministic Models in OR',10940,'IE 301R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10940',36,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Deterministic Models in OR',10941,'IE 301R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10941',36,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Deterministic Models in OR',10942,'IE 301R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10942',54,26), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=301R&sel_crse_end=301R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Deterministic Models in OR',10944,'IE 301R','A5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10944',54,36), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302&sel_crse_end=302&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,4,'Course','Stochastic Models in Operations Research',10456,'IE 302','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10456',111,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302&sel_crse_end=302&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,4,'Course','Stochastic Models in Operations Research',10457,'IE 302','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10457',90,24), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Stochastic Models in Operations Research',10458,'IE 302R','AB1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10458',36,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Stochastic Models in Operations Research',10459,'IE 302R','AB2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10459',37,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Stochastic Models in Operations Research',10460,'IE 302R','AB3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10460',39,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Stochastic Models in Operations Research',10461,'IE 302R','BA1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10461',30,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Stochastic Models in Operations Research',10462,'IE 302R','BA2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10462',30,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=302R&sel_crse_end=302R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Stochastic Models in Operations Research',10463,'IE 302R','BA3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10463',30,11), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=303&sel_crse_end=303&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Decision Economics',10464,'IE 303','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10464',200,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=303R&sel_crse_end=303R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Economics',10465,'IE 303R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10465',67,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=303R&sel_crse_end=303R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Economics',10466,'IE 303R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10466',67,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=303R&sel_crse_end=303R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Economics',10467,'IE 303R','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10467',66,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304&sel_crse_end=304&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Production and Service Systems Planning and Design',10468,'IE 304','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10468',110,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304&sel_crse_end=304&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Production and Service Systems Planning and Design',10469,'IE 304','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10469',90,35), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304R&sel_crse_end=304R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Planning and Design',10470,'IE 304R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10470',41,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304R&sel_crse_end=304R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Planning and Design',10471,'IE 304R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10471',40,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304R&sel_crse_end=304R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Planning and Design',10472,'IE 304R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10472',40,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304R&sel_crse_end=304R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Planning and Design',10473,'IE 304R','A4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10473',40,18), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=304R&sel_crse_end=304R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Planning and Design',10474,'IE 304R','A5','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10474',40,22), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=305&sel_crse_end=305&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Simulation',10475,'IE 305','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10475',90,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=305&sel_crse_end=305&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Simulation',10476,'IE 305','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10476',90,25), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=305R&sel_crse_end=305R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Simulation',10477,'IE 305R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10477',90,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=305R&sel_crse_end=305R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Simulation',10478,'IE 305R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10478',90,25), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=309&sel_crse_end=309&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Manufacturing Processes I',10479,'IE 309','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10479',150,34), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=309R&sel_crse_end=309R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Manufacturing Processes I',10480,'IE 309R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10480',38,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=309R&sel_crse_end=309R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Manufacturing Processes I',10481,'IE 309R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10481',37,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=309R&sel_crse_end=309R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Manufacturing Processes I',10482,'IE 309R','B1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10482',50,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=401&sel_crse_end=401&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Production and Service Systems Operations',10484,'IE 401','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10484',90,37), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=401&sel_crse_end=401&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Production and Service Systems Operations',10485,'IE 401','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10485',90,62), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=401R&sel_crse_end=401R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Operations',10486,'IE 401R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10486',36,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=401R&sel_crse_end=401R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Operations',10487,'IE 401R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10487',36,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=401R&sel_crse_end=401R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Production and Service Systems Operations',10488,'IE 401R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10488',108,95), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=402&sel_crse_end=402&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',8,4,'Course','Integrated Manufacturing Systems',10491,'IE 402','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10491',102,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=402L&sel_crse_end=402L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Integrated Manufacturing Systems',10492,'IE 402L','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10492',34,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=402L&sel_crse_end=402L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Integrated Manufacturing Systems',10493,'IE 402L','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10493',34,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=402L&sel_crse_end=402L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Integrated Manufacturing Systems',10494,'IE 402L','C','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10494',37,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=403&sel_crse_end=403&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Quality Planning and Control',10495,'IE 403','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10495',119,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=403R&sel_crse_end=403R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Quality Planning and Control',10496,'IE 403R','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10496',77,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=403R&sel_crse_end=403R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Quality Planning and Control',10497,'IE 403R','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10497',58,20), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=405&sel_crse_end=405&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Decision Analysis',10498,'IE 405','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10498',115,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=405R&sel_crse_end=405R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Analysis',10499,'IE 405R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10499',31,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=405R&sel_crse_end=405R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Analysis',10500,'IE 405R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10500',30,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=405R&sel_crse_end=405R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Analysis',11157,'IE 405R','A3','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11157',30,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=405R&sel_crse_end=405R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Decision Analysis',11702,'IE 405R','A4','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11702',24,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=407&sel_crse_end=407&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Investment Decision Making',10501,'IE 407','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10501',9999,9910), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=408&sel_crse_end=408&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Reliability and Maintenance Analysis',10502,'IE 408','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10502',60,41), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=409&sel_crse_end=409&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Project Scheduling and Management',11158,'IE 409','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11158',75,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=409R&sel_crse_end=409R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Project Scheduling and Management',11192,'IE 409R','A1','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11192',39,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=409R&sel_crse_end=409R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Project Scheduling and Management',11193,'IE 409R','A2','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11193',38,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=413&sel_crse_end=413&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Information Systems',10503,'IE 413','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10503',61,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=413R&sel_crse_end=413R&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Recitation','Information Systems',10504,'IE 413R','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10504',61,1), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=430&sel_crse_end=430&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Logistics Systems Planning and Design',10506,'IE 430','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10506',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=454&sel_crse_end=454&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Supply Chain Analysis',10508,'IE 454','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10508',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=471&sel_crse_end=471&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',5,3,'Course','Supply Chain Practice',10509,'IE 471','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10509',50,19), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=472&sel_crse_end=472&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',5,3,'Course','Strategic Decision Making Practice',10510,'IE 472','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10510',31,2), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Linear Programming and Extensions',10511,'IE 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10511',40,25), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=512&sel_crse_end=512&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Graph Theory and Network Flows',10512,'IE 512','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10512',20,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=525&sel_crse_end=525&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Operations Research and Data Mining',10516,'IE 525','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10516',25,5), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=551&sel_crse_end=551&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',1,0,'Course','Graduate Seminar I',11552,'IE 551','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11552',50,40), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=552&sel_crse_end=552&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',1,0,'Course','Graduate Seminar II',11553,'IE 552','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11553',50,46), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=565&sel_crse_end=565&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Machine Tool Engineering',10513,'IE 565','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10513',20,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=565L&sel_crse_end=565L&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',0,0,'Lab','Machine Tool Engineering',10514,'IE 565L','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10514',20,12), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=566&sel_crse_end=566&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Computer - Aided Biomodeling and Fabrication',10515,'IE 566','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10515',15,10), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=58000&sel_crse_end=58000&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Special Topics in IE: Logistics and Transportation Planning',11711,'IE 58000','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11711',9999,9984), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=58001&sel_crse_end=58001&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',10,3,'Course','Special Topics in IE: Simulation for Statistical Inference',11712,'IE 58001','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11712',30,11), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11430,'IE 590','01','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11430',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11431,'IE 590','02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11431',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11433,'IE 590','03','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11433',10,4), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11436,'IE 590','05','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11436',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11442,'IE 590','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11442',10,7), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11443,'IE 590','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11443',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11445,'IE 590','09','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11445',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11448,'IE 590','11','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11448',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11450,'IE 590','12','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11450',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11451,'IE 590','13','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11451',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=590&sel_crse_end=590&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',50,0,'Course','Master Thesis',11455,'IE 590','16','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11455',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=751&sel_crse_end=751&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',1,0,'Course','Graduate Seminar I',11537,'IE 751','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11537',50,49), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D. Dissertation',11458,'IE 790','01','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11458',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D. Dissertation',11460,'IE 790','02','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11460',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D. Dissertation',11462,'IE 790','04','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11462',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D. Dissertation',11467,'IE 790','07','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11467',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D. Dissertation',11470,'IE 790','08','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11470',10,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IE&sel_crse_strt=790&sel_crse_end=790&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',180,0,'Course','Ph.D. Dissertation',11473,'IE 790','10','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11473',10,8), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IT&sel_crse_strt=501&sel_crse_end=501&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Introduction to Computer Programming',11569,'IT 501','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11569',35,16), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IT&sel_crse_strt=511&sel_crse_end=511&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Fundamentals of Data Communications and TCP/IP Networking',11573,'IT 511','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11573',35,15), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IT&sel_crse_strt=524&sel_crse_end=524&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',7,3,'Course','Programming with Java',11575,'IT 524','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11575',35,15), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IT&sel_crse_strt=525&sel_crse_end=525&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Advanced Java Programming',11608,'IT 525','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11608',20,18), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IT&sel_crse_strt=553&sel_crse_end=553&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Database Design, Management and Administration',11570,'IT 553','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11570',35,14), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IT&sel_crse_strt=592&sel_crse_end=592&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',30,0,'Course','Project Course',11579,'IT 592','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11579',35,31), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IF&sel_crse_strt=200&sel_crse_end=200&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FENS',6,3,'Course','Fantasy, Reality, Science and Society',10518,'IF 200','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10518',300,145), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IR&sel_crse_strt=201&sel_crse_end=201&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','International Relations Theory',11002,'IR 201','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11002',61,9), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IR&sel_crse_strt=201D&sel_crse_end=201D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','International Relations Theory',11003,'IR 201D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11003',31,6), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IR&sel_crse_strt=201D&sel_crse_end=201D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',0,0,'Discussion','International Relations Theory',11004,'IR 201D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11004',30,3), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IR&sel_crse_strt=301&sel_crse_end=301&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Globalization and International Relations',10170,'IR 301','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10170',40,19), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IR&sel_crse_strt=391&sel_crse_end=391&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','International Political Economy',10171,'IR 391','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10171',40,30), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=IR&sel_crse_strt=410&sel_crse_end=410&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','International Security',10172,'IR 410','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10172',30,17), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ITA&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic Italian I',11042,'ITA 110','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11042',16,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=ITA&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Italian I',11043,'ITA 110D','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11043',16,0), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic Latin I',11047,'LAT 110','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11047',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=110&sel_crse_end=110&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Basic Latin I',11048,'LAT 110','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11048',9999,9981), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Latin I',11051,'LAT 110D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11051',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=110D&sel_crse_end=110D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Latin I',11052,'LAT 110D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11052',9999,9981), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=140&sel_crse_end=140&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',8,3,'Course','Intermediate Latin II',11055,'LAT 140','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11055',9999,9976), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=140D&sel_crse_end=140D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Intermediate Latin II',11057,'LAT 140D','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11057',9999,9976), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',10,3,'Course','Basic Latin I',11049,'LAT 510','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11049',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=510&sel_crse_end=510&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',10,3,'Course','Basic Latin I',11050,'LAT 510','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11050',9999,9981), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=510D&sel_crse_end=510D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Latin I',11053,'LAT 510D','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11053',9999,9980), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=510D&sel_crse_end=510D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Basic Latin I',11054,'LAT 510D','B','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11054',9999,9981), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=540&sel_crse_end=540&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',10,3,'Course','Intermediate Latin II',11056,'LAT 540','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11056',9999,9976), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LAT&sel_crse_strt=540D&sel_crse_end=540D&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','SL',0,0,'Discussion','Intermediate Latin I',11058,'LAT 540D','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=11058',9999,9976), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LIT&sel_crse_strt=345&sel_crse_end=345&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',6,3,'Course','Gender and Sexuality in Literature',10173,'LIT 345','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10173',9999,9964), ('http://suis.sabanciuniv.edu/prod/bwckctlg.p_display_courses?term_in=201601&one_subj=LIT&sel_crse_strt=545&sel_crse_end=545&sel_subj=&sel_levl=&sel_schd=&sel_coll=&sel_divs=&sel_dept=&sel_attr=','Fall 2016-2017','FASS',10,3,'Course','Gender and Sexuality in Literature',10174,'LIT 545','0','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10174',9999,9964), (NULL,'Fall 2016-2017','FASS',1,NULL,'Course','Majors: Informative Course',10671,'MJC 100','A','http://suis.sabanciuniv.edu/prod/bwckschd.p_disp_detail_sched?term_in=201601&crn_in=10671',115,2); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `requirements` ( `code` VARCHAR(16) NOT NULL, `requirement` VARCHAR(16) NOT NULL, PRIMARY KEY (`code`, `requirement`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `requirements` (`code`, `requirement`) VALUES ('ECON 340','ECON 202'), ('CS 300','CS 204'), ('CONF 599','CONF 501'), ('IE 302','MATH 203'), ('IE 304R','IE 304'), ('HIST 245','SPS 101'), ('IE 305','MATH 306'), ('GR 503E','GR 501E'), ('IE 401','MS 304'), ('IE 402','MS 309'), ('ACC 301R','ACC 301'), ('LAT 110D','LAT 110'), ('LAT 140D','LAT 140'), ('ENS 203','MATH 102'), ('ARA 510D','ARA 510'), ('ENS 492','ENS 491'), ('IE 301','IE 301R'), ('EE 307','ENS 203'), ('ECON 320','ECON 204'), ('IE 304','IE 304R'), ('CS 300R','CS 300'), ('ECON 201R','ECON 201'), ('CS 307','CS 307R'), ('IE 403R','IE 403'), ('ENS 204','MATH 102'), ('ECON 485','ECON 485R'), ('CS 204L','CS 204'), ('CS 307R','CS 307'), ('CS 400','MATH 204'), ('FIN 301R','FIN 301'), ('IE 454','OPIM 450'), ('HUM 203','SPS'), ('IE 405','IE 405R'), ('IE 405R','IE 405'), ('ENS 209','ENS 209L'), ('IE 304','IE 301'), ('EE 401','CS 303'), ('LAT 140','LAT 130'), ('IE 454','IE 401'), ('ENS 211','MATH 101'), ('IE 301','MATH 201'), ('ECON 202R','ECON 202'), ('ECON 202','ECON 202R'), ('IE 401','IE 304'), ('IE 409','IE 409R'), ('IE 565L','IE 565'), ('CS 402','CS 300'), ('CULT 432','HUM 201'), ('EE 407','EE 407R'), ('IE 303','IE 303R'), ('LAT 140','LAT 140D'), ('ENS 202','MATH 102'), ('HUM 214D','HUM 214'), ('LAT 110','LAT 110D'), ('ENS 209R','ENS 209'), ('ACC 301','MGMT 202'), ('IE 305R','IE 305'), ('CS 408L','CS 408'), ('ARA 130','ARA 302'), ('ENS 202','ENS 202R'), ('HUM 212D','HUM 212'), ('ENS 211R','ENS 211'), ('ENS 208','ENS 208R'), ('EE 311','EE 311R'), ('IE 454','MS 401'), ('CS 307','CS 300'), ('ARA 130','ARA 120'), ('IR 301','SPS 102'), ('ARA 530D','ARA 530'), ('EE 413','TE 304'), ('ENS 499','ENS 491'), ('EE 403R','EE 403'), ('IE 403','IE 403R'), ('GR 503E','GR 502E'), ('ECON 301','ECON 204'), ('IE 301R','IE 301'), ('IR 410','IR 201'), ('HUM 206','SPS'), ('ECON 204','ECON 204R'), ('HUM 211','SPS'), ('EE 417','EE 417L'), ('EE 417L','EE 417'), ('IE 304','MS 301'), ('IE 309R','IE 309'), ('HIST 331','SPS 101'), ('ECON 401','ECON 301'), ('HUM 214','SPS'), ('GR 502M','GR 501M'), ('IE 305','IE 305R'), ('IE 565','IE 565L'), ('ENS 205','MATH 102'), ('ENS 499','ENS 492'), ('ECON 501R','ECON 501'), ('ECON 405','ECON 204'), ('HIST 349','SPS 101'), ('HUM 204D','HUM 204'), ('IE 430','IE 301'), ('ECON 405','ECON 201'), ('ARA 130','ARA 130D'), ('ARA 110','ARA 110D'), ('CS 405','CS 202'), ('CONF 593','CONF 512'), ('IE 302','IE 302R'), ('HIST 489','SPS 102'), ('IE 309','ENS 205'), ('FRE 110D','FRE 110'), ('IE 409','MS 301'), ('IE 402L','IE 402'), ('CONF 593','CONF 501'), ('EE 307R','EE 307'), ('CS 307','CS 204'), ('ECON 201','ECON 201R'), ('FIN 301','FIN 301R'), ('ENS 205R','ENS 205'), ('EE 313','EE 313R'), ('LAT 540','LAT 540D'), ('GR 503E','GR 555E'), ('ACC 301','ACC 301R'), ('ECON 301','MATH 306'), ('ECON 503','ECON 503R'), ('IE 303R','IE 303'), ('ACC 201R','ACC 201'), ('IE 403','MATH 306'), ('EE 413R','EE 413'), ('IE 454','OPIM 401'), ('HUM 201','SPS'), ('IE 302','MS 301'), ('ARA 110D','ARA 110'), ('ECON 505','ECON 505R'), ('ECON 204R','ECON 204'), ('HUM 241','SPS'), ('CHEM 301','CHEM 301L'), ('IE 301','ENS 208'), ('IE 471','MS 401'), ('HIST 205','SPS 102'), ('IE 408','MS 304'), ('ACC 201','ACC 201R'), ('IR 391','IR 201'), ('ENS 204R','ENS 204'), ('FIN 401','FIN 301'), ('HIST 489','SPS 101'), ('IR 201','IR 201D'), ('ACC 403','ACC 201'), ('EE 407R','EE 407'), ('GER 110D','GER 110'), ('GR 502E','GR 501E'), ('EE 307','EE 307R'), ('ENS 204','NS 101'), ('ENS 209L','ENS 209'), ('ECON 370','ECON 201'), ('IE 430','MS 301'), ('GR 503E','ENS 555'), ('ENG 102','ENG 101'), ('ECON 340','ECON 204'), ('ECON 607','MATH 571'), ('EE 303','EE 202'), ('IE 413','IE 413R'), ('CS 402','CS 305'), ('LAT 510','LAT 510D'), ('ECON 485R','ECON 485'), ('CS 201R','CS 201'), ('CS 307','CS 202'), ('CS 402','CS 202'), ('HUM 203D','HUM 203'), ('IE 409','IE 301'), ('ARA 530','ARA 502'), ('ENS 491R','ENS 491'), ('IE 407','IE 303'), ('ECON 505R','ECON 505'), ('IE 402','IE 402L'), ('IE 402','IE 309'), ('ECON 301','ECON 301R'), ('IE 302R','IE 302'), ('EE 313R','EE 313'), ('ENS 211','ENS 211R'), ('EE 303','EL 202'), ('HUM 212','SPS'), ('ITA 110','ITA 110D'), ('ECON 320','ECON 202'), ('EE 413','EE 314'), ('EE 303','EE 303R'), ('EE 409R','EE 409'), ('IE 302','IE 301'), ('CS 303L','CS 303'), ('IR 301','IR 201'), ('HUM 204','SPS'), ('LAT 510D','LAT 510'), ('FIN 402','MS 407'), ('EE 311R','EE 311'), ('CS 405','CS 405L'), ('LAT 540','LAT 530'), ('HIST 205','SPS 101'), ('HUM 214','HUM 214D'), ('CS 303L','CS 303R'), ('CS 303','CS 303L'), ('GER 110','GER 110D'), ('IR 391','ECON 202'), ('IE 409','MS 303'), ('EE 303R','EE 303'), ('ECON 481R','ECON 481'), ('ENS 205','NS 102'), ('ENS 202','NS 101'), ('HIST 589','HIST 689'), ('HUM 231','SPS'), ('CS 303','CS 303R'), ('CS 303R','CS 303'), ('ECON 481','ECON 481R'), ('ARA 510','ARA 510D'), ('FIN 405','FIN 301'), ('IE 409R','IE 409'), ('CS 302R','CS 302'), ('EE 311','ENS 211'), ('EE 414','CS 201'), ('HUM 203','HUM 203D'), ('EE 417','CS 201'), ('IE 408','IE 304'), ('CS 204','CS 201'), ('ARA 530','ARA 530D'), ('ENS 202','NS 102'), ('EE 409','EE 409R'), ('ACC 403','MGMT 202'), ('LAT 540D','LAT 540'), ('CS 300','CS 300R'), ('HUM 212','HUM 212D'), ('ENS 203','ENS 203R'), ('IR 410','SPS 102'), ('IR 201','SPS 101'), ('HUM 202','SPS'), ('IE 401','IE 401R'), ('IE 413R','IE 413'), ('EE 403','NS 101'), ('HIST 245','SPS 102'), ('CS 408','CS 408L'), ('HART 311','HUM 202'), ('IR 201D','IR 201'), ('CS 302','CS 302R'), ('ECON 501','ECON 501R'), ('HUM 204','HUM 204D'), ('EE 407','EL 204'), ('ARA 530','ARA 520'), ('HIST 192','HIST 191'), ('EE 407','EE 307'), ('IE 309','IE 309R'), ('ENS 209','ENS 209R'), ('ENS 204','ENS 204R'), ('CHEM 301L','CHEM 301'), ('ENS 208R','ENS 208'), ('EE 403','EE 403R'), ('HUM 202','HUM 202D'), ('CS 405L','CS 405'), ('EE 401L','EE 401'), ('EE 414R','EE 414'), ('ENS 491','ENS 491R'), ('HUM 202D','HUM 202'), ('IE 402','ENS 209'), ('IE 407','MS 303'), ('CS 402','CS 204'), ('IE 405','MATH 306'), ('EE 401','EL 302'), ('CULT 432','CULT 201'), ('CONF 599','CONF 531'), ('ECON 503R','ECON 503'), ('FIN 402','FIN 301'), ('EE 414','EE 414R'), ('CS 303R','CS 303L'), ('CS 408','CS 201'), ('EE 413','EE 413R'), ('HIST 331','SPS 102'), ('CONF 593','CONF 531'), ('ECON 370','ECON 204'), ('ENS 202R','ENS 202'), ('CONF 599','CONF 512'), ('ENS 205','ENS 205R'), ('FIN 402','IE 407'), ('IE 407','FIN 402'), ('ENS 203R','ENS 203'), ('IR 391','SPS 101'), ('HIST 349','SPS 102'), ('EE 401','EE 401L'), ('CS 201','CS 201R'), ('IR 391','SPS 102'), ('CS 204','CS 204L'), ('ACC 301','ACC 201'), ('EE 401','EE 302'), ('EE 409','ENS 201'), ('ECON 320','ECON 201'), ('IR 410','SPS 101'), ('IR 201','SPS 102'), ('CS 405','CS 300'), ('ECON 301R','ECON 301'), ('FRE 110','FRE 110D'), ('IR 301','SPS 101'), ('IE 552','IE 551'), ('IE 471','IE 401'), ('ENS 202','MATH 101'), ('IE 408','MATH 306'), ('IE 409','IE 303'), ('IE 401R','IE 401'), ('EE 313','ENS 211'), ('ITA 110D','ITA 110'), ('ARA 130D','ARA 130'); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `meetings` ( `m_id` INT NOT NULL, `cdn` INT NOT NULL, `term` VARCHAR(16) NOT NULL, `day` VARCHAR(1), `room` VARCHAR(50), `start_time` TIME, `end_time` TIME, `start_date` DATETIME, `end_date` DATETIME, `schedule_type` VARCHAR(20) NOT NULL, PRIMARY KEY (`m_id`), FOREIGN KEY (`cdn`, `term`) REFERENCES courses(`cdn`, `term`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `meetings` (`start_time`, `end_time`, `day`, `room`, `start_date`, `end_date`, `schedule_type`, `m_id`, `cdn`, `term`) VALUES ('10:40','13:30','T','School of Management G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',0,10001,'Fall 2016-2017'), ('14:40','17:30','T','School of Management G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1,10002,'Fall 2016-2017'), ('11:40','14:30','W','School of Management L018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',2,10003,'Fall 2016-2017'), ('15:40','16:30','F','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',3,10977,'Fall 2016-2017'), ('16:40','17:30','F','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',4,10978,'Fall 2016-2017'), ('13:40','14:30','F','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',5,10979,'Fall 2016-2017'), ('14:40','15:30','F','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',6,10980,'Fall 2016-2017'), ('11:40','24:30','F','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',7,10981,'Fall 2016-2017'), ('24:40','13:30','F','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',8,10982,'Fall 2016-2017'), ('14:40','17:30','R','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',9,10004,'Fall 2016-2017'), ('11:40','24:30','F','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',10,10005,'Fall 2016-2017'), ('8:40','11:30','F','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',11,10006,'Fall 2016-2017'), ('18:00','21:00','F','School of Management G060','2016-12-23 00:00:00','2017-01-21 00:00:00','1st del',12,11162,'Fall 2016-2017'), ('9:00','17:00','S','School of Management G060','2016-12-23 00:00:00','2017-01-21 00:00:00','2nd del',13,11162,'Fall 2016-2017'), ('13:40','16:30','W','School of Management G013-14','2016-09-21 00:00:00','2016-12-21 00:00:00','1st del',14,11194,'Fall 2016-2017'), ('18:00','22:00','F',NULL,'2016-09-23 00:00:00','2016-10-15 00:00:00','Lecture',15,11185,'Fall 2016-2017'), ('14:40','16:30','S','School of Management 1099','2016-10-01 00:00:00','2016-10-01 00:00:00','Lecture',16,11185,'Fall 2016-2017'), ('14:40','16:30','S','School of Management 1099','2016-10-15 00:00:00','2016-10-15 00:00:00','Lecture',17,11185,'Fall 2016-2017'), ('9:40','13:30','S','School of Management L018','2016-09-23 00:00:00','2016-10-15 00:00:00','Lecture',18,11184,'Fall 2016-2017'), ('14:40','16:30','S','School of Management 1099','2016-10-01 00:00:00','2016-10-01 00:00:00','Lecture',19,11184,'Fall 2016-2017'), ('14:40','16:30','S','School of Management 1099','2016-10-15 00:00:00','2016-10-15 00:00:00','Lecture',20,11184,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',21,11297,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',22,11137,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',23,10137,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',24,11298,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',25,11138,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',26,10138,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',27,11299,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',28,10139,'Fall 2016-2017'), ('10:40','13:30','M','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',29,11146,'Fall 2016-2017'), ('10:40','13:30','T','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',30,11147,'Fall 2016-2017'), ('10:40','13:30','R','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',31,11148,'Fall 2016-2017'), ('8:40','11:30','T','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',32,11015,'Fall 2016-2017'), ('13:40','16:30','R','School of Languages Building G023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',33,11016,'Fall 2016-2017'), ('11:40','13:30','R','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',34,11019,'Fall 2016-2017'), ('14:40','16:30','T','School of Languages Building G018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',35,11020,'Fall 2016-2017'), ('8:40','11:30','R','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',36,11023,'Fall 2016-2017'), ('24:40','14:30','T','School of Languages Building G018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',37,11025,'Fall 2016-2017'), ('8:40','11:30','T','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',38,11017,'Fall 2016-2017'), ('13:40','16:30','R','School of Languages Building G023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',39,11018,'Fall 2016-2017'), ('11:40','13:30','R','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',40,11021,'Fall 2016-2017'), ('14:40','16:30','T','School of Languages Building G018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',41,11022,'Fall 2016-2017'), ('8:40','11:30','R','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',42,11024,'Fall 2016-2017'), ('24:40','14:30','T','School of Languages Building G018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',43,11026,'Fall 2016-2017'), ('18:30','21:30','T','Karaköy Communication Center','2016-10-11 00:00:00','2016-12-06 00:00:00','Lecture',44,11728,'Fall 2016-2017'), ('18:30','21:30','R','Karaköy Communication Center','2016-12-22 00:00:00','2016-12-22 00:00:00','Lecture',45,11728,'Fall 2016-2017'), ('18:30','21:30','T','Karaköy Communication Center','2016-12-27 00:00:00','2016-12-27 00:00:00','Lecture',46,11728,'Fall 2016-2017'), ('18:30','21:30','R','Karaköy Communication Center','2016-12-29 00:00:00','2016-12-29 00:00:00','Lecture',47,11728,'Fall 2016-2017'), ('10:00','17:00','S',NULL,'2016-11-26 00:00:00','2016-12-03 00:00:00','Lecture',48,11730,'Fall 2016-2017'), ('18:30','21:30','R','Karaköy Communication Center','2017-01-05 00:00:00','2017-01-12 00:00:00','Lecture',49,11730,'Fall 2016-2017'), ('10:00','17:00','S',NULL,'2017-01-07 00:00:00','2017-01-14 00:00:00','Lecture',50,11730,'Fall 2016-2017'), ('18:30','21:30','R','Karaköy Communication Center','2016-12-08 00:00:00','2016-12-15 00:00:00','Lecture',51,11731,'Fall 2016-2017'), ('10:00','17:00','S',NULL,'2016-12-10 00:00:00','2016-12-17 00:00:00','Lecture',52,11731,'Fall 2016-2017'), ('18:30','21:30','T','Karaköy Communication Center','2016-12-13 00:00:00','2016-12-20 00:00:00','Lecture',53,11731,'Fall 2016-2017'), ('10:00','17:00','S',NULL,'2016-10-08 00:00:00','2016-11-19 00:00:00','1st del',54,11727,'Fall 2016-2017'), ('18:30','21:30','F',NULL,'2016-11-18 00:00:00','2016-11-18 00:00:00','2nd del',55,11727,'Fall 2016-2017'), ('18:30','21:30','R',NULL,'2016-10-13 00:00:00','2016-11-24 00:00:00','Lecture',56,11737,'Fall 2016-2017'), ('9:40','24:30','M','School of Management G041','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',57,11152,'Fall 2016-2017'), ('13:40','16:30','R','School of Management G041','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',58,11153,'Fall 2016-2017'), ('24:40','14:30','F','School of Management G041','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',59,11238,'Fall 2016-2017'), ('15:40','16:30','M','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',60,10387,'Fall 2016-2017'), ('13:40','15:30','T','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',61,10387,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',62,11122,'Fall 2016-2017'), ('9:40','11:30','T','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',63,10389,'Fall 2016-2017'), ('9:40','10:30','R','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',64,10389,'Fall 2016-2017'), ('9:40','11:30','T','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',65,10390,'Fall 2016-2017'), ('9:40','10:30','R','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',66,10390,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',67,10847,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',68,10848,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',69,11564,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',70,11565,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',71,11566,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',72,11567,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',73,11568,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',74,11571,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',75,11572,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',76,11574,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',77,11576,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',78,11577,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',79,11578,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',80,11580,'Fall 2016-2017'), ('15:40','18:30','T',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',81,11581,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',82,11582,'Fall 2016-2017'), ('13:40','16:30','T',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',83,11583,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',84,11584,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',85,11585,'Fall 2016-2017'), ('13:40','16:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',86,11586,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',87,11587,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',88,11588,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',89,11589,'Fall 2016-2017'), ('24:40','15:30','F',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',90,11590,'Fall 2016-2017'), ('19:40','21:30','T',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',91,11591,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',92,11592,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',93,11593,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',94,11594,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',95,11595,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',96,11596,'Fall 2016-2017'), ('24:40','15:30','T',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',97,11597,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',98,11598,'Fall 2016-2017'), ('24:40','15:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',99,11609,'Fall 2016-2017'), ('13:40','16:30','T',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',100,11732,'Fall 2016-2017'), ('24:40','15:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',101,11733,'Fall 2016-2017'), ('24:40','15:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',102,11734,'Fall 2016-2017'), ('15:40','18:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',103,11735,'Fall 2016-2017'), ('24:40','15:30','F',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',104,11736,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',105,10916,'Fall 2016-2017'), ('24:40','13:30','T','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',106,10916,'Fall 2016-2017'), ('9:40','24:30','R','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',107,10917,'Fall 2016-2017'), ('9:40','24:30','R','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',108,10918,'Fall 2016-2017'), ('9:40','24:30','R','School of Management G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',109,10919,'Fall 2016-2017'), ('9:40','24:30','R','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',110,10920,'Fall 2016-2017'), ('16:40','19:30','R','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',111,10921,'Fall 2016-2017'), ('16:40','19:30','R','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',112,10922,'Fall 2016-2017'), ('16:40','19:30','R','School of Management G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',113,10923,'Fall 2016-2017'), ('16:40','19:30','R','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',114,10924,'Fall 2016-2017'), ('16:40','19:30','R','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',115,11703,'Fall 2016-2017'), ('9:40','24:30','F','School of Management G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',116,10925,'Fall 2016-2017'), ('9:40','24:30','F','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',117,10926,'Fall 2016-2017'), ('9:40','24:30','F','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',118,10927,'Fall 2016-2017'), ('9:40','24:30','F','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',119,10928,'Fall 2016-2017'), ('24:40','15:30','F','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',120,10929,'Fall 2016-2017'), ('24:40','15:30','F','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',121,10930,'Fall 2016-2017'), ('24:40','15:30','F','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',122,10931,'Fall 2016-2017'), ('24:40','15:30','F','School of Management L018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',123,10932,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',124,10933,'Fall 2016-2017'), ('24:40','13:30','T','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',125,10933,'Fall 2016-2017'), ('11:40','13:30','F','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',126,10934,'Fall 2016-2017'), ('11:40','13:30','F','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',127,10935,'Fall 2016-2017'), ('13:40','15:30','F','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',128,10936,'Fall 2016-2017'), ('13:40','15:30','F','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',129,10937,'Fall 2016-2017'), ('10:40','24:30','R','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',130,10391,'Fall 2016-2017'), ('14:40','15:30','F','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',131,10391,'Fall 2016-2017'), ('15:40','17:30','F','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',132,10392,'Fall 2016-2017'), ('14:40','16:30','T','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',133,10393,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',134,10393,'Fall 2016-2017'), ('15:40','16:30','W','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',135,11126,'Fall 2016-2017'), ('24:40','15:30','W','School of Management 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',136,10394,'Fall 2016-2017'), ('8:40','10:30','F','Fac. of Engin. and Nat. Sci. 1033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',137,10395,'Fall 2016-2017'), ('17:40','19:30','W','Fac. of Engin. and Nat. Sci. 1033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',138,10396,'Fall 2016-2017'), ('13:40','15:30','R','Fac. of Engin. and Nat. Sci. 1033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',139,10397,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. 1033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',140,10398,'Fall 2016-2017'), ('15:40','17:30','R','Fac. of Engin. and Nat. Sci. 1033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',141,10399,'Fall 2016-2017'), ('17:40','19:30','F','Fac. of Engin. and Nat. Sci. 1033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',142,10400,'Fall 2016-2017'), ('16:40','17:30','W','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',143,10401,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',144,10402,'Fall 2016-2017'), ('10:40','11:30','T','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',145,10402,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',146,10403,'Fall 2016-2017'), ('9:40','10:30','T','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',147,10404,'Fall 2016-2017'), ('14:40','16:30','R','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',148,10404,'Fall 2016-2017'), ('15:40','17:30','M','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',149,10406,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',150,10406,'Fall 2016-2017'), ('10:40','11:30','M','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',151,10407,'Fall 2016-2017'), ('15:40','17:30','T','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',152,10407,'Fall 2016-2017'), ('24:40','14:30','F','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',153,10408,'Fall 2016-2017'), ('11:40','13:30','M','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',154,10409,'Fall 2016-2017'), ('11:40','24:30','T','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',155,10409,'Fall 2016-2017'), ('8:40','10:30','F','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',156,10410,'Fall 2016-2017'), ('8:40','10:30','F','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',157,10411,'Fall 2016-2017'), ('17:40','19:30','F','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',158,10412,'Fall 2016-2017'), ('9:40','10:30','T','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',159,10405,'Fall 2016-2017'), ('14:40','16:30','R','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',160,10405,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',161,11697,'Fall 2016-2017'), ('14:40','15:30','T','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',162,11697,'Fall 2016-2017'), ('11:40','13:30','T','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',163,10413,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',164,10413,'Fall 2016-2017'), ('9:40','10:30','M','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',165,10414,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',166,10414,'Fall 2016-2017'), ('11:40','13:30','M','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',167,10415,'Fall 2016-2017'), ('16:40','17:30','T','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',168,10415,'Fall 2016-2017'), ('15:40','16:30','T','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',169,10416,'Fall 2016-2017'), ('9:40','11:30','R','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',170,10416,'Fall 2016-2017'), ('15:40','17:30','M','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',171,10417,'Fall 2016-2017'), ('13:40','14:30','T','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',172,10417,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',173,11556,'Fall 2016-2017'), ('14:40','16:30','W','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',174,10418,'Fall 2016-2017'), ('8:40','9:30','R','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',175,10418,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',176,11354,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',177,11364,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',178,11365,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',179,11367,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',180,11371,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',181,11379,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',182,11381,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',183,11383,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',184,11384,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',185,11393,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',186,11394,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',187,11395,'Fall 2016-2017'), ('13:40','16:30','W','Fac.of Arts and Social Sci. 2080','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',188,10043,'Fall 2016-2017'), ('24:40','15:30','T','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',189,10044,'Fall 2016-2017'), ('13:40','16:30','M','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',190,10045,'Fall 2016-2017'), ('24:40','15:30','F','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',191,10046,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',192,10048,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',193,10059,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',194,10051,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',195,10052,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',196,10053,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',197,10054,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',198,10056,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',199,10057,'Fall 2016-2017'), ('24:40','15:30','T','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',200,10064,'Fall 2016-2017'), ('17:40','20:30','T','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',201,10066,'Fall 2016-2017'), ('8:40','11:30','R','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',202,10068,'Fall 2016-2017'), ('9:40','24:30','M','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',203,10070,'Fall 2016-2017'), ('16:40','19:30','W','Fac.of Arts and Social Sci. 1080','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',204,10074,'Fall 2016-2017'), ('17:40','20:30','M','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',205,10075,'Fall 2016-2017'), ('24:40','15:30','T','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',206,10065,'Fall 2016-2017'), ('8:40','11:30','R','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',207,10069,'Fall 2016-2017'), ('9:40','24:30','M','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',208,10071,'Fall 2016-2017'), ('17:40','20:30','T','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',209,10067,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',210,10077,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Independent Study',211,11255,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',212,10078,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',213,10079,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',214,10080,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',215,10082,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',216,10083,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',217,10087,'Fall 2016-2017'), ('19:00','22:00','W','Karaköy Communication Center 3005','2016-10-01 00:00:00','2016-11-16 00:00:00','1st del',218,11559,'Fall 2016-2017'), ('9:00','24:00','S','Karaköy Communication Center 204','2016-10-01 00:00:00','2016-11-16 00:00:00','2nd del',219,11559,'Fall 2016-2017'), ('19:00','22:00','M','Karaköy Communication Center 3005','2016-10-01 00:00:00','2016-11-14 00:00:00','1st del',220,11560,'Fall 2016-2017'), ('13:00','16:00','S','Karaköy Communication Center 204','2016-10-01 00:00:00','2016-11-14 00:00:00','2nd del',221,11560,'Fall 2016-2017'), ('19:00','22:00','M','Karaköy Communication Center 3005','2016-11-19 00:00:00','2017-01-07 00:00:00','1st del',222,11561,'Fall 2016-2017'), ('13:00','16:00','S','Karaköy Communication Center 204','2016-11-19 00:00:00','2017-01-07 00:00:00','2nd del',223,11561,'Fall 2016-2017'), ('19:00','22:00','W','Karaköy Communication Center 3005','2016-11-19 00:00:00','2017-01-07 00:00:00','1st del',224,11562,'Fall 2016-2017'), ('9:00','24:00','S','Karaköy Communication Center 204','2016-11-19 00:00:00','2017-01-07 00:00:00','2nd del',225,11562,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-10-01 00:00:00','2017-01-14 00:00:00','Lecture',226,11725,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-10-01 00:00:00','2017-01-07 00:00:00','Project',227,11563,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',228,10965,'Fall 2016-2017'), ('9:40','11:30','W','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',229,10965,'Fall 2016-2017'), ('10:40','24:30','M','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',230,10966,'Fall 2016-2017'), ('14:40','15:30','W','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',231,10966,'Fall 2016-2017'), ('9:40','10:30','T','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',232,10967,'Fall 2016-2017'), ('13:40','15:30','T','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',233,10967,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',234,10991,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',235,10992,'Fall 2016-2017'), ('9:40','10:30','F','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',236,10993,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',237,10968,'Fall 2016-2017'), ('9:40','11:30','W','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',238,10968,'Fall 2016-2017'), ('10:40','24:30','M','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',239,10969,'Fall 2016-2017'), ('14:40','15:30','W','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',240,10969,'Fall 2016-2017'), ('24:40','14:30','W','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',241,10970,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',242,10970,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',243,10994,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',244,10995,'Fall 2016-2017'), ('9:40','10:30','F','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',245,10996,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',246,10971,'Fall 2016-2017'), ('9:40','11:30','W','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',247,10971,'Fall 2016-2017'), ('10:40','24:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',248,10972,'Fall 2016-2017'), ('14:40','15:30','W','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',249,10972,'Fall 2016-2017'), ('13:40','15:30','T','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',250,10973,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',251,10973,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',252,10997,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',253,10998,'Fall 2016-2017'), ('9:40','10:30','F','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',254,10999,'Fall 2016-2017'), ('13:40','16:30','R','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',255,10088,'Fall 2016-2017'), ('9:40','10:30','F','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',256,11000,'Fall 2016-2017'), ('24:40','15:30','M','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',257,10090,'Fall 2016-2017'), ('8:40','10:30','M','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',258,10092,'Fall 2016-2017'), ('8:40','9:30','W','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',259,10092,'Fall 2016-2017'), ('16:40','19:30','W','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',260,10093,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Independent Study',261,10094,'Fall 2016-2017'), ('10:40','13:30','T','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',262,10095,'Fall 2016-2017'), ('17:40','18:30','M','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',263,10097,'Fall 2016-2017'), ('17:40','19:30','T','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',264,10097,'Fall 2016-2017'), ('10:40','13:30','R','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',265,10098,'Fall 2016-2017'), ('15:40','18:30','T','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',266,10101,'Fall 2016-2017'), ('16:40','17:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',267,11009,'Fall 2016-2017'), ('13:40','16:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',268,10105,'Fall 2016-2017'), ('17:40','18:30','W','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',269,11013,'Fall 2016-2017'), ('15:40','18:30','T','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',270,10100,'Fall 2016-2017'), ('16:40','17:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',271,11010,'Fall 2016-2017'), ('11:40','14:30','R','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',272,10102,'Fall 2016-2017'), ('17:40','18:30','F','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',273,11012,'Fall 2016-2017'), ('13:40','16:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',274,10104,'Fall 2016-2017'), ('17:40','18:30','W','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',275,11014,'Fall 2016-2017'), ('10:40','13:30','R','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',276,10099,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',277,11256,'Fall 2016-2017'), ('10:40','13:30','T','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',278,10096,'Fall 2016-2017'), ('15:40','18:30','T','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',279,10107,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',280,11257,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',281,10109,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',282,10110,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',283,10111,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',284,10112,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',285,10113,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',286,10114,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',287,10115,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',288,10116,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',289,10122,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',290,10123,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',291,10126,'Fall 2016-2017'), ('8:40','10:30','M','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',292,10419,'Fall 2016-2017'), ('24:40','13:30','T','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',293,10419,'Fall 2016-2017'), ('17:40','19:30','F','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',294,10420,'Fall 2016-2017'), ('8:40','10:30','T','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',295,10421,'Fall 2016-2017'), ('10:40','11:30','W','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',296,10421,'Fall 2016-2017'), ('17:40','19:30','W','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',297,10422,'Fall 2016-2017'), ('13:40','15:30','T','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',298,10423,'Fall 2016-2017'), ('15:40','16:30','W','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',299,10423,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',300,10424,'Fall 2016-2017'), ('10:40','24:30','T','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',301,10425,'Fall 2016-2017'), ('10:40','11:30','R','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',302,10425,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',303,10426,'Fall 2016-2017'), ('10:40','24:30','F','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',304,10427,'Fall 2016-2017'), ('14:40','15:30','F','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',305,10427,'Fall 2016-2017'), ('13:40','14:30','F','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',306,10428,'Fall 2016-2017'), ('15:40','17:30','M','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',307,10429,'Fall 2016-2017'), ('15:40','16:30','T','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',308,10429,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',309,10430,'Fall 2016-2017'), ('14:40','17:30','W','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',310,10431,'Fall 2016-2017'), ('17:40','19:30','F','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',311,10433,'Fall 2016-2017'), ('15:40','17:30','M','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',312,10434,'Fall 2016-2017'), ('16:40','17:30','T','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',313,10434,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',314,10435,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',315,10436,'Fall 2016-2017'), ('11:40','13:30','M','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',316,10436,'Fall 2016-2017'), ('17:40','18:30','F','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',317,10437,'Fall 2016-2017'), ('24:40','13:30','W','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',318,10438,'Fall 2016-2017'), ('13:40','15:30','R','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',319,10438,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',320,10439,'Fall 2016-2017'), ('13:40','15:30','M','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',321,10440,'Fall 2016-2017'), ('9:40','10:30','W','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',322,10440,'Fall 2016-2017'), ('17:40','19:30','W','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',323,10441,'Fall 2016-2017'), ('14:40','17:30','W','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',324,10432,'Fall 2016-2017'), ('24:40','14:30','R','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',325,10447,'Fall 2016-2017'), ('24:40','13:30','F','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',326,10447,'Fall 2016-2017'), ('24:40','14:30','W','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',327,10448,'Fall 2016-2017'), ('14:40','15:30','R','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',328,10448,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',329,11540,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',330,11541,'Fall 2016-2017'), ('13:40','15:30','M','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',331,10450,'Fall 2016-2017'), ('9:40','10:30','W','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',332,10450,'Fall 2016-2017'), ('9:40','11:30','M','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',333,10443,'Fall 2016-2017'), ('13:40','14:30','T','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',334,10443,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',335,11398,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',336,11405,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',337,11406,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',338,11408,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',339,11409,'Fall 2016-2017'), ('14:40','17:30','W','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',340,10451,'Fall 2016-2017'), ('24:40','13:30','M','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',341,10452,'Fall 2016-2017'), ('15:40','17:30','T','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',342,10452,'Fall 2016-2017'), ('24:40','15:30','T','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',343,11710,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',344,11412,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',345,11414,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',346,11416,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',347,11417,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',348,11418,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',349,11421,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',350,11422,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',351,11427,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',352,11739,'Fall 2016-2017'), ('19:00','22:00','M','Karaköy Communication Center 3003','2016-10-01 00:00:00','2016-11-14 00:00:00','1st del',353,11604,'Fall 2016-2017'), ('9:00','24:00','S','Karaköy Communication Center 3003','2016-10-01 00:00:00','2016-11-14 00:00:00','2nd del',354,11604,'Fall 2016-2017'), ('9:00','16:00','S','Karaköy Communication Center 3003','2016-11-19 00:00:00','2017-01-07 00:00:00','1st del',355,11607,'Fall 2016-2017'), ('19:00','22:00','M','Karaköy Communication Center 3003','2016-11-21 00:00:00','2017-01-04 00:00:00','1st del',356,11606,'Fall 2016-2017'), ('19:00','22:00','W','Karaköy Communication Center 3003','2016-11-21 00:00:00','2017-01-04 00:00:00','2nd del',357,11606,'Fall 2016-2017'), ('19:00','22:00','W','Karaköy Communication Center 3003','2016-10-01 00:00:00','2016-11-16 00:00:00','1st del',358,11605,'Fall 2016-2017'), ('13:00','16:00','S','Karaköy Communication Center 3003','2016-10-01 00:00:00','2016-11-16 00:00:00','2nd del',359,11605,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',360,10886,'Fall 2016-2017'), ('24:40','14:30','F','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',361,10886,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. G055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',362,10887,'Fall 2016-2017'), ('16:40','17:30','M','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',363,10986,'Fall 2016-2017'), ('15:40','17:30','W','School of Management 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',364,10986,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',365,10987,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',366,10988,'Fall 2016-2017'), ('8:40','10:30','F','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',367,10989,'Fall 2016-2017'), ('8:40','10:30','F','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',368,10990,'Fall 2016-2017'), ('13:40','14:30','R','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',369,10888,'Fall 2016-2017'), ('10:40','24:30','F','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',370,10888,'Fall 2016-2017'), ('17:40','19:30','T','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',371,10889,'Fall 2016-2017'), ('14:40','15:30','T','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',372,10890,'Fall 2016-2017'), ('8:40','10:30','F','Fac. of Engin. and Nat. Sci. G077','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',373,10890,'Fall 2016-2017'), ('11:40','24:30','W','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',374,10891,'Fall 2016-2017'), ('11:40','24:30','W','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',375,10892,'Fall 2016-2017'), ('17:40','18:30','W','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',376,10893,'Fall 2016-2017'), ('17:40','18:30','W','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',377,10894,'Fall 2016-2017'), ('18:40','19:30','W','School of Management G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',378,10895,'Fall 2016-2017'), ('18:40','19:30','W','School of Management G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',379,10896,'Fall 2016-2017'), ('8:40','9:30','R','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',380,10897,'Fall 2016-2017'), ('8:40','9:30','R','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',381,10898,'Fall 2016-2017'), ('9:40','10:30','R','Fac. of Engin. and Nat. Sci. L067','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',382,10899,'Fall 2016-2017'), ('9:40','10:30','R','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',383,10900,'Fall 2016-2017'), ('15:40','16:30','F','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',384,10901,'Fall 2016-2017'), ('15:40','16:30','F','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',385,10902,'Fall 2016-2017'), ('16:40','17:30','F','School of Management G065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',386,10903,'Fall 2016-2017'), ('16:40','17:30','F','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',387,10904,'Fall 2016-2017'), ('10:40','24:30','M','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',388,10876,'Fall 2016-2017'), ('9:40','10:30','R','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',389,10876,'Fall 2016-2017'), ('15:40','17:30','M','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',390,10877,'Fall 2016-2017'), ('10:40','11:30','R','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',391,10877,'Fall 2016-2017'), ('11:40','24:30','R','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',392,10878,'Fall 2016-2017'), ('11:40','24:30','R','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',393,10879,'Fall 2016-2017'), ('11:40','24:30','R','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',394,10880,'Fall 2016-2017'), ('15:40','16:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',395,10881,'Fall 2016-2017'), ('15:40','16:30','R','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',396,10882,'Fall 2016-2017'), ('15:40','16:30','R','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',397,10883,'Fall 2016-2017'), ('16:40','17:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',398,10884,'Fall 2016-2017'), ('16:40','17:30','R','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',399,10885,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',400,10905,'Fall 2016-2017'), ('15:40','17:30','T','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',401,10905,'Fall 2016-2017'), ('15:40','16:30','M','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',402,11233,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',403,11233,'Fall 2016-2017'), ('8:40','10:30','W','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',404,10906,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',405,10907,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',406,10908,'Fall 2016-2017'), ('16:40','18:30','W','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',407,10909,'Fall 2016-2017'), ('16:40','18:30','W','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',408,10910,'Fall 2016-2017'), ('14:40','16:30','F','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',409,11234,'Fall 2016-2017'), ('14:40','16:30','F','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',410,11235,'Fall 2016-2017'), ('10:40','11:30','W','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',411,10911,'Fall 2016-2017'), ('10:40','11:30','W','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',412,10912,'Fall 2016-2017'), ('10:40','11:30','W','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',413,10913,'Fall 2016-2017'), ('18:40','19:30','W','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',414,10914,'Fall 2016-2017'), ('18:40','19:30','W','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',415,10915,'Fall 2016-2017'), ('16:40','17:30','F','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',416,11236,'Fall 2016-2017'), ('16:40','17:30','F','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',417,11237,'Fall 2016-2017'), ('10:40','24:30','M','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',418,10874,'Fall 2016-2017'), ('14:40','15:30','W','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',419,10874,'Fall 2016-2017'), ('10:40','24:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',420,11150,'Fall 2016-2017'), ('10:40','24:30','R','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',421,11151,'Fall 2016-2017'), ('10:40','24:30','R','Fac.of Arts and Social Sci. 2031','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',422,11704,'Fall 2016-2017'), ('15:40','17:30','R','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',423,10875,'Fall 2016-2017'), ('15:40','17:30','R','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',424,11149,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',425,11664,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',426,11665,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',427,11669,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',428,11671,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',429,11672,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',430,11620,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',431,11621,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',432,11622,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',433,11623,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',434,11624,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',435,11625,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',436,11626,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',437,11628,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',438,11630,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',439,11632,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',440,11635,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',441,11636,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',442,11643,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',443,11646,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',444,11647,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',445,11648,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',446,11650,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',447,11652,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',448,11653,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',449,11655,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',450,11657,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',451,11658,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',452,11659,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',453,11660,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',454,11662,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',455,11674,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',456,11675,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',457,11677,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',458,11678,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',459,11679,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',460,11680,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',461,11681,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',462,11682,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',463,11683,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',464,11684,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',465,11685,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',466,11686,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',467,11687,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',468,11688,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',469,11689,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',470,11690,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',471,11698,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',472,11718,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',473,11719,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',474,11720,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',475,11722,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',476,11724,'Fall 2016-2017'), ('19:40','21:30','M',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',477,11738,'Fall 2016-2017'), ('15:40','17:30','W',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',478,11693,'Fall 2016-2017'), ('15:40','17:30','F',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Recitation',479,11694,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',480,11300,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',481,11301,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',482,11303,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',483,11304,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',484,11305,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',485,11306,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',486,11307,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',487,11308,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',488,11309,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',489,11310,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',490,11311,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',491,11312,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',492,11313,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',493,11314,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',494,11315,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',495,11316,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',496,11317,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',497,11318,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',498,11319,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',499,11320,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',500,11321,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',501,11322,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',502,11323,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',503,11324,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',504,11325,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',505,11326,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',506,11327,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',507,11328,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',508,11329,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',509,11330,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',510,11603,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',511,11721,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',512,11723,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',513,11745,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',514,10454,'Fall 2016-2017'), ('11:40','24:30','W','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',515,10454,'Fall 2016-2017'), ('16:40','17:30','M','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',516,10455,'Fall 2016-2017'), ('10:40','24:30','R','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',517,10455,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1023','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',518,10238,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1037','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',519,10238,'Fall 2016-2017'), ('8:40','24:30','W','School of Management G045','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',520,10238,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G036','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',521,10238,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G018','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',522,10238,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G042','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',523,10239,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1038','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',524,10239,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G032','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',525,10239,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1025','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',526,10239,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G023','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',527,10239,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1026','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',528,10242,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G062','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',529,10242,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1038','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',530,10242,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G000','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',531,10242,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G024','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',532,10242,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1031','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',533,10251,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1050','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',534,10251,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G041','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',535,10251,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1023','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',536,10251,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G039','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',537,10251,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1037','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',538,10253,'Fall 2016-2017'), ('8:40','24:30','T','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',539,10253,'Fall 2016-2017'), ('8:40','24:30','W','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',540,10253,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G042','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',541,10253,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1025','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',542,10253,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G033','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',543,10255,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1023','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',544,10255,'Fall 2016-2017'), ('8:40','24:30','W','School of Management G042','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',545,10255,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1026','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',546,10255,'Fall 2016-2017'), ('8:40','24:30','F','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',547,10255,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1046','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',548,10258,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1031','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',549,10258,'Fall 2016-2017'), ('8:40','24:30','W','School of Management G050','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',550,10258,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G033','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',551,10258,'Fall 2016-2017'), ('8:40','24:30','F','Fac.of Arts and Social Sci. G050','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',552,10258,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1048','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',553,10264,'Fall 2016-2017'), ('8:40','24:30','T','Fac.of Arts and Social Sci. G050','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',554,10264,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G033','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',555,10264,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1030','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',556,10264,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G032','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',557,10264,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1049','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',558,10265,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G042','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',559,10265,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G000','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',560,10265,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1031','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',561,10265,'Fall 2016-2017'), ('8:40','24:30','F','School of Management G042','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',562,10265,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1050','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',563,10267,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G023','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',564,10267,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G036','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',565,10267,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1037','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',566,10267,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1026','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',567,10267,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G018','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',568,10290,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G042','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',569,10290,'Fall 2016-2017'), ('8:40','24:30','W','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',570,10290,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G041','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',571,10290,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G000','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',572,10290,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G023','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',573,10292,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1026','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',574,10292,'Fall 2016-2017'), ('8:40','24:30','W','School of Management G056','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',575,10292,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1049','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',576,10292,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G036','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',577,10292,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G024','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',578,10293,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1027','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',579,10293,'Fall 2016-2017'), ('8:40','24:30','W','School of Management G062','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',580,10293,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1050','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',581,10293,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G041','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',582,10293,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G025','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',583,10295,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1030','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',584,10295,'Fall 2016-2017'), ('8:40','24:30','W','School of Management G065','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',585,10295,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G016','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',586,10295,'Fall 2016-2017'), ('8:40','24:30','F','School of Management G050','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',587,10295,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G038','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',588,10296,'Fall 2016-2017'), ('8:40','24:30','T','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',589,10296,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1023','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',590,10296,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G017','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',591,10296,'Fall 2016-2017'), ('8:40','24:30','F','School of Management G056','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',592,10296,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G039','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',593,10297,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G050','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',594,10297,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G042','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',595,10297,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G018','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',596,10297,'Fall 2016-2017'), ('8:40','24:30','F','School of Management G062','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',597,10297,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1025','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',598,10298,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G056','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',599,10298,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1026','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',600,10298,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G023','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',601,10298,'Fall 2016-2017'), ('8:40','24:30','F','School of Management G065','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',602,10298,'Fall 2016-2017'), ('8:40','24:30','M','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',603,10299,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1046','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',604,10299,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1027','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',605,10299,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G024','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',606,10299,'Fall 2016-2017'), ('8:40','24:30','F','Fac.of Arts and Social Sci. 2101','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',607,10299,'Fall 2016-2017'), ('8:40','24:30','M','Fac.of Arts and Social Sci. G050','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',608,10300,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1048','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',609,10300,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1030','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',610,10300,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G025','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',611,10300,'Fall 2016-2017'), ('8:40','24:30','F','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',612,10300,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G036','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',613,10301,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1049','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',614,10301,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1031','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',615,10301,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G038','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',616,10301,'Fall 2016-2017'), ('8:40','24:30','F','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',617,10301,'Fall 2016-2017'), ('8:40','24:30','M','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',618,10304,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G016','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',619,10304,'Fall 2016-2017'), ('8:40','24:30','W','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',620,10304,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G032','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',621,10304,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1023','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',622,10304,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G032','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',623,10305,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G017','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',624,10305,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1046','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',625,10305,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G050','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',626,10305,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1031','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',627,10305,'Fall 2016-2017'), ('8:40','24:30','M','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',628,10306,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G018','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',629,10306,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1048','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',630,10306,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G056','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',631,10306,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G033','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',632,10306,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G000','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',633,10307,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G045','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',634,10307,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1049','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',635,10307,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G062','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',636,10307,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1027','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',637,10307,'Fall 2016-2017'), ('8:40','24:30','M','School of Management G045','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',638,10308,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G041','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',639,10308,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1050','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',640,10308,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G065','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',641,10308,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1030','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',642,10308,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building G041','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',643,10309,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G025','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',644,10309,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G016','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',645,10309,'Fall 2016-2017'), ('8:40','24:30','R','Fac.of Arts and Social Sci. 2101','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',646,10309,'Fall 2016-2017'), ('8:40','24:30','F','School of Management G045','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',647,10309,'Fall 2016-2017'), ('8:40','24:30','M','School of Management G050','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',648,10310,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G038','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',649,10310,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G017','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',650,10310,'Fall 2016-2017'), ('8:40','24:30','R','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',651,10310,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1037','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',652,10310,'Fall 2016-2017'), ('8:40','24:30','M','School of Management G056','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',653,10313,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G039','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',654,10313,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G018','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',655,10313,'Fall 2016-2017'), ('8:40','24:30','R','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',656,10313,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1038','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',657,10313,'Fall 2016-2017'), ('8:40','24:30','M','School of Management G062','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',658,10315,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building 1025','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',659,10315,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G023','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',660,10315,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1048','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',661,10315,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1046','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',662,10315,'Fall 2016-2017'), ('8:40','24:30','M','School of Management G065','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',663,10316,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G032','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',664,10316,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G024','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',665,10316,'Fall 2016-2017'), ('8:40','24:30','R','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',666,10316,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1048','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',667,10316,'Fall 2016-2017'), ('8:40','24:30','M','Fac.of Arts and Social Sci. 2101','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',668,10318,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G033','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',669,10318,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G025','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',670,10318,'Fall 2016-2017'), ('8:40','24:30','R','Fac.of Arts and Social Sci. G050','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',671,10318,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1049','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',672,10318,'Fall 2016-2017'), ('8:40','24:30','M','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',673,10320,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G000','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',674,10320,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G038','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',675,10320,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1038','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',676,10320,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building 1050','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',677,10320,'Fall 2016-2017'), ('8:40','24:30','T','School of Languages Building G036','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',678,10322,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building G039','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',679,10322,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G042','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',680,10322,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G016','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',681,10322,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1027','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',682,11600,'Fall 2016-2017'), ('8:40','24:30','T','School of Management G065','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',683,11600,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1037','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',684,11600,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building 1046','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',685,11600,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G042','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',686,11600,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1038','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',687,11601,'Fall 2016-2017'), ('8:40','24:30','W','School of Languages Building 1025','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',688,11601,'Fall 2016-2017'), ('8:40','24:30','R','School of Management G045','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',689,11601,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G017','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',690,11601,'Fall 2016-2017'), ('8:40','24:30','M','School of Languages Building 1030','2016-09-26 00:00:00','2017-01-12 00:00:00','1st del',691,11602,'Fall 2016-2017'), ('8:40','24:30','T','Fac.of Arts and Social Sci. 2101','2016-09-26 00:00:00','2017-01-12 00:00:00','2nd del',692,11602,'Fall 2016-2017'), ('8:40','24:30','W','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2017-01-12 00:00:00','3rd del',693,11602,'Fall 2016-2017'), ('8:40','24:30','R','School of Languages Building G039','2016-09-26 00:00:00','2017-01-12 00:00:00','4th del',694,11602,'Fall 2016-2017'), ('8:40','24:30','F','School of Languages Building G038','2016-09-26 00:00:00','2017-01-12 00:00:00','5th del',695,11602,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',696,10585,'Fall 2016-2017'), ('8:40','10:30','R','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',697,10585,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',698,10586,'Fall 2016-2017'), ('8:40','10:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',699,10586,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',700,10587,'Fall 2016-2017'), ('8:40','10:30','R','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',701,10587,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',702,10588,'Fall 2016-2017'), ('8:40','10:30','R','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',703,10588,'Fall 2016-2017'), ('10:40','11:30','M','School of Management G042','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',704,10589,'Fall 2016-2017'), ('8:40','10:30','R','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',705,10589,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',706,10590,'Fall 2016-2017'), ('8:40','10:30','R','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',707,10590,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',708,10591,'Fall 2016-2017'), ('8:40','10:30','R','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',709,10591,'Fall 2016-2017'), ('10:40','11:30','M','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',710,10592,'Fall 2016-2017'), ('8:40','10:30','R','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',711,10592,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',712,10593,'Fall 2016-2017'), ('13:40','14:30','R','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',713,10593,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',714,10594,'Fall 2016-2017'), ('13:40','14:30','R','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',715,10594,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',716,10595,'Fall 2016-2017'), ('13:40','14:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',717,10595,'Fall 2016-2017'), ('13:40','15:30','M','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',718,10596,'Fall 2016-2017'), ('13:40','14:30','R','School of Management G045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',719,10596,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',720,10597,'Fall 2016-2017'), ('13:40','14:30','R','School of Management G042','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',721,10597,'Fall 2016-2017'), ('13:40','14:30','R','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',722,10598,'Fall 2016-2017'), ('13:40','15:30','M','School of Management G041','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',723,10599,'Fall 2016-2017'), ('13:40','14:30','R','School of Management G065','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',724,10599,'Fall 2016-2017'), ('13:40','15:30','M','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',725,10600,'Fall 2016-2017'), ('13:40','14:30','R','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',726,10600,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',727,10601,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',728,10601,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',729,10602,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',730,10602,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',731,10603,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',732,10603,'Fall 2016-2017'), ('8:40','10:30','T','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',733,10604,'Fall 2016-2017'), ('24:40','13:30','R','School of Management G045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',734,10604,'Fall 2016-2017'), ('8:40','10:30','T','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',735,10605,'Fall 2016-2017'), ('24:40','13:30','R','School of Management G042','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',736,10605,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',737,10606,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',738,10606,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',739,10607,'Fall 2016-2017'), ('24:40','13:30','R','School of Management G065','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',740,10607,'Fall 2016-2017'), ('8:40','10:30','T','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',741,10608,'Fall 2016-2017'), ('24:40','13:30','R','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',742,10608,'Fall 2016-2017'), ('15:40','16:30','M','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',743,10609,'Fall 2016-2017'), ('10:40','24:30','W','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',744,10609,'Fall 2016-2017'), ('15:40','16:30','M','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',745,10610,'Fall 2016-2017'), ('10:40','24:30','W','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',746,10610,'Fall 2016-2017'), ('15:40','16:30','M','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',747,10611,'Fall 2016-2017'), ('10:40','24:30','W','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',748,10611,'Fall 2016-2017'), ('15:40','16:30','M','School of Management G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',749,10612,'Fall 2016-2017'), ('10:40','24:30','W','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',750,10612,'Fall 2016-2017'), ('15:40','16:30','M','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',751,10613,'Fall 2016-2017'), ('10:40','24:30','W','School of Management G041','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',752,10613,'Fall 2016-2017'), ('15:40','16:30','M','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',753,10614,'Fall 2016-2017'), ('10:40','24:30','W','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',754,10614,'Fall 2016-2017'), ('15:40','16:30','M','School of Management G041','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',755,10615,'Fall 2016-2017'), ('10:40','24:30','W','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',756,10615,'Fall 2016-2017'), ('15:40','16:30','M','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',757,10616,'Fall 2016-2017'), ('10:40','24:30','W','Fac. of Engin. and Nat. Sci. 2019','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',758,10616,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',759,10623,'Fall 2016-2017'), ('10:40','24:30','R','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',760,10623,'Fall 2016-2017'), ('24:40','13:30','M','School of Management G042','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',761,10624,'Fall 2016-2017'), ('10:40','24:30','R','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',762,10624,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',763,10625,'Fall 2016-2017'), ('10:40','24:30','R','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',764,10625,'Fall 2016-2017'), ('13:40','15:30','M','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',765,10620,'Fall 2016-2017'), ('24:40','13:30','T','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',766,10620,'Fall 2016-2017'), ('13:40','15:30','M','School of Management G042','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',767,10621,'Fall 2016-2017'), ('24:40','13:30','T','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',768,10621,'Fall 2016-2017'), ('13:40','15:30','M','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',769,10622,'Fall 2016-2017'), ('24:40','13:30','T','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',770,10622,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',771,10626,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. 1102','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',772,10626,'Fall 2016-2017'), ('10:40','24:30','T','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',773,10627,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',774,10627,'Fall 2016-2017'), ('10:40','24:30','T','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',775,10628,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',776,10628,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',777,11280,'Fall 2016-2017'), ('24:40','13:30','R','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',778,11280,'Fall 2016-2017'), ('8:40','10:30','W','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',779,10617,'Fall 2016-2017'), ('14:40','15:30','R','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',780,10617,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. G059','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',781,10618,'Fall 2016-2017'), ('14:40','15:30','R','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',782,10618,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. G015','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',783,10619,'Fall 2016-2017'), ('14:40','15:30','R','School of Management G045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',784,10619,'Fall 2016-2017'), ('15:40','16:30','T','School of Languages Building 1031','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',785,11027,'Fall 2016-2017'), ('10:40','24:30','W','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',786,11027,'Fall 2016-2017'), ('24:40','14:30','M','School of Management G045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',787,11028,'Fall 2016-2017'), ('24:40','13:30','T','School of Languages Building G023','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',788,11028,'Fall 2016-2017'), ('14:40','16:30','M','School of Languages Building G018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',789,11029,'Fall 2016-2017'), ('14:40','15:30','W','School of Languages Building G023','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',790,11029,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',791,10127,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',792,10130,'Fall 2016-2017'), ('8:40','11:30','T','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',793,10007,'Fall 2016-2017'), ('9:40','24:30','M','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',794,10008,'Fall 2016-2017'), ('17:40','18:30','W','School of Management G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',795,10009,'Fall 2016-2017'), ('17:40','18:30','M','School of Management G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',796,10010,'Fall 2016-2017'), ('14:40','17:30','W','School of Management L018','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',797,10011,'Fall 2016-2017'), ('24:40','15:30','F','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',798,10012,'Fall 2016-2017'), ('8:40','11:30','T','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',799,10014,'Fall 2016-2017'), ('13:40','16:30','M','School of Management G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',800,11129,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-19 00:00:00','2016-12-30 00:00:00','Lecture',801,11217,'Fall 2016-2017'), ('10:40','13:30','W','School of Management CAFE','2016-09-21 00:00:00','2016-11-02 00:00:00','Lecture',802,11218,'Fall 2016-2017'), ('13:40','16:30','T','School of Management CAFE','2016-11-15 00:00:00','2016-12-27 00:00:00','Lecture',803,11219,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-19 00:00:00','2016-12-30 00:00:00','Lecture',804,11220,'Fall 2016-2017'), ('9:40','24:30','R','School of Management CAFE','2016-09-19 00:00:00','2016-12-30 00:00:00','1st del',805,11221,'Fall 2016-2017'), ('18:00','21:00','F','School of Management G050','2016-11-26 00:00:00','2016-12-03 00:00:00','1st del',806,11177,'Fall 2016-2017'), ('9:00','17:00','S','School of Management G050','2016-11-26 00:00:00','2016-12-03 00:00:00','2nd del',807,11177,'Fall 2016-2017'), ('9:40','24:30','M','School of Management CAFE','2016-09-19 00:00:00','2016-10-31 00:00:00','Lecture',808,11222,'Fall 2016-2017'), ('24:40','15:30','M','School of Management CAFE','2016-11-14 00:00:00','2016-12-26 00:00:00','Lecture',809,11223,'Fall 2016-2017'), ('8:40','11:30','F','School of Management CAFE','2016-11-18 00:00:00','2016-12-30 00:00:00','Lecture',810,11224,'Fall 2016-2017'), ('13:40','16:30','T','School of Management CAFE','2016-09-20 00:00:00','2016-11-01 00:00:00','Lecture',811,11225,'Fall 2016-2017'), ('9:40','24:30','R','School of Management CAFE','2016-11-17 00:00:00','2016-12-29 00:00:00','Lecture',812,11226,'Fall 2016-2017'), ('9:40','24:30','W','School of Management CAFE','2016-11-16 00:00:00','2016-12-28 00:00:00','Lecture',813,11227,'Fall 2016-2017'), ('13:40','16:30','M','School of Management CAFE','2016-09-22 00:00:00','2016-11-03 00:00:00','1st del',814,11228,'Fall 2016-2017'), ('14:40','17:30','W','School of Management CAFE','2016-09-21 00:00:00','2016-12-28 00:00:00','Lecture',815,11229,'Fall 2016-2017'), ('14:40','16:30','R','School of Management G013-14','2016-09-22 00:00:00','2016-12-22 00:00:00','Workshop',816,11230,'Fall 2016-2017'), ('8:40','11:30','T','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',817,11030,'Fall 2016-2017'), ('8:40','11:30','R','Fac.of Arts and Social Sci. 1001A','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',818,11031,'Fall 2016-2017'), ('14:40','16:30','R','School of Languages Building G033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',819,11032,'Fall 2016-2017'), ('14:40','16:30','T','School of Languages Building G033','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',820,11033,'Fall 2016-2017'), ('8:40','11:30','M','School of Languages Building G016','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',821,11036,'Fall 2016-2017'), ('8:40','11:30','T','School of Languages Building G024','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',822,11037,'Fall 2016-2017'), ('24:40','14:30','T','School of Languages Building G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',823,11038,'Fall 2016-2017'), ('9:40','11:30','W','Fac.of Arts and Social Sci. 2101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',824,11039,'Fall 2016-2017'), ('24:40','14:30','W','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',825,10140,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',826,10140,'Fall 2016-2017'), ('14:40','17:30','M','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',827,10141,'Fall 2016-2017'), ('16:40','19:30','W','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',828,10142,'Fall 2016-2017'), ('10:40','13:30','M','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',829,10144,'Fall 2016-2017'), ('16:40','19:30','W','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',830,10143,'Fall 2016-2017'), ('10:40','13:30','M','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',831,10145,'Fall 2016-2017'), ('10:40','24:30','T','School of Management 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',832,10629,'Fall 2016-2017'), ('10:40','24:30','R','School of Management 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',833,10630,'Fall 2016-2017'), ('9:40','11:30','M','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',834,10631,'Fall 2016-2017'), ('15:40','17:30','F','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',835,10633,'Fall 2016-2017'), ('9:40','11:30','M','School of Management 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',836,10632,'Fall 2016-2017'), ('10:40','13:30','T','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',837,10146,'Fall 2016-2017'), ('13:40','16:30','T','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',838,11253,'Fall 2016-2017'), ('24:40','15:30','T','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',839,11118,'Fall 2016-2017'), ('24:40','14:30','M','Fac.of Arts and Social Sci. 2031','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',840,10147,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',841,10147,'Fall 2016-2017'), ('11:40','14:30','M','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',842,10148,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',843,10150,'Fall 2016-2017'), ('17:40','20:30','M','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',844,10151,'Fall 2016-2017'), ('24:40','15:30','M','Fac.of Arts and Social Sci. G050','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',845,11125,'Fall 2016-2017'), ('24:40','15:30','T','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',846,11119,'Fall 2016-2017'), ('14:40','17:30','W','Fac.of Arts and Social Sci. G043','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',847,11120,'Fall 2016-2017'), ('11:40','14:30','M','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',848,10149,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Project',849,10155,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',850,10157,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',851,10158,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',852,10159,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',853,10160,'Fall 2016-2017'), ('24:40','15:30','F','Fac.of Arts and Social Sci. 2080','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',854,11121,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',855,10163,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',856,10164,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',857,10165,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Independent Study',858,11755,'Fall 2016-2017'), ('13:40','16:30','R','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',859,10634,'Fall 2016-2017'), ('9:40','24:30','F','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',860,10635,'Fall 2016-2017'), ('10:40','24:30','T','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',861,10636,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',862,10637,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',863,10638,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',864,10639,'Fall 2016-2017'), ('14:40','15:30','R','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',865,10641,'Fall 2016-2017'), ('14:40','15:30','R','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',866,10642,'Fall 2016-2017'), ('14:40','15:30','R','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',867,10643,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',868,10645,'Fall 2016-2017'), ('15:40','16:30','T','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',869,10646,'Fall 2016-2017'), ('16:40','17:30','T','Fac.of Arts and Social Sci. G060','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',870,10647,'Fall 2016-2017'), ('10:40','24:30','T','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',871,10648,'Fall 2016-2017'), ('10:40','24:30','W','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',872,10649,'Fall 2016-2017'), ('15:40','16:30','T','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',873,10650,'Fall 2016-2017'), ('15:40','16:30','T','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',874,10651,'Fall 2016-2017'), ('16:40','17:30','T','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',875,10652,'Fall 2016-2017'), ('16:40','17:30','T','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',876,10653,'Fall 2016-2017'), ('13:40','14:30','W','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',877,10654,'Fall 2016-2017'), ('14:40','15:30','W','Fac.of Arts and Social Sci. G052','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',878,10655,'Fall 2016-2017'), ('9:40','24:30','W','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',879,10656,'Fall 2016-2017'), ('13:40','16:30','W','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',880,10657,'Fall 2016-2017'), ('9:40','24:30','W','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',881,10658,'Fall 2016-2017'), ('13:40','16:30','R','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',882,10659,'Fall 2016-2017'), ('10:40','24:30','W','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',883,10660,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',884,10661,'Fall 2016-2017'), ('13:40','14:30','R','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',885,10662,'Fall 2016-2017'), ('14:40','15:30','R','Fac.of Arts and Social Sci. 1001','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',886,10663,'Fall 2016-2017'), ('14:40','15:30','R','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',887,10664,'Fall 2016-2017'), ('10:40','24:30','W','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',888,10665,'Fall 2016-2017'), ('13:40','14:30','W','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',889,10666,'Fall 2016-2017'), ('14:40','15:30','W','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',890,10667,'Fall 2016-2017'), ('13:40','16:30','R','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',891,10668,'Fall 2016-2017'), ('9:40','24:30','T','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',892,10669,'Fall 2016-2017'), ('15:40','18:30','T','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',893,10670,'Fall 2016-2017'), ('9:40','11:30','W','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',894,10938,'Fall 2016-2017'), ('9:40','11:30','R','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',895,10938,'Fall 2016-2017'), ('24:40','14:30','W','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',896,10939,'Fall 2016-2017'), ('24:40','14:30','R','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',897,10939,'Fall 2016-2017'), ('17:40','19:30','M','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',898,10940,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. L048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',899,10941,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. G025','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',900,10942,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. L061','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',901,10944,'Fall 2016-2017'), ('15:40','17:30','M','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',902,10456,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',903,10456,'Fall 2016-2017'), ('14:40','16:30','T','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',904,10457,'Fall 2016-2017'), ('14:40','16:30','R','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',905,10457,'Fall 2016-2017'), ('17:40','19:30','R','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',906,10458,'Fall 2016-2017'), ('17:40','19:30','R','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',907,10459,'Fall 2016-2017'), ('17:40','19:30','R','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',908,10460,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',909,10461,'Fall 2016-2017'), ('17:40','19:30','T','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',910,10462,'Fall 2016-2017'), ('17:40','19:30','T','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',911,10463,'Fall 2016-2017'), ('14:40','17:30','W','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',912,10464,'Fall 2016-2017'), ('24:40','13:30','F','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',913,10465,'Fall 2016-2017'), ('14:40','15:30','R','Fac.of Arts and Social Sci. 1103','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',914,10466,'Fall 2016-2017'), ('17:40','18:30','W','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',915,10467,'Fall 2016-2017'), ('10:40','24:30','M','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',916,10468,'Fall 2016-2017'), ('24:40','13:30','R','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',917,10468,'Fall 2016-2017'), ('13:40','15:30','T','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',918,10469,'Fall 2016-2017'), ('13:40','14:30','R','Fac.of Arts and Social Sci. G062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',919,10469,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',920,10470,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',921,10471,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',922,10472,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',923,10473,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',924,10474,'Fall 2016-2017'), ('13:40','15:30','M','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',925,10475,'Fall 2016-2017'), ('13:40','14:30','T','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',926,10475,'Fall 2016-2017'), ('10:40','24:30','M','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',927,10476,'Fall 2016-2017'), ('11:40','24:30','T','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',928,10476,'Fall 2016-2017'), ('17:40','19:30','W','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',929,10477,'Fall 2016-2017'), ('17:40','19:30','F','Fac.of Arts and Social Sci. 2119/2128','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',930,10478,'Fall 2016-2017'), ('24:40','13:30','M','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',931,10479,'Fall 2016-2017'), ('14:40','16:30','T','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',932,10479,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',933,10480,'Fall 2016-2017'), ('17:40','19:30','T','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',934,10481,'Fall 2016-2017'), ('17:40','19:30','W','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',935,10482,'Fall 2016-2017'), ('24:40','13:30','T','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',936,10484,'Fall 2016-2017'), ('9:40','11:30','F','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',937,10484,'Fall 2016-2017'), ('11:40','24:30','T','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',938,10485,'Fall 2016-2017'), ('24:40','14:30','F','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',939,10485,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. G029','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',940,10486,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',941,10487,'Fall 2016-2017'), ('17:40','19:30','M','Fac. of Engin. and Nat. Sci. L035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',942,10488,'Fall 2016-2017'), ('8:40','10:30','T','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',943,10491,'Fall 2016-2017'), ('8:40','10:30','W','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',944,10491,'Fall 2016-2017'), ('16:40','19:30','W','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',945,10492,'Fall 2016-2017'), ('16:40','19:30','F','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',946,10493,'Fall 2016-2017'), ('16:40','19:30','R','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',947,10494,'Fall 2016-2017'), ('8:40','11:30','R','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',948,10495,'Fall 2016-2017'), ('16:40','17:30','R','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',949,10496,'Fall 2016-2017'), ('17:40','18:30','R','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',950,10497,'Fall 2016-2017'), ('11:40','24:30','W','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',951,10498,'Fall 2016-2017'), ('11:40','13:30','R','Fac. of Engin. and Nat. Sci. L045','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',952,10498,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',953,10499,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',954,10500,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',955,11157,'Fall 2016-2017'), ('17:40','19:30','R','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',956,11702,'Fall 2016-2017'), ('24:40','15:30','F','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',957,10501,'Fall 2016-2017'), ('11:40','13:30','M','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',958,10502,'Fall 2016-2017'), ('10:40','11:30','T','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',959,10502,'Fall 2016-2017'), ('8:40','10:30','M','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',960,11158,'Fall 2016-2017'), ('13:40','14:30','T','Fac. of Engin. and Nat. Sci. G035','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',961,11158,'Fall 2016-2017'), ('17:40','19:30','W','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',962,11192,'Fall 2016-2017'), ('17:40','19:30','W','Fac.of Arts and Social Sci. 2023','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',963,11193,'Fall 2016-2017'), ('24:40','15:30','W','Fac.of Arts and Social Sci. G022','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',964,10503,'Fall 2016-2017'), ('17:40','19:30','W','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',965,10504,'Fall 2016-2017'), ('14:40','16:30','T','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',966,10506,'Fall 2016-2017'), ('10:40','11:30','W','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',967,10506,'Fall 2016-2017'), ('8:40','11:30','M','School of Management L014','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',968,10508,'Fall 2016-2017'), ('13:40','16:30','R','Fac. of Engin. and Nat. Sci. G032','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',969,10509,'Fall 2016-2017'), ('13:40','16:30','R','Fac. of Engin. and Nat. Sci. L065','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',970,10510,'Fall 2016-2017'), ('9:40','10:30','M','Fac.of Arts and Social Sci. 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',971,10511,'Fall 2016-2017'), ('11:40','13:30','T','Fac.of Arts and Social Sci. 1098','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',972,10511,'Fall 2016-2017'), ('14:40','16:30','M','Fac. of Engin. and Nat. Sci. L056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',973,10512,'Fall 2016-2017'), ('13:40','14:30','T','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',974,10512,'Fall 2016-2017'), ('11:40','14:30','M','Fac. of Engin. and Nat. Sci. L055','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',975,10516,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',976,11552,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',977,11553,'Fall 2016-2017'), ('8:40','10:30','R',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',978,10513,'Fall 2016-2017'), ('11:40','24:30','F',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',979,10513,'Fall 2016-2017'), ('14:40','16:30','F',NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',980,10514,'Fall 2016-2017'), ('8:40','11:30','M','Fac. of Engin. and Nat. Sci. L030','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',981,10515,'Fall 2016-2017'), ('14:40','16:30','T','Fac. of Engin. and Nat. Sci. L047','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',982,11711,'Fall 2016-2017'), ('10:40','11:30','W','Fac. of Engin. and Nat. Sci. L062','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',983,11711,'Fall 2016-2017'), ('15:40','16:30','W','Fac. of Engin. and Nat. Sci. L058','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',984,11712,'Fall 2016-2017'), ('24:40','14:30','R','Fac. of Engin. and Nat. Sci. L027','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',985,11712,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',986,11430,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',987,11431,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',988,11433,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',989,11436,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',990,11442,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',991,11443,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',992,11445,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',993,11448,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',994,11450,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',995,11451,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',996,11455,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Seminar',997,11537,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',998,11458,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',999,11460,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',1000,11462,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',1001,11467,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',1002,11470,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-09-26 00:00:00','2016-12-30 00:00:00','Thesis',1003,11473,'Fall 2016-2017'), ('19:00','22:00','R','Karaköy Communication Center 3005','2016-10-01 00:00:00','2016-11-17 00:00:00','1st del',1004,11569,'Fall 2016-2017'), ('13:00','16:00','S','Fac. of Engin. and Nat. Sci. G032','2016-10-01 00:00:00','2016-11-17 00:00:00','2nd del',1005,11569,'Fall 2016-2017'), ('19:00','22:00','T','Karaköy Communication Center 3005','2016-11-19 00:00:00','2017-01-07 00:00:00','1st del',1006,11573,'Fall 2016-2017'), ('9:00','24:00','S','Fac. of Engin. and Nat. Sci. G032','2016-11-19 00:00:00','2017-01-07 00:00:00','2nd del',1007,11573,'Fall 2016-2017'), ('19:00','22:00','R','Karaköy Communication Center 3005','2016-11-19 00:00:00','2017-01-07 00:00:00','1st del',1008,11575,'Fall 2016-2017'), ('13:00','16:00','S','Fac. of Engin. and Nat. Sci. G032','2016-11-19 00:00:00','2017-01-07 00:00:00','2nd del',1009,11575,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-10-01 00:00:00','2017-01-14 00:00:00','Lecture',1010,11608,'Fall 2016-2017'), ('19:00','22:00','T','Karaköy Communication Center 3005','2016-10-01 00:00:00','2016-11-15 00:00:00','1st del',1011,11570,'Fall 2016-2017'), ('9:00','24:00','S','Fac. of Engin. and Nat. Sci. G032','2016-10-01 00:00:00','2016-11-15 00:00:00','2nd del',1012,11570,'Fall 2016-2017'), (NULL,NULL,NULL,NULL,'2016-10-01 00:00:00','2017-01-07 00:00:00','Project',1013,11579,'Fall 2016-2017'), ('16:40','19:30','R','School of Management 1099','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1014,10518,'Fall 2016-2017'), ('8:40','10:30','T','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1015,11002,'Fall 2016-2017'), ('8:40','9:30','R','Fac.of Arts and Social Sci. 1097','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',1016,11002,'Fall 2016-2017'), ('10:40','11:30','F','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1017,11003,'Fall 2016-2017'), ('11:40','24:30','F','Fac.of Arts and Social Sci. G049','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1018,11004,'Fall 2016-2017'), ('9:40','24:30','W','Fac.of Arts and Social Sci. G048','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1019,10170,'Fall 2016-2017'), ('15:40','17:30','M','Fac.of Arts and Social Sci. 1101','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1020,10171,'Fall 2016-2017'), ('15:40','16:30','W','Fac.of Arts and Social Sci. 1080','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',1021,10171,'Fall 2016-2017'), ('24:40','13:30','M','Fac.of Arts and Social Sci. 1081','2016-09-26 00:00:00','2016-12-30 00:00:00','2nd del',1022,10172,'Fall 2016-2017'), ('10:40','24:30','T','Fac.of Arts and Social Sci. 2031','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1023,10172,'Fall 2016-2017'), ('11:40','14:30','F','Fac.of Arts and Social Sci. 1001A','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1024,11042,'Fall 2016-2017'), ('14:40','16:30','R','Fac.of Arts and Social Sci. 1008A','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1025,11043,'Fall 2016-2017'), ('8:40','11:30','R','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1026,11047,'Fall 2016-2017'), ('11:40','14:30','F','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1027,11048,'Fall 2016-2017'), ('14:40','16:30','F','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1028,11051,'Fall 2016-2017'), ('14:40','16:30','R','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1029,11052,'Fall 2016-2017'), ('11:40','14:30','R','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1030,11055,'Fall 2016-2017'), ('8:40','10:30','F','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1031,11057,'Fall 2016-2017'), ('8:40','11:30','R','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1032,11049,'Fall 2016-2017'), ('11:40','14:30','F','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1033,11050,'Fall 2016-2017'), ('14:40','16:30','F','Fac.of Arts and Social Sci. 1096','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1034,11053,'Fall 2016-2017'), ('14:40','16:30','R','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1035,11054,'Fall 2016-2017'), ('11:40','14:30','R','Fac.of Arts and Social Sci. 1089','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1036,11056,'Fall 2016-2017'), ('8:40','10:30','F','Fac. of Engin. and Nat. Sci. L063','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1037,11058,'Fall 2016-2017'), ('13:40','16:30','M','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1038,10173,'Fall 2016-2017'), ('13:40','16:30','M','Fac.of Arts and Social Sci. G056','2016-09-26 00:00:00','2016-12-30 00:00:00','1st del',1039,10174,'Fall 2016-2017'); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `instructors` ( `i_id` INT NOT NULL, `name` VARCHAR(255) NOT NULL, `mail` VARCHAR(255), PRIMARY KEY (`i_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `instructors` (`i_id`, `name`, `mail`) VALUES (0,'<EMAIL>','<NAME>'), (1,'<EMAIL>','<NAME>'), (2,'<EMAIL>','<NAME>'), (3,NULL,'<NAME>'), (4,'<EMAIL>','<NAME>'), (5,NULL,'<NAME>'), (6,'<EMAIL>','<NAME>'), (7,'<EMAIL>','<NAME>'), (8,'<EMAIL>','<NAME>'), (9,'<EMAIL>','<NAME>'), (10,'<EMAIL>','<NAME>'), (11,'<EMAIL>','<NAME>'), (12,'<EMAIL>','<NAME>'), (13,'<EMAIL>','<NAME>'), (14,'<EMAIL>','<NAME>'), (15,'<EMAIL>','<NAME>'), (16,'<EMAIL>','<NAME>'), (17,NULL,'<NAME>'), (18,'<EMAIL>','<NAME>'), (19,'<EMAIL>','<NAME>'), (20,NULL,'<NAME>'), (21,'<EMAIL>','<NAME>'), (22,'<EMAIL>','<NAME>'), (23,NULL,'<NAME>'), (24,NULL,'<NAME>'), (25,'<EMAIL>','<NAME>'), (26,'<EMAIL>','<NAME>'), (27,'<EMAIL>','<NAME>'), (28,'<EMAIL>','<NAME>'), (29,NULL,'<NAME>'), (30,'<EMAIL>','<NAME>'), (31,'<EMAIL>','<NAME>'), (32,'<EMAIL>','<NAME>'), (33,'<EMAIL>','<NAME>'), (34,'<EMAIL>','<NAME>'), (35,'<EMAIL>','<NAME>'), (36,'<EMAIL>','<NAME>'), (37,'<EMAIL>','<NAME>'), (38,'<EMAIL>','<NAME>'), (39,'<EMAIL>','<NAME>'), (40,NULL,'<NAME>'), (41,'<EMAIL>','<NAME>'), (42,'<EMAIL>','<NAME>'), (43,NULL,'İlkem Kayıcan'), (44,'<EMAIL>','<NAME>'), (45,'<EMAIL>','<NAME>'), (46,'<EMAIL>','<NAME>'), (47,NULL,'<NAME>'), (48,'<EMAIL>','<NAME>'), (49,NULL,'<NAME>'), (50,'<EMAIL>','<NAME>'), (51,'<EMAIL>','<NAME>'), (52,'<EMAIL>','<NAME>'), (53,'<EMAIL>','<NAME>'), (54,'<EMAIL>','<NAME>'), (55,'<EMAIL>','<NAME>'), (56,'<EMAIL>','<NAME>'), (57,'<EMAIL>','<NAME>'), (58,'<EMAIL>','<NAME>'), (59,'<EMAIL>','<NAME>'), (60,'<EMAIL>','<NAME>'), (61,'<EMAIL>','<NAME>'), (62,NULL,'<NAME>'), (63,'<EMAIL>','<NAME>'), (64,'<EMAIL>','<NAME>'), (65,'<EMAIL>','<NAME>'), (66,'<EMAIL>','<NAME>'), (67,'<EMAIL>','<NAME>'), (68,'<EMAIL>','<NAME>'), (69,'<EMAIL>','<NAME>'), (70,'<EMAIL>','<NAME>'), (71,'<EMAIL>','<NAME>'), (72,NULL,'Füsun Ülengin'), (73,'<EMAIL>','<NAME>'), (74,'<EMAIL>','<NAME>'), (75,'<EMAIL>','<NAME>'), (76,'<EMAIL>','<NAME>'), (77,'<EMAIL>','<NAME>'), (78,'<EMAIL>','<NAME>'), (79,'<EMAIL>','<NAME>'), (80,'<EMAIL>','<NAME>'), (81,'<EMAIL>','<NAME>'), (82,'<EMAIL>','<NAME>'), (83,'<EMAIL>','<NAME>'), (84,'<EMAIL>','<NAME>'), (85,'<EMAIL>','<NAME>'), (86,'<EMAIL>','<NAME>'), (87,'<EMAIL>','<NAME>'), (88,'<EMAIL>','<NAME>'), (89,'<EMAIL>','Evrim Uysal'), (90,'<EMAIL>','<NAME>'), (91,'<EMAIL>','<NAME>'), (92,'<EMAIL>','<NAME>'), (93,'<EMAIL>','<NAME>'), (94,'<EMAIL>','<NAME>'), (95,'<EMAIL>','<NAME>'), (96,'<EMAIL>','<NAME>'), (97,'<EMAIL>','<NAME>'), (98,'<EMAIL>','<NAME>'), (99,'<EMAIL>','<NAME>'), (100,NULL,'<NAME>'), (101,'<EMAIL>','<NAME>'), (102,'<EMAIL>','<NAME>'), (103,'<EMAIL>','<NAME>'), (104,NULL,'<NAME>'), (105,NULL,'<NAME>'), (106,'<EMAIL>','<NAME>'), (107,NULL,'<NAME>'), (108,'<EMAIL>','<NAME>'), (109,'<EMAIL>','<NAME>'), (110,'<EMAIL>','<NAME>'), (111,'<EMAIL>','<NAME>'), (112,'<EMAIL>','<NAME>'), (113,'<EMAIL>','<NAME>'), (114,'<EMAIL>','<NAME>'), (115,'<EMAIL>','<NAME>'), (116,'<EMAIL>','<NAME>'), (117,'<EMAIL>','<NAME>'), (118,'<EMAIL>','<NAME>'), (119,NULL,'Vildan Çal'), (120,'<EMAIL>','<NAME>'), (121,NULL,'Deniz Atalayer'), (122,NULL,'<NAME>'), (123,'<EMAIL>','<NAME>'), (124,'<EMAIL>','<NAME>'), (125,'<EMAIL>','<NAME>'), (126,'<EMAIL>','<NAME>'), (127,'<EMAIL>','<NAME>'), (128,'<EMAIL>','<NAME>'), (129,'<EMAIL>','<NAME>'), (130,'<EMAIL>','<NAME>'), (131,'<EMAIL>','<NAME>'), (132,'<EMAIL>','<NAME>'), (133,'<EMAIL>','<NAME>'), (134,'<EMAIL>','<NAME>'), (135,'<EMAIL>','<NAME>'), (136,NULL,'<NAME>'), (137,'<EMAIL>','<NAME>'), (138,'<EMAIL>','<NAME>'), (139,'<EMAIL>','<NAME>'), (140,'<EMAIL>','<NAME>'), (141,'<EMAIL>','<NAME>'), (142,NULL,'<NAME>'), (143,NULL,'<NAME>'), (144,'<EMAIL>','<NAME>'), (145,NULL,'<NAME>'), (146,'<EMAIL>','<NAME>'), (147,'<EMAIL>','<NAME>'), (148,'<EMAIL>','<NAME>'), (149,NULL,'<NAME>'), (150,'<EMAIL>','<NAME>'), (151,NULL,'<NAME>'), (152,'<EMAIL>','<NAME>'), (153,'<EMAIL>','<NAME>'), (154,'<EMAIL>','<NAME>'), (155,'<EMAIL>','<NAME>'), (156,'<EMAIL>','<NAME>'), (157,'<EMAIL>','<NAME>'), (158,'<EMAIL>','<NAME>'), (159,'<EMAIL>','<NAME>'), (160,'<EMAIL>','<NAME>'), (161,'<EMAIL>','<NAME>'), (162,'<EMAIL>','<NAME>'), (163,'<EMAIL>','<NAME>'), (164,'<EMAIL>','<NAME>'), (165,'<EMAIL>','<NAME>'), (166,'<EMAIL>','<NAME>'), (167,'<EMAIL>','<NAME>'), (168,'<EMAIL>','<NAME>'), (169,'<EMAIL>','<NAME>'), (170,'<EMAIL>','<NAME>'), (171,'<EMAIL>','<NAME>'), (172,'<EMAIL>','<NAME>'), (173,'<EMAIL>','<NAME>'), (174,'<EMAIL>','<NAME>'), (175,'<EMAIL>','<NAME>'), (176,'<EMAIL>','<NAME>'), (177,'<EMAIL>','<NAME>'), (178,'<EMAIL>','<NAME>'), (179,'<EMAIL>','<NAME>'), (180,'<EMAIL>','<NAME>'), (181,'<EMAIL>','<NAME>'), (182,'<EMAIL>','<NAME>'), (183,NULL,'Yusuf İzmirlioğlu'), (184,'<EMAIL>','<NAME>'), (185,'<EMAIL>','<NAME>'), (186,NULL,'Akif Çal'), (187,'<EMAIL>','<NAME>'), (188,'<EMAIL>','<NAME>'), (189,'<EMAIL>','<NAME>'), (190,'<EMAIL>','<NAME>'), (191,'<EMAIL>','<NAME>'), (192,'<EMAIL>','<NAME>'), (193,'<EMAIL>','<NAME>'), (194,NULL,'Aslıgül Berktay'), (195,'<EMAIL>','<NAME>'), (196,'<EMAIL>','<NAME>'), (197,'<EMAIL>','<NAME>'), (198,'<EMAIL>','<NAME>'), (199,NULL,'<NAME>'), (200,'<EMAIL>','<NAME>'), (201,'<EMAIL>','<NAME>'), (202,'<EMAIL>','<NAME>'), (203,'<EMAIL>','<NAME>'), (204,'<EMAIL>','<NAME>'), (205,'<EMAIL>','<NAME>'), (206,'<EMAIL>','<NAME>'), (207,'<EMAIL>','<NAME>'), (208,'<EMAIL>','<NAME>'), (209,'<EMAIL>','<NAME>'), (210,'<EMAIL>','<NAME>'), (211,'<EMAIL>','<NAME>'), (212,'<EMAIL>','<NAME>'), (213,'<EMAIL>','<NAME>'), (214,'<EMAIL>','<NAME>'), (215,'<EMAIL>','<NAME>'), (216,'<EMAIL>','<NAME>'), (217,'<EMAIL>','<NAME>'), (218,'<EMAIL>','<NAME>'), (219,'<EMAIL>','<NAME>'), (220,'<EMAIL>','<NAME>'), (221,'<EMAIL>','<NAME>'), (222,'<EMAIL>','<NAME>'), (223,NULL,'Ayşegül Kayaoğlu'), (224,NULL,'<NAME>'), (225,'<EMAIL>','<NAME>'), (226,'<EMAIL>','<NAME>'), (227,'<EMAIL>','<NAME>'), (228,'<EMAIL>','<NAME>'), (229,'<EMAIL>','<NAME>'), (230,'<EMAIL>','<NAME>'), (231,'<EMAIL>','<NAME>'), (232,'<EMAIL>','<NAME>'), (233,'<EMAIL>','<NAME>'), (234,'<EMAIL>','<NAME>'), (235,'<EMAIL>','<NAME>'), (236,'<EMAIL>','<NAME>ill'), (237,'<EMAIL>','<NAME>'), (238,'<EMAIL>','<NAME>'), (239,'<EMAIL>','<NAME>'), (240,'<EMAIL>','Ayşe Kocabıyıkoğlu'), (241,'<EMAIL>','<NAME>'), (242,'<EMAIL>','<NAME>'), (243,'<EMAIL>','<NAME>'), (244,'<EMAIL>','<NAME>'), (245,'<EMAIL>','<NAME>'), (246,'<EMAIL>','<NAME>'), (247,'<EMAIL>','<NAME>'), (248,'<EMAIL>','<NAME>'), (249,'<EMAIL>','<NAME>'), (250,'<EMAIL>','<NAME>'), (251,'<EMAIL>','<NAME>'), (252,'<EMAIL>','<NAME>'), (253,NULL,'<NAME>'), (254,'<EMAIL>','<NAME>'), (255,'<EMAIL>','<NAME>'), (256,NULL,'<NAME>'), (257,'<EMAIL>','<NAME>'), (258,NULL,'<NAME>ok'), (259,'<EMAIL>','<NAME>'), (260,'<EMAIL>','<NAME>'), (261,'<EMAIL>','<NAME>'), (262,'<EMAIL>','<NAME>'), (263,'<EMAIL>','<NAME>'), (264,'<EMAIL>','<NAME>'), (265,'<EMAIL>','<NAME>'), (266,'<EMAIL>','<NAME>'), (267,'<EMAIL>','<NAME>'), (268,'<EMAIL>','<NAME>'), (269,'<EMAIL>','<NAME>'), (270,'<EMAIL>','<NAME>'), (271,NULL,'<NAME>'), (272,'<EMAIL>','<NAME>'), (273,'<EMAIL>','<NAME>'), (274,'<EMAIL>','<NAME>'), (275,'<EMAIL>','<NAME>'), (276,'<EMAIL>','<NAME>'), (277,'<EMAIL>','<NAME>'), (278,'<EMAIL>','<NAME>'), (279,NULL,'<NAME>'), (280,'<EMAIL>','<NAME>'), (281,'<EMAIL>','<NAME>'), (282,'<EMAIL>','<NAME>'), (283,'<EMAIL>','<NAME>'), (284,'<EMAIL>','<NAME>'), (285,'<EMAIL>','<NAME>'), (286,'<EMAIL>','<NAME>'), (287,'<EMAIL>','<NAME>'), (288,'<EMAIL>','<NAME>'), (289,'<EMAIL>','<NAME>'), (290,'<EMAIL>','<NAME>'), (291,'<EMAIL>','<NAME>'), (292,NULL,'<NAME>'), (293,'<EMAIL>','<NAME>'), (294,'<EMAIL>','<NAME>'), (295,'<EMAIL>','<NAME>'), (296,'<EMAIL>','<NAME>'), (297,'<EMAIL>','<NAME>'), (298,'<EMAIL>','<NAME>'), (299,'<EMAIL>','<NAME>'), (300,'<EMAIL>','<NAME>'), (301,'<EMAIL>','<NAME>'), (302,'<EMAIL>','<NAME>'), (303,'<EMAIL>','<NAME>'), (304,'<EMAIL>','<NAME>'), (305,NULL,'<NAME>'), (306,NULL,'Gözde İnce'), (307,'<EMAIL>','<NAME>'), (308,'<EMAIL>','<NAME>'), (309,'<EMAIL>','<NAME>'), (310,'<EMAIL>','<NAME>'), (311,'<EMAIL>','<NAME>'), (312,'<EMAIL>','<NAME>'), (313,'<EMAIL>','<NAME>'), (314,'<EMAIL>','<NAME>'), (315,'<EMAIL>','<NAME>'), (316,'<EMAIL>','<NAME>'), (317,'<EMAIL>','<NAME>'), (318,NULL,'<NAME>'), (319,NULL,'<NAME>'), (320,'<EMAIL>','<NAME>'), (321,'<EMAIL>','<NAME>'), (322,'<EMAIL>','<NAME>'), (323,'<EMAIL>','<NAME>'), (324,'<EMAIL>','<NAME>'), (325,'<EMAIL>','<NAME>'), (326,'<EMAIL>','<NAME>'), (327,'<EMAIL>','<NAME>'), (328,NULL,'<NAME>'), (329,'<EMAIL>','<NAME>'), (330,'<EMAIL>','<NAME>'), (331,'ahuant<EMAIL>','<NAME>'), (332,'<EMAIL>','<NAME>'), (333,'<EMAIL>','<NAME>'), (334,'<EMAIL>','<NAME>'), (335,'<EMAIL>','<NAME>'), (336,'<EMAIL>','<NAME>'), (337,'<EMAIL>','<NAME>'), (338,'<EMAIL>','<NAME>'), (339,'<EMAIL>','<NAME>'), (340,NULL,'<NAME>'), (341,NULL,'<NAME>'), (342,'<EMAIL>','<NAME>'), (343,NULL,'<NAME>'), (344,'<EMAIL>','<NAME>'), (345,'<EMAIL>','<NAME>'), (346,'<EMAIL>','<NAME>'), (347,'<EMAIL>','<NAME>'), (348,'<EMAIL>','<NAME>'), (349,'<EMAIL>','<NAME>'), (350,'<EMAIL>','<NAME>'), (351,'<EMAIL>','<NAME>'), (352,NULL,'<NAME>'), (353,'<EMAIL>','Alev <NAME>'), (354,NULL,'<NAME>'), (355,'<EMAIL>','<NAME>'), (356,'<EMAIL>','<NAME>'), (357,'<EMAIL>','<NAME>'), (358,'<EMAIL>','<NAME>'), (359,NULL,'<NAME>'), (360,'<EMAIL>','<NAME>'), (361,'<EMAIL>','<NAME>'), (362,'<EMAIL>','<NAME>'), (363,'<EMAIL>','<NAME>'), (364,'<EMAIL>','<NAME>'), (365,'<EMAIL>','<NAME>'), (366,'<EMAIL>','<NAME>'), (367,'<EMAIL>','<NAME>'); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `course_instructors` ( `cdn` INT NOT NULL, `term` VARCHAR(14) NOT NULL, `i_id` INT NOT NULL, `primary` BOOL NOT NULL, PRIMARY KEY (`cdn`, `term`, `i_id`), FOREIGN KEY (`cdn`, `term`) REFERENCES courses(`cdn`, `term`), FOREIGN KEY (`i_id`) REFERENCES instructors(`i_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `course_instructors` (`cdn`, `term`, `i_id`, `primary`) VALUES (10001,'Fall 2016-2017',320,1), (10002,'Fall 2016-2017',320,1), (10003,'Fall 2016-2017',320,1), (10977,'Fall 2016-2017',320,1), (10977,'Fall 2016-2017',212,0), (10977,'Fall 2016-2017',165,0), (10978,'Fall 2016-2017',320,1), (10978,'Fall 2016-2017',212,0), (10978,'Fall 2016-2017',165,0), (10979,'Fall 2016-2017',320,1), (10979,'Fall 2016-2017',212,0), (10979,'Fall 2016-2017',165,0), (10980,'Fall 2016-2017',320,1), (10980,'Fall 2016-2017',212,0), (10980,'Fall 2016-2017',165,0), (10981,'Fall 2016-2017',320,1), (10981,'Fall 2016-2017',212,0), (10981,'Fall 2016-2017',165,0), (10982,'Fall 2016-2017',320,1), (10982,'Fall 2016-2017',212,0), (10982,'Fall 2016-2017',165,0), (10004,'Fall 2016-2017',320,1), (10005,'Fall 2016-2017',320,1), (10005,'Fall 2016-2017',212,0), (10005,'Fall 2016-2017',165,0), (10006,'Fall 2016-2017',263,1), (11162,'Fall 2016-2017',7,1), (11194,'Fall 2016-2017',301,1), (11185,'Fall 2016-2017',327,1), (11184,'Fall 2016-2017',327,1), (11297,'Fall 2016-2017',296,1), (11137,'Fall 2016-2017',296,1), (10137,'Fall 2016-2017',296,1), (11298,'Fall 2016-2017',296,1), (11138,'Fall 2016-2017',296,1), (10138,'Fall 2016-2017',296,1), (11299,'Fall 2016-2017',296,1), (10139,'Fall 2016-2017',296,1), (11146,'Fall 2016-2017',242,1), (11147,'Fall 2016-2017',242,1), (11148,'Fall 2016-2017',242,1), (11015,'Fall 2016-2017',108,1), (11016,'Fall 2016-2017',108,1), (11019,'Fall 2016-2017',108,1), (11020,'Fall 2016-2017',108,1), (11023,'Fall 2016-2017',108,1), (11025,'Fall 2016-2017',108,1), (11017,'Fall 2016-2017',108,1), (11018,'Fall 2016-2017',108,1), (11021,'Fall 2016-2017',108,1), (11022,'Fall 2016-2017',108,1), (11024,'Fall 2016-2017',108,1), (11026,'Fall 2016-2017',108,1), (11728,'Fall 2016-2017',144,1), (11730,'Fall 2016-2017',91,1), (11731,'Fall 2016-2017',139,1), (11727,'Fall 2016-2017',179,1), (11737,'Fall 2016-2017',30,1), (11152,'Fall 2016-2017',233,1), (11153,'Fall 2016-2017',240,1), (11238,'Fall 2016-2017',233,1), (10387,'Fall 2016-2017',284,1), (11122,'Fall 2016-2017',284,1), (11122,'Fall 2016-2017',88,0), (11122,'Fall 2016-2017',218,0), (10389,'Fall 2016-2017',46,1), (10390,'Fall 2016-2017',46,1), (10847,'Fall 2016-2017',145,1), (10848,'Fall 2016-2017',145,1), (11564,'Fall 2016-2017',145,1), (11565,'Fall 2016-2017',145,1), (11566,'Fall 2016-2017',145,1), (11567,'Fall 2016-2017',145,1), (11568,'Fall 2016-2017',145,1), (11571,'Fall 2016-2017',145,1), (11572,'Fall 2016-2017',145,1), (11574,'Fall 2016-2017',145,1), (11576,'Fall 2016-2017',145,1), (11577,'Fall 2016-2017',145,1), (11578,'Fall 2016-2017',145,1), (11580,'Fall 2016-2017',145,1), (11581,'Fall 2016-2017',145,1), (11582,'Fall 2016-2017',145,1), (11583,'Fall 2016-2017',145,1), (11584,'Fall 2016-2017',145,1), (11585,'Fall 2016-2017',145,1), (11586,'Fall 2016-2017',145,1), (11587,'Fall 2016-2017',145,1), (11588,'Fall 2016-2017',145,1), (11589,'Fall 2016-2017',145,1), (11590,'Fall 2016-2017',145,1), (11591,'Fall 2016-2017',145,1), (11592,'Fall 2016-2017',145,1), (11593,'Fall 2016-2017',145,1), (11594,'Fall 2016-2017',145,1), (11595,'Fall 2016-2017',145,1), (11596,'Fall 2016-2017',145,1), (11597,'Fall 2016-2017',145,1), (11598,'Fall 2016-2017',145,1), (11609,'Fall 2016-2017',145,1), (11732,'Fall 2016-2017',145,1), (11733,'Fall 2016-2017',145,1), (11734,'Fall 2016-2017',145,1), (11735,'Fall 2016-2017',145,1), (11736,'Fall 2016-2017',145,1), (10916,'Fall 2016-2017',188,1), (10917,'Fall 2016-2017',188,1), (10917,'Fall 2016-2017',261,0), (10918,'Fall 2016-2017',188,1), (10918,'Fall 2016-2017',183,0), (10919,'Fall 2016-2017',188,1), (10919,'Fall 2016-2017',148,0), (10920,'Fall 2016-2017',188,1), (10920,'Fall 2016-2017',295,0), (10921,'Fall 2016-2017',188,1), (10922,'Fall 2016-2017',188,1), (10922,'Fall 2016-2017',207,0), (10923,'Fall 2016-2017',188,1), (10923,'Fall 2016-2017',281,0), (10924,'Fall 2016-2017',188,1), (10924,'Fall 2016-2017',25,0), (11703,'Fall 2016-2017',188,1), (11703,'Fall 2016-2017',68,0), (10925,'Fall 2016-2017',188,1), (10925,'Fall 2016-2017',267,0), (10926,'Fall 2016-2017',188,1), (10926,'Fall 2016-2017',207,0), (10927,'Fall 2016-2017',188,1), (10927,'Fall 2016-2017',86,0), (10928,'Fall 2016-2017',188,1), (10928,'Fall 2016-2017',198,0), (10929,'Fall 2016-2017',188,1), (10929,'Fall 2016-2017',267,0), (10930,'Fall 2016-2017',188,1), (10930,'Fall 2016-2017',208,0), (10931,'Fall 2016-2017',188,1), (10932,'Fall 2016-2017',188,1), (10932,'Fall 2016-2017',217,0), (10933,'Fall 2016-2017',136,1), (10934,'Fall 2016-2017',136,1), (10934,'Fall 2016-2017',229,0), (10935,'Fall 2016-2017',136,1), (10936,'Fall 2016-2017',136,1), (10936,'Fall 2016-2017',229,0), (10937,'Fall 2016-2017',136,1), (10391,'Fall 2016-2017',280,1), (10392,'Fall 2016-2017',280,1), (10392,'Fall 2016-2017',191,0), (10392,'Fall 2016-2017',134,0), (10393,'Fall 2016-2017',345,1), (11126,'Fall 2016-2017',345,1), (11126,'Fall 2016-2017',268,0), (10394,'Fall 2016-2017',309,1), (10395,'Fall 2016-2017',309,1), (10395,'Fall 2016-2017',64,0), (10396,'Fall 2016-2017',309,1), (10396,'Fall 2016-2017',34,0), (10396,'Fall 2016-2017',225,0), (10397,'Fall 2016-2017',309,1), (10397,'Fall 2016-2017',51,0), (10397,'Fall 2016-2017',64,0), (10398,'Fall 2016-2017',309,1), (10398,'Fall 2016-2017',34,0), (10399,'Fall 2016-2017',309,1), (10399,'Fall 2016-2017',51,0), (10400,'Fall 2016-2017',309,1), (10400,'Fall 2016-2017',225,0), (10401,'Fall 2016-2017',309,1), (10401,'Fall 2016-2017',34,0), (10401,'Fall 2016-2017',225,0), (10401,'Fall 2016-2017',51,0), (10401,'Fall 2016-2017',64,0), (10402,'Fall 2016-2017',239,1), (10403,'Fall 2016-2017',239,1), (10403,'Fall 2016-2017',103,0), (10404,'Fall 2016-2017',150,1), (10406,'Fall 2016-2017',213,1), (10407,'Fall 2016-2017',13,1), (10408,'Fall 2016-2017',13,1), (10408,'Fall 2016-2017',141,0), (10409,'Fall 2016-2017',116,1), (10410,'Fall 2016-2017',116,1), (10410,'Fall 2016-2017',22,0), (10410,'Fall 2016-2017',244,0), (10410,'Fall 2016-2017',28,0), (10411,'Fall 2016-2017',116,1), (10411,'Fall 2016-2017',22,0), (10411,'Fall 2016-2017',244,0), (10411,'Fall 2016-2017',28,0), (10412,'Fall 2016-2017',116,1), (10412,'Fall 2016-2017',22,0), (10412,'Fall 2016-2017',244,0), (10412,'Fall 2016-2017',28,0), (10405,'Fall 2016-2017',150,1), (11697,'Fall 2016-2017',130,1), (10413,'Fall 2016-2017',150,1), (10414,'Fall 2016-2017',213,1), (10415,'Fall 2016-2017',239,1), (10416,'Fall 2016-2017',116,1), (10417,'Fall 2016-2017',13,1), (11556,'Fall 2016-2017',150,1), (10418,'Fall 2016-2017',280,1), (11354,'Fall 2016-2017',116,1), (11364,'Fall 2016-2017',18,1), (11365,'Fall 2016-2017',150,1), (11367,'Fall 2016-2017',213,1), (11371,'Fall 2016-2017',239,1), (11379,'Fall 2016-2017',116,1), (11381,'Fall 2016-2017',160,1), (11383,'Fall 2016-2017',280,1), (11384,'Fall 2016-2017',18,1), (11393,'Fall 2016-2017',356,1), (11394,'Fall 2016-2017',13,1), (11395,'Fall 2016-2017',239,1), (10043,'Fall 2016-2017',111,1), (10044,'Fall 2016-2017',111,1), (10045,'Fall 2016-2017',328,1), (10046,'Fall 2016-2017',274,1), (10048,'Fall 2016-2017',274,1), (10059,'Fall 2016-2017',187,1), (10051,'Fall 2016-2017',241,1), (10052,'Fall 2016-2017',111,1), (10053,'Fall 2016-2017',172,1), (10054,'Fall 2016-2017',328,1), (10056,'Fall 2016-2017',274,1), (10057,'Fall 2016-2017',221,1), (10064,'Fall 2016-2017',332,1), (10066,'Fall 2016-2017',332,1), (10068,'Fall 2016-2017',99,1), (10070,'Fall 2016-2017',259,1), (10074,'Fall 2016-2017',90,1), (10075,'Fall 2016-2017',332,1), (10075,'Fall 2016-2017',99,0), (10065,'Fall 2016-2017',332,1), (10069,'Fall 2016-2017',99,1), (10071,'Fall 2016-2017',259,1), (10067,'Fall 2016-2017',332,1), (10077,'Fall 2016-2017',142,1), (11255,'Fall 2016-2017',241,1), (10078,'Fall 2016-2017',241,1), (10079,'Fall 2016-2017',259,1), (10080,'Fall 2016-2017',313,1), (10082,'Fall 2016-2017',332,1), (10083,'Fall 2016-2017',204,1), (10087,'Fall 2016-2017',90,1), (11559,'Fall 2016-2017',227,1), (11560,'Fall 2016-2017',20,1), (11561,'Fall 2016-2017',101,1), (11562,'Fall 2016-2017',299,1), (11725,'Fall 2016-2017',275,1), (11563,'Fall 2016-2017',275,1), (10965,'Fall 2016-2017',9,1), (10966,'Fall 2016-2017',9,1), (10967,'Fall 2016-2017',190,1), (10991,'Fall 2016-2017',9,1), (10991,'Fall 2016-2017',175,0), (10991,'Fall 2016-2017',37,0), (10992,'Fall 2016-2017',9,1), (10992,'Fall 2016-2017',110,0), (10993,'Fall 2016-2017',190,1), (10993,'Fall 2016-2017',60,0), (10968,'Fall 2016-2017',118,1), (10969,'Fall 2016-2017',118,1), (10970,'Fall 2016-2017',100,1), (10994,'Fall 2016-2017',118,1), (10994,'Fall 2016-2017',276,0), (10994,'Fall 2016-2017',96,0), (10995,'Fall 2016-2017',118,1), (10995,'Fall 2016-2017',247,0), (10996,'Fall 2016-2017',100,1), (10996,'Fall 2016-2017',167,0), (10971,'Fall 2016-2017',123,1), (10972,'Fall 2016-2017',123,1), (10973,'Fall 2016-2017',84,1), (10997,'Fall 2016-2017',123,1), (10997,'Fall 2016-2017',346,0), (10997,'Fall 2016-2017',137,0), (10998,'Fall 2016-2017',123,1), (10998,'Fall 2016-2017',180,0), (10999,'Fall 2016-2017',84,1), (10999,'Fall 2016-2017',347,0), (10088,'Fall 2016-2017',223,1), (11000,'Fall 2016-2017',223,1), (11000,'Fall 2016-2017',192,0), (10090,'Fall 2016-2017',289,1), (10092,'Fall 2016-2017',230,1), (10093,'Fall 2016-2017',234,1), (10094,'Fall 2016-2017',234,1), (10095,'Fall 2016-2017',216,1), (10097,'Fall 2016-2017',123,1), (10098,'Fall 2016-2017',84,1), (10101,'Fall 2016-2017',158,1), (10101,'Fall 2016-2017',234,0), (11009,'Fall 2016-2017',158,1), (11009,'Fall 2016-2017',234,0), (11009,'Fall 2016-2017',310,0), (10105,'Fall 2016-2017',8,1), (11013,'Fall 2016-2017',8,1), (11013,'Fall 2016-2017',6,0), (11013,'Fall 2016-2017',177,0), (10100,'Fall 2016-2017',158,1), (10100,'Fall 2016-2017',234,0), (11010,'Fall 2016-2017',158,1), (11010,'Fall 2016-2017',234,0), (11010,'Fall 2016-2017',310,0), (10102,'Fall 2016-2017',289,1), (11012,'Fall 2016-2017',289,1), (11012,'Fall 2016-2017',127,0), (10104,'Fall 2016-2017',8,1), (11014,'Fall 2016-2017',8,1), (11014,'Fall 2016-2017',6,0), (11014,'Fall 2016-2017',177,0), (10099,'Fall 2016-2017',84,1), (11256,'Fall 2016-2017',158,1), (10096,'Fall 2016-2017',216,1), (10107,'Fall 2016-2017',234,1), (10107,'Fall 2016-2017',158,0), (11257,'Fall 2016-2017',158,1), (10109,'Fall 2016-2017',216,1), (10110,'Fall 2016-2017',9,1), (10111,'Fall 2016-2017',289,1), (10112,'Fall 2016-2017',118,1), (10113,'Fall 2016-2017',84,1), (10114,'Fall 2016-2017',234,1), (10115,'Fall 2016-2017',8,1), (10116,'Fall 2016-2017',158,1), (10122,'Fall 2016-2017',158,1), (10123,'Fall 2016-2017',9,1), (10126,'Fall 2016-2017',216,1), (10419,'Fall 2016-2017',2,1), (10420,'Fall 2016-2017',2,1), (10420,'Fall 2016-2017',173,0), (10420,'Fall 2016-2017',337,0), (10421,'Fall 2016-2017',271,1), (10422,'Fall 2016-2017',271,1), (10422,'Fall 2016-2017',52,0), (10423,'Fall 2016-2017',85,1), (10424,'Fall 2016-2017',85,1), (10424,'Fall 2016-2017',283,0), (10425,'Fall 2016-2017',93,1), (10426,'Fall 2016-2017',93,1), (10426,'Fall 2016-2017',367,0), (10427,'Fall 2016-2017',309,1), (10428,'Fall 2016-2017',309,1), (10428,'Fall 2016-2017',10,0), (10429,'Fall 2016-2017',341,1), (10430,'Fall 2016-2017',341,1), (10430,'Fall 2016-2017',311,0), (10431,'Fall 2016-2017',271,1), (10433,'Fall 2016-2017',271,1), (10433,'Fall 2016-2017',147,0), (10434,'Fall 2016-2017',171,1), (10435,'Fall 2016-2017',171,1), (10435,'Fall 2016-2017',339,0), (10436,'Fall 2016-2017',130,1), (10437,'Fall 2016-2017',130,1), (10437,'Fall 2016-2017',112,0), (10438,'Fall 2016-2017',93,1), (10439,'Fall 2016-2017',93,1), (10439,'Fall 2016-2017',217,0), (10440,'Fall 2016-2017',39,1), (10441,'Fall 2016-2017',39,1), (10441,'Fall 2016-2017',195,0), (10432,'Fall 2016-2017',271,1), (10447,'Fall 2016-2017',61,1), (10448,'Fall 2016-2017',62,1), (11540,'Fall 2016-2017',271,1), (11541,'Fall 2016-2017',271,1), (10450,'Fall 2016-2017',39,1), (10443,'Fall 2016-2017',69,1), (11398,'Fall 2016-2017',309,1), (11405,'Fall 2016-2017',356,1), (11406,'Fall 2016-2017',85,1), (11408,'Fall 2016-2017',93,1), (11409,'Fall 2016-2017',2,1), (10451,'Fall 2016-2017',348,1), (10452,'Fall 2016-2017',155,1), (11710,'Fall 2016-2017',356,1), (11412,'Fall 2016-2017',69,1), (11414,'Fall 2016-2017',239,1), (11416,'Fall 2016-2017',171,1), (11417,'Fall 2016-2017',21,1), (11418,'Fall 2016-2017',309,1), (11421,'Fall 2016-2017',235,1), (11422,'Fall 2016-2017',356,1), (11427,'Fall 2016-2017',2,1), (11739,'Fall 2016-2017',160,1), (11604,'Fall 2016-2017',11,1), (11604,'Fall 2016-2017',16,0), (11607,'Fall 2016-2017',253,1), (11606,'Fall 2016-2017',253,1), (11605,'Fall 2016-2017',253,1), (10886,'Fall 2016-2017',138,1), (10887,'Fall 2016-2017',138,1), (10887,'Fall 2016-2017',270,0), (10986,'Fall 2016-2017',235,1), (10987,'Fall 2016-2017',235,1), (10987,'Fall 2016-2017',350,0), (10988,'Fall 2016-2017',235,1), (10988,'Fall 2016-2017',35,0), (10989,'Fall 2016-2017',235,1), (10989,'Fall 2016-2017',92,0), (10990,'Fall 2016-2017',235,1), (10990,'Fall 2016-2017',237,0), (10888,'Fall 2016-2017',87,1), (10889,'Fall 2016-2017',87,1), (10889,'Fall 2016-2017',336,0), (10889,'Fall 2016-2017',215,0), (10889,'Fall 2016-2017',95,0), (10889,'Fall 2016-2017',334,0), (10890,'Fall 2016-2017',21,1), (10891,'Fall 2016-2017',21,1), (10891,'Fall 2016-2017',287,0), (10892,'Fall 2016-2017',21,1), (10892,'Fall 2016-2017',277,0), (10893,'Fall 2016-2017',21,1), (10893,'Fall 2016-2017',157,0), (10894,'Fall 2016-2017',21,1), (10894,'Fall 2016-2017',316,0), (10895,'Fall 2016-2017',21,1), (10895,'Fall 2016-2017',31,0), (10896,'Fall 2016-2017',21,1), (10896,'Fall 2016-2017',269,0), (10897,'Fall 2016-2017',21,1), (10897,'Fall 2016-2017',19,0), (10898,'Fall 2016-2017',21,1), (10898,'Fall 2016-2017',238,0), (10899,'Fall 2016-2017',21,1), (10899,'Fall 2016-2017',128,0), (10900,'Fall 2016-2017',21,1), (10900,'Fall 2016-2017',272,0), (10901,'Fall 2016-2017',21,1), (10901,'Fall 2016-2017',291,0), (10902,'Fall 2016-2017',21,1), (10902,'Fall 2016-2017',159,0), (10903,'Fall 2016-2017',21,1), (10903,'Fall 2016-2017',226,0), (10904,'Fall 2016-2017',21,1), (10904,'Fall 2016-2017',245,0), (10876,'Fall 2016-2017',227,1), (10877,'Fall 2016-2017',227,1), (10878,'Fall 2016-2017',227,1), (10878,'Fall 2016-2017',303,0), (10878,'Fall 2016-2017',174,0), (10878,'Fall 2016-2017',209,0), (10878,'Fall 2016-2017',42,0), (10878,'Fall 2016-2017',94,0), (10878,'Fall 2016-2017',71,0), (10879,'Fall 2016-2017',227,1), (10879,'Fall 2016-2017',303,0), (10879,'Fall 2016-2017',174,0), (10879,'Fall 2016-2017',209,0), (10879,'Fall 2016-2017',42,0), (10879,'Fall 2016-2017',94,0), (10879,'Fall 2016-2017',71,0), (10880,'Fall 2016-2017',227,1), (10880,'Fall 2016-2017',303,0), (10880,'Fall 2016-2017',174,0), (10880,'Fall 2016-2017',209,0), (10880,'Fall 2016-2017',42,0), (10880,'Fall 2016-2017',94,0), (10880,'Fall 2016-2017',71,0), (10881,'Fall 2016-2017',227,1), (10881,'Fall 2016-2017',303,0), (10881,'Fall 2016-2017',174,0), (10881,'Fall 2016-2017',209,0), (10881,'Fall 2016-2017',42,0), (10881,'Fall 2016-2017',94,0), (10881,'Fall 2016-2017',71,0), (10882,'Fall 2016-2017',227,1), (10882,'Fall 2016-2017',303,0), (10882,'Fall 2016-2017',174,0), (10882,'Fall 2016-2017',209,0), (10882,'Fall 2016-2017',42,0), (10882,'Fall 2016-2017',94,0), (10882,'Fall 2016-2017',71,0), (10883,'Fall 2016-2017',227,1), (10883,'Fall 2016-2017',303,0), (10883,'Fall 2016-2017',174,0), (10883,'Fall 2016-2017',209,0), (10883,'Fall 2016-2017',42,0), (10883,'Fall 2016-2017',94,0), (10883,'Fall 2016-2017',71,0), (10884,'Fall 2016-2017',227,1), (10884,'Fall 2016-2017',303,0), (10884,'Fall 2016-2017',174,0), (10884,'Fall 2016-2017',209,0), (10884,'Fall 2016-2017',42,0), (10884,'Fall 2016-2017',94,0), (10884,'Fall 2016-2017',71,0), (10885,'Fall 2016-2017',227,1), (10885,'Fall 2016-2017',303,0), (10885,'Fall 2016-2017',174,0), (10885,'Fall 2016-2017',209,0), (10885,'Fall 2016-2017',42,0), (10885,'Fall 2016-2017',94,0), (10885,'Fall 2016-2017',71,0), (10905,'Fall 2016-2017',76,1), (11233,'Fall 2016-2017',49,1), (10906,'Fall 2016-2017',76,1), (10906,'Fall 2016-2017',286,0), (10907,'Fall 2016-2017',76,1), (10907,'Fall 2016-2017',114,0), (10908,'Fall 2016-2017',76,1), (10908,'Fall 2016-2017',200,0), (10909,'Fall 2016-2017',76,1), (10909,'Fall 2016-2017',135,0), (10910,'Fall 2016-2017',76,1), (10910,'Fall 2016-2017',54,0), (11234,'Fall 2016-2017',49,1), (11234,'Fall 2016-2017',322,0), (11235,'Fall 2016-2017',49,1), (11235,'Fall 2016-2017',156,0), (10911,'Fall 2016-2017',76,1), (10911,'Fall 2016-2017',286,0), (10912,'Fall 2016-2017',76,1), (10912,'Fall 2016-2017',114,0), (10913,'Fall 2016-2017',76,1), (10913,'Fall 2016-2017',200,0), (10914,'Fall 2016-2017',76,1), (10914,'Fall 2016-2017',135,0), (10915,'Fall 2016-2017',76,1), (10915,'Fall 2016-2017',54,0), (11236,'Fall 2016-2017',49,1), (11236,'Fall 2016-2017',322,0), (11237,'Fall 2016-2017',49,1), (11237,'Fall 2016-2017',156,0), (10874,'Fall 2016-2017',356,1), (11150,'Fall 2016-2017',356,1), (11150,'Fall 2016-2017',255,0), (11151,'Fall 2016-2017',356,1), (11151,'Fall 2016-2017',131,0), (11704,'Fall 2016-2017',356,1), (11704,'Fall 2016-2017',232,0), (10875,'Fall 2016-2017',356,1), (10875,'Fall 2016-2017',273,0), (11149,'Fall 2016-2017',356,1), (11149,'Fall 2016-2017',129,0), (11664,'Fall 2016-2017',178,1), (11665,'Fall 2016-2017',154,1), (11669,'Fall 2016-2017',297,1), (11671,'Fall 2016-2017',59,1), (11672,'Fall 2016-2017',45,1), (11620,'Fall 2016-2017',116,1), (11621,'Fall 2016-2017',280,1), (11622,'Fall 2016-2017',150,1), (11623,'Fall 2016-2017',213,1), (11624,'Fall 2016-2017',136,1), (11625,'Fall 2016-2017',13,1), (11626,'Fall 2016-2017',239,1), (11628,'Fall 2016-2017',171,1), (11630,'Fall 2016-2017',130,1), (11632,'Fall 2016-2017',356,1), (11635,'Fall 2016-2017',93,1), (11636,'Fall 2016-2017',2,1), (11643,'Fall 2016-2017',306,1), (11646,'Fall 2016-2017',87,1), (11647,'Fall 2016-2017',363,1), (11648,'Fall 2016-2017',46,1), (11650,'Fall 2016-2017',126,1), (11652,'Fall 2016-2017',26,1), (11653,'Fall 2016-2017',317,1), (11655,'Fall 2016-2017',77,1), (11657,'Fall 2016-2017',343,1), (11658,'Fall 2016-2017',39,1), (11659,'Fall 2016-2017',155,1), (11660,'Fall 2016-2017',256,1), (11662,'Fall 2016-2017',285,1), (11674,'Fall 2016-2017',122,1), (11675,'Fall 2016-2017',351,1), (11677,'Fall 2016-2017',222,1), (11678,'Fall 2016-2017',98,1), (11679,'Fall 2016-2017',170,1), (11680,'Fall 2016-2017',299,1), (11681,'Fall 2016-2017',220,1), (11682,'Fall 2016-2017',227,1), (11683,'Fall 2016-2017',290,1), (11684,'Fall 2016-2017',196,1), (11685,'Fall 2016-2017',11,1), (11686,'Fall 2016-2017',249,1), (11687,'Fall 2016-2017',357,1), (11688,'Fall 2016-2017',211,1), (11689,'Fall 2016-2017',38,1), (11690,'Fall 2016-2017',76,1), (11698,'Fall 2016-2017',50,1), (11718,'Fall 2016-2017',161,1), (11719,'Fall 2016-2017',219,1), (11720,'Fall 2016-2017',253,1), (11722,'Fall 2016-2017',15,1), (11724,'Fall 2016-2017',121,1), (11738,'Fall 2016-2017',323,1), (11693,'Fall 2016-2017',59,1), (11693,'Fall 2016-2017',48,0), (11693,'Fall 2016-2017',203,0), (11693,'Fall 2016-2017',120,0), (11693,'Fall 2016-2017',0,0), (11693,'Fall 2016-2017',358,0), (11693,'Fall 2016-2017',83,0), (11694,'Fall 2016-2017',59,1), (11694,'Fall 2016-2017',48,0), (11694,'Fall 2016-2017',203,0), (11694,'Fall 2016-2017',120,0), (11694,'Fall 2016-2017',0,0), (11694,'Fall 2016-2017',358,0), (11694,'Fall 2016-2017',83,0), (11300,'Fall 2016-2017',323,1), (11301,'Fall 2016-2017',122,1), (11303,'Fall 2016-2017',250,1), (11304,'Fall 2016-2017',178,1), (11305,'Fall 2016-2017',222,1), (11306,'Fall 2016-2017',138,1), (11307,'Fall 2016-2017',154,1), (11308,'Fall 2016-2017',18,1), (11309,'Fall 2016-2017',150,1), (11310,'Fall 2016-2017',170,1), (11311,'Fall 2016-2017',47,1), (11312,'Fall 2016-2017',220,1), (11313,'Fall 2016-2017',213,1), (11314,'Fall 2016-2017',77,1), (11315,'Fall 2016-2017',130,1), (11316,'Fall 2016-2017',87,1), (11317,'Fall 2016-2017',343,1), (11318,'Fall 2016-2017',39,1), (11319,'Fall 2016-2017',356,1), (11320,'Fall 2016-2017',249,1), (11321,'Fall 2016-2017',85,1), (11322,'Fall 2016-2017',13,1), (11323,'Fall 2016-2017',357,1), (11324,'Fall 2016-2017',211,1), (11325,'Fall 2016-2017',38,1), (11326,'Fall 2016-2017',155,1), (11327,'Fall 2016-2017',76,1), (11328,'Fall 2016-2017',285,1), (11329,'Fall 2016-2017',317,1), (11330,'Fall 2016-2017',72,1), (11603,'Fall 2016-2017',280,1), (11721,'Fall 2016-2017',136,1), (11723,'Fall 2016-2017',253,1), (11745,'Fall 2016-2017',317,1), (10454,'Fall 2016-2017',85,1), (10455,'Fall 2016-2017',284,1), (10238,'Fall 2016-2017',185,1), (10238,'Fall 2016-2017',335,0), (10239,'Fall 2016-2017',335,1), (10239,'Fall 2016-2017',251,0), (10242,'Fall 2016-2017',353,1), (10242,'Fall 2016-2017',362,0), (10251,'Fall 2016-2017',89,1), (10251,'Fall 2016-2017',104,0), (10251,'Fall 2016-2017',359,0), (10253,'Fall 2016-2017',186,1), (10253,'Fall 2016-2017',338,0), (10253,'Fall 2016-2017',359,0), (10255,'Fall 2016-2017',338,1), (10255,'Fall 2016-2017',186,0), (10255,'Fall 2016-2017',17,0), (10258,'Fall 2016-2017',307,1), (10258,'Fall 2016-2017',23,0), (10258,'Fall 2016-2017',17,0), (10264,'Fall 2016-2017',104,1), (10264,'Fall 2016-2017',89,0), (10264,'Fall 2016-2017',107,0), (10265,'Fall 2016-2017',107,1), (10265,'Fall 2016-2017',117,0), (10267,'Fall 2016-2017',23,1), (10267,'Fall 2016-2017',152,0), (10267,'Fall 2016-2017',354,0), (10290,'Fall 2016-2017',340,1), (10290,'Fall 2016-2017',115,0), (10292,'Fall 2016-2017',201,1), (10292,'Fall 2016-2017',151,0), (10293,'Fall 2016-2017',146,1), (10293,'Fall 2016-2017',340,0), (10293,'Fall 2016-2017',184,0), (10295,'Fall 2016-2017',151,1), (10295,'Fall 2016-2017',279,0), (10295,'Fall 2016-2017',201,0), (10296,'Fall 2016-2017',97,1), (10296,'Fall 2016-2017',65,0), (10297,'Fall 2016-2017',5,1), (10297,'Fall 2016-2017',57,0), (10297,'Fall 2016-2017',97,0), (10298,'Fall 2016-2017',57,1), (10298,'Fall 2016-2017',262,0), (10299,'Fall 2016-2017',262,1), (10299,'Fall 2016-2017',146,0), (10299,'Fall 2016-2017',5,0), (10300,'Fall 2016-2017',184,1), (10300,'Fall 2016-2017',246,0), (10300,'Fall 2016-2017',75,0), (10301,'Fall 2016-2017',115,1), (10301,'Fall 2016-2017',246,0), (10301,'Fall 2016-2017',75,0), (10304,'Fall 2016-2017',132,1), (10304,'Fall 2016-2017',56,0), (10304,'Fall 2016-2017',78,0), (10305,'Fall 2016-2017',29,1), (10305,'Fall 2016-2017',132,0), (10306,'Fall 2016-2017',329,1), (10306,'Fall 2016-2017',326,0), (10306,'Fall 2016-2017',304,0), (10307,'Fall 2016-2017',304,1), (10307,'Fall 2016-2017',29,0), (10307,'Fall 2016-2017',140,0), (10308,'Fall 2016-2017',43,1), (10308,'Fall 2016-2017',298,0), (10308,'Fall 2016-2017',319,0), (10309,'Fall 2016-2017',319,1), (10309,'Fall 2016-2017',329,0), (10309,'Fall 2016-2017',298,0), (10310,'Fall 2016-2017',166,1), (10310,'Fall 2016-2017',43,0), (10310,'Fall 2016-2017',78,0), (10313,'Fall 2016-2017',302,1), (10313,'Fall 2016-2017',224,0), (10315,'Fall 2016-2017',53,1), (10315,'Fall 2016-2017',152,0), (10315,'Fall 2016-2017',79,0), (10316,'Fall 2016-2017',140,1), (10316,'Fall 2016-2017',352,0), (10316,'Fall 2016-2017',32,0), (10318,'Fall 2016-2017',224,1), (10318,'Fall 2016-2017',53,0), (10318,'Fall 2016-2017',302,0), (10320,'Fall 2016-2017',119,1), (10320,'Fall 2016-2017',80,0), (10320,'Fall 2016-2017',312,0), (10322,'Fall 2016-2017',312,1), (10322,'Fall 2016-2017',80,0), (10322,'Fall 2016-2017',119,0), (11600,'Fall 2016-2017',32,1), (11600,'Fall 2016-2017',326,0), (11600,'Fall 2016-2017',102,0), (11601,'Fall 2016-2017',102,1), (11601,'Fall 2016-2017',298,0), (11601,'Fall 2016-2017',166,0), (11602,'Fall 2016-2017',352,1), (11602,'Fall 2016-2017',152,0), (11602,'Fall 2016-2017',79,0), (10585,'Fall 2016-2017',236,1), (10586,'Fall 2016-2017',193,1), (10587,'Fall 2016-2017',314,1), (10588,'Fall 2016-2017',260,1), (10589,'Fall 2016-2017',231,1), (10590,'Fall 2016-2017',182,1), (10591,'Fall 2016-2017',162,1), (10592,'Fall 2016-2017',55,1), (10593,'Fall 2016-2017',236,1), (10594,'Fall 2016-2017',193,1), (10595,'Fall 2016-2017',314,1), (10596,'Fall 2016-2017',260,1), (10597,'Fall 2016-2017',231,1), (10598,'Fall 2016-2017',182,1), (10599,'Fall 2016-2017',162,1), (10600,'Fall 2016-2017',55,1), (10601,'Fall 2016-2017',236,1), (10602,'Fall 2016-2017',193,1), (10603,'Fall 2016-2017',314,1), (10604,'Fall 2016-2017',260,1), (10605,'Fall 2016-2017',231,1), (10606,'Fall 2016-2017',182,1), (10607,'Fall 2016-2017',162,1), (10608,'Fall 2016-2017',55,1), (10609,'Fall 2016-2017',236,1), (10610,'Fall 2016-2017',193,1), (10611,'Fall 2016-2017',314,1), (10612,'Fall 2016-2017',260,1), (10613,'Fall 2016-2017',231,1), (10614,'Fall 2016-2017',182,1), (10615,'Fall 2016-2017',162,1), (10616,'Fall 2016-2017',55,1), (10623,'Fall 2016-2017',125,1), (10624,'Fall 2016-2017',344,1), (10625,'Fall 2016-2017',325,1), (10620,'Fall 2016-2017',125,1), (10621,'Fall 2016-2017',344,1), (10622,'Fall 2016-2017',325,1), (10626,'Fall 2016-2017',125,1), (10627,'Fall 2016-2017',344,1), (10628,'Fall 2016-2017',325,1), (11280,'Fall 2016-2017',300,1), (10617,'Fall 2016-2017',125,1), (10618,'Fall 2016-2017',344,1), (10619,'Fall 2016-2017',325,1), (11027,'Fall 2016-2017',300,1), (11028,'Fall 2016-2017',300,1), (11029,'Fall 2016-2017',300,1), (10127,'Fall 2016-2017',274,1), (10130,'Fall 2016-2017',113,1), (10007,'Fall 2016-2017',292,1), (10008,'Fall 2016-2017',292,1), (10009,'Fall 2016-2017',292,1), (10010,'Fall 2016-2017',292,1), (10011,'Fall 2016-2017',12,1), (10012,'Fall 2016-2017',257,1), (10014,'Fall 2016-2017',168,1), (11129,'Fall 2016-2017',168,1), (11129,'Fall 2016-2017',12,0), (11217,'Fall 2016-2017',40,1), (11218,'Fall 2016-2017',12,1), (11219,'Fall 2016-2017',12,1), (11220,'Fall 2016-2017',168,1), (11221,'Fall 2016-2017',233,1), (11177,'Fall 2016-2017',40,1), (11222,'Fall 2016-2017',40,1), (11223,'Fall 2016-2017',257,1), (11224,'Fall 2016-2017',1,1), (11225,'Fall 2016-2017',168,1), (11226,'Fall 2016-2017',292,1), (11227,'Fall 2016-2017',257,1), (11228,'Fall 2016-2017',168,1), (11229,'Fall 2016-2017',333,1), (11230,'Fall 2016-2017',242,1), (11030,'Fall 2016-2017',248,1), (11031,'Fall 2016-2017',248,1), (11032,'Fall 2016-2017',248,1), (11033,'Fall 2016-2017',248,1), (11036,'Fall 2016-2017',199,1), (11037,'Fall 2016-2017',199,1), (11038,'Fall 2016-2017',199,1), (11039,'Fall 2016-2017',199,1), (10140,'Fall 2016-2017',143,1), (10141,'Fall 2016-2017',164,1), (10142,'Fall 2016-2017',181,1), (10144,'Fall 2016-2017',331,1), (10143,'Fall 2016-2017',181,1), (10145,'Fall 2016-2017',331,1), (10629,'Fall 2016-2017',321,1), (10630,'Fall 2016-2017',243,1), (10631,'Fall 2016-2017',305,1), (10633,'Fall 2016-2017',305,1), (10632,'Fall 2016-2017',321,1), (10146,'Fall 2016-2017',364,1), (11253,'Fall 2016-2017',194,1), (11118,'Fall 2016-2017',318,1), (10147,'Fall 2016-2017',243,1), (10148,'Fall 2016-2017',364,1), (10150,'Fall 2016-2017',294,1), (10151,'Fall 2016-2017',66,1), (11125,'Fall 2016-2017',318,1), (11119,'Fall 2016-2017',318,1), (11120,'Fall 2016-2017',294,1), (10149,'Fall 2016-2017',364,1), (10155,'Fall 2016-2017',294,1), (10157,'Fall 2016-2017',294,1), (10158,'Fall 2016-2017',243,1), (10159,'Fall 2016-2017',315,1), (10160,'Fall 2016-2017',321,1), (11121,'Fall 2016-2017',70,1), (10163,'Fall 2016-2017',70,1), (10164,'Fall 2016-2017',294,1), (10165,'Fall 2016-2017',243,1), (11755,'Fall 2016-2017',66,1), (10634,'Fall 2016-2017',3,1), (10635,'Fall 2016-2017',3,1), (10636,'Fall 2016-2017',181,1), (10637,'Fall 2016-2017',181,1), (10637,'Fall 2016-2017',258,0), (10638,'Fall 2016-2017',181,1), (10638,'Fall 2016-2017',67,0), (10639,'Fall 2016-2017',181,1), (10639,'Fall 2016-2017',24,0), (10641,'Fall 2016-2017',181,1), (10641,'Fall 2016-2017',258,0), (10642,'Fall 2016-2017',181,1), (10642,'Fall 2016-2017',67,0), (10643,'Fall 2016-2017',181,1), (10643,'Fall 2016-2017',24,0), (10645,'Fall 2016-2017',294,1), (10646,'Fall 2016-2017',294,1), (10646,'Fall 2016-2017',355,0), (10647,'Fall 2016-2017',294,1), (10647,'Fall 2016-2017',355,0), (10648,'Fall 2016-2017',41,1), (10648,'Fall 2016-2017',124,0), (10649,'Fall 2016-2017',342,1), (10650,'Fall 2016-2017',124,1), (10651,'Fall 2016-2017',124,1), (10651,'Fall 2016-2017',105,0), (10652,'Fall 2016-2017',124,1), (10653,'Fall 2016-2017',124,1), (10653,'Fall 2016-2017',105,0), (10654,'Fall 2016-2017',342,1), (10654,'Fall 2016-2017',288,0), (10655,'Fall 2016-2017',342,1), (10655,'Fall 2016-2017',288,0), (10656,'Fall 2016-2017',33,1), (10657,'Fall 2016-2017',33,1), (10658,'Fall 2016-2017',282,1), (10659,'Fall 2016-2017',282,1), (10660,'Fall 2016-2017',164,1), (10661,'Fall 2016-2017',164,1), (10661,'Fall 2016-2017',189,0), (10662,'Fall 2016-2017',164,1), (10662,'Fall 2016-2017',265,0), (10663,'Fall 2016-2017',164,1), (10663,'Fall 2016-2017',189,0), (10664,'Fall 2016-2017',164,1), (10664,'Fall 2016-2017',265,0), (10665,'Fall 2016-2017',124,1), (10666,'Fall 2016-2017',124,1), (10666,'Fall 2016-2017',73,0), (10667,'Fall 2016-2017',124,1), (10667,'Fall 2016-2017',73,0), (10668,'Fall 2016-2017',33,1), (10669,'Fall 2016-2017',282,1), (10670,'Fall 2016-2017',282,1), (10938,'Fall 2016-2017',196,1), (10939,'Fall 2016-2017',196,1), (10940,'Fall 2016-2017',196,1), (10941,'Fall 2016-2017',196,1), (10942,'Fall 2016-2017',196,1), (10944,'Fall 2016-2017',196,1), (10456,'Fall 2016-2017',220,1), (10456,'Fall 2016-2017',357,0), (10457,'Fall 2016-2017',220,1), (10457,'Fall 2016-2017',357,0), (10458,'Fall 2016-2017',220,1), (10458,'Fall 2016-2017',357,0), (10459,'Fall 2016-2017',220,1), (10459,'Fall 2016-2017',360,0), (10459,'Fall 2016-2017',357,0), (10460,'Fall 2016-2017',220,1), (10460,'Fall 2016-2017',264,0), (10460,'Fall 2016-2017',357,0), (10461,'Fall 2016-2017',220,1), (10461,'Fall 2016-2017',357,0), (10462,'Fall 2016-2017',220,1), (10462,'Fall 2016-2017',357,0), (10463,'Fall 2016-2017',220,1), (10463,'Fall 2016-2017',163,0), (10463,'Fall 2016-2017',357,0), (10464,'Fall 2016-2017',205,1), (10465,'Fall 2016-2017',205,1), (10465,'Fall 2016-2017',293,0), (10466,'Fall 2016-2017',205,1), (10466,'Fall 2016-2017',293,0), (10467,'Fall 2016-2017',205,1), (10467,'Fall 2016-2017',153,0), (10467,'Fall 2016-2017',293,0), (10468,'Fall 2016-2017',170,1), (10469,'Fall 2016-2017',170,1), (10470,'Fall 2016-2017',170,1), (10470,'Fall 2016-2017',82,0), (10471,'Fall 2016-2017',170,1), (10471,'Fall 2016-2017',361,0), (10472,'Fall 2016-2017',170,1), (10472,'Fall 2016-2017',63,0), (10473,'Fall 2016-2017',170,1), (10473,'Fall 2016-2017',106,0), (10474,'Fall 2016-2017',170,1), (10475,'Fall 2016-2017',351,1), (10476,'Fall 2016-2017',351,1), (10477,'Fall 2016-2017',351,1), (10477,'Fall 2016-2017',169,0), (10477,'Fall 2016-2017',330,0), (10478,'Fall 2016-2017',351,1), (10478,'Fall 2016-2017',58,0), (10478,'Fall 2016-2017',44,0), (10479,'Fall 2016-2017',250,1), (10480,'Fall 2016-2017',250,1), (10480,'Fall 2016-2017',214,0), (10481,'Fall 2016-2017',250,1), (10481,'Fall 2016-2017',206,0), (10482,'Fall 2016-2017',250,1), (10482,'Fall 2016-2017',308,0), (10484,'Fall 2016-2017',249,1), (10485,'Fall 2016-2017',249,1), (10486,'Fall 2016-2017',249,1), (10486,'Fall 2016-2017',176,0), (10487,'Fall 2016-2017',249,1), (10488,'Fall 2016-2017',249,1), (10491,'Fall 2016-2017',266,1), (10492,'Fall 2016-2017',266,1), (10492,'Fall 2016-2017',278,0), (10493,'Fall 2016-2017',266,1), (10493,'Fall 2016-2017',4,0), (10494,'Fall 2016-2017',266,1), (10494,'Fall 2016-2017',252,0), (10495,'Fall 2016-2017',27,1), (10496,'Fall 2016-2017',27,1), (10496,'Fall 2016-2017',133,0), (10497,'Fall 2016-2017',27,1), (10497,'Fall 2016-2017',14,0), (10498,'Fall 2016-2017',11,1), (10499,'Fall 2016-2017',11,1), (10499,'Fall 2016-2017',74,0), (10500,'Fall 2016-2017',11,1), (10500,'Fall 2016-2017',109,0), (11157,'Fall 2016-2017',11,1), (11702,'Fall 2016-2017',11,1), (11702,'Fall 2016-2017',228,0), (10501,'Fall 2016-2017',257,1), (10502,'Fall 2016-2017',122,1), (11158,'Fall 2016-2017',285,1), (11192,'Fall 2016-2017',285,1), (11192,'Fall 2016-2017',324,0), (11193,'Fall 2016-2017',285,1), (11193,'Fall 2016-2017',81,0), (10503,'Fall 2016-2017',50,1), (10504,'Fall 2016-2017',50,1), (10504,'Fall 2016-2017',202,0), (10506,'Fall 2016-2017',222,1), (10508,'Fall 2016-2017',72,1), (10509,'Fall 2016-2017',11,1), (10510,'Fall 2016-2017',290,1), (10511,'Fall 2016-2017',38,1), (10512,'Fall 2016-2017',299,1), (10516,'Fall 2016-2017',290,1), (11552,'Fall 2016-2017',122,1), (11553,'Fall 2016-2017',122,1), (10513,'Fall 2016-2017',98,1), (10514,'Fall 2016-2017',98,1), (10515,'Fall 2016-2017',250,1), (11711,'Fall 2016-2017',222,1), (11712,'Fall 2016-2017',211,1), (11430,'Fall 2016-2017',250,1), (11431,'Fall 2016-2017',222,1), (11433,'Fall 2016-2017',98,1), (11436,'Fall 2016-2017',299,1), (11442,'Fall 2016-2017',227,1), (11443,'Fall 2016-2017',290,1), (11445,'Fall 2016-2017',196,1), (11448,'Fall 2016-2017',351,1), (11450,'Fall 2016-2017',211,1), (11451,'Fall 2016-2017',122,1), (11455,'Fall 2016-2017',38,1), (11537,'Fall 2016-2017',122,1), (11458,'Fall 2016-2017',357,1), (11460,'Fall 2016-2017',250,1), (11462,'Fall 2016-2017',222,1), (11467,'Fall 2016-2017',299,1), (11470,'Fall 2016-2017',220,1), (11473,'Fall 2016-2017',290,1), (11569,'Fall 2016-2017',197,1), (11573,'Fall 2016-2017',349,1), (11575,'Fall 2016-2017',323,1), (11608,'Fall 2016-2017',323,1), (11570,'Fall 2016-2017',149,1), (11579,'Fall 2016-2017',275,1), (10518,'Fall 2016-2017',365,1), (11002,'Fall 2016-2017',113,1), (11003,'Fall 2016-2017',113,1), (11003,'Fall 2016-2017',210,0), (11004,'Fall 2016-2017',113,1), (11004,'Fall 2016-2017',210,0), (10170,'Fall 2016-2017',221,1), (10171,'Fall 2016-2017',254,1), (10172,'Fall 2016-2017',328,1), (11042,'Fall 2016-2017',36,1), (11043,'Fall 2016-2017',36,1), (11047,'Fall 2016-2017',366,1), (11048,'Fall 2016-2017',366,1), (11051,'Fall 2016-2017',366,1), (11052,'Fall 2016-2017',366,1), (11055,'Fall 2016-2017',366,1), (11057,'Fall 2016-2017',366,1), (11049,'Fall 2016-2017',366,1), (11050,'Fall 2016-2017',366,1), (11053,'Fall 2016-2017',366,1), (11054,'Fall 2016-2017',366,1), (11056,'Fall 2016-2017',366,1), (11058,'Fall 2016-2017',366,1), (10173,'Fall 2016-2017',99,1), (10174,'Fall 2016-2017',99,1); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `meeting_instructors` ( `m_id` INT NOT NULL, `i_id` INT NOT NULL, PRIMARY KEY (`m_id`, `i_id`), FOREIGN KEY (`m_id`) REFERENCES meetings(`m_id`), FOREIGN KEY (`i_id`) REFERENCES instructors(`i_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `meeting_instructors` (`m_id`, `i_id`) VALUES (0,320), (1,320), (2,320), (3,320), (3,212), (3,165), (4,320), (4,212), (4,165), (5,320), (5,212), (5,165), (6,320), (6,212), (6,165), (7,320), (7,212), (7,165), (8,320), (8,212), (8,165), (9,320), (10,320), (10,212), (10,165), (11,263), (12,7), (13,7), (14,301), (15,327), (16,327), (17,327), (18,327), (19,327), (20,327), (21,296), (22,296), (23,296), (24,296), (25,296), (26,296), (27,296), (28,296), (29,242), (30,242), (31,242), (32,108), (33,108), (34,108), (35,108), (36,108), (37,108), (38,108), (39,108), (40,108), (41,108), (42,108), (43,108), (44,144), (45,144), (46,144), (47,144), (48,91), (49,91), (50,91), (51,139), (52,139), (53,139), (54,179), (55,179), (56,30), (57,233), (58,240), (59,233), (60,284), (61,284), (62,284), (62,88), (62,218), (63,46), (64,46), (65,46), (66,46), (67,145), (68,145), (69,145), (70,145), (71,145), (72,145), (73,145), (74,145), (75,145), (76,145), (77,145), (78,145), (79,145), (80,145), (81,145), (82,145), (83,145), (84,145), (85,145), (86,145), (87,145), (88,145), (89,145), (90,145), (91,145), (92,145), (93,145), (94,145), (95,145), (96,145), (97,145), (98,145), (99,145), (100,145), (101,145), (102,145), (103,145), (104,145), (105,188), (106,188), (107,188), (107,261), (108,188), (108,183), (109,188), (109,148), (110,188), (110,295), (111,188), (112,188), (112,207), (113,188), (113,281), (114,188), (114,25), (115,188), (115,68), (116,188), (116,267), (117,188), (117,207), (118,188), (118,86), (119,188), (119,198), (120,188), (120,267), (121,188), (121,208), (122,188), (123,188), (123,217), (124,136), (125,136), (126,136), (126,229), (127,136), (128,136), (128,229), (129,136), (130,280), (131,280), (132,280), (132,191), (132,134), (133,345), (134,345), (135,345), (135,268), (136,309), (137,309), (137,64), (138,309), (138,34), (138,225), (139,309), (139,51), (139,64), (140,309), (140,34), (141,309), (141,51), (142,309), (142,225), (143,309), (143,34), (143,225), (143,51), (143,64), (144,239), (145,239), (146,239), (146,103), (147,150), (148,150), (149,213), (150,213), (151,13), (152,13), (153,13), (153,141), (154,116), (155,116), (156,116), (156,22), (156,244), (156,28), (157,116), (157,22), (157,244), (157,28), (158,116), (158,22), (158,244), (158,28), (159,150), (160,150), (161,130), (162,130), (163,150), (164,150), (165,213), (166,213), (167,239), (168,239), (169,116), (170,116), (171,13), (172,13), (173,150), (174,280), (175,280), (176,116), (177,18), (178,150), (179,213), (180,239), (181,116), (182,160), (183,280), (184,18), (185,356), (186,13), (187,239), (188,111), (189,111), (190,328), (191,274), (192,274), (193,187), (194,241), (195,111), (196,172), (197,328), (198,274), (199,221), (200,332), (201,332), (202,99), (203,259), (204,90), (205,332), (205,99), (206,332), (207,99), (208,259), (209,332), (210,142), (211,241), (212,241), (213,259), (214,313), (215,332), (216,204), (217,90), (218,227), (219,227), (220,20), (221,20), (222,101), (223,101), (224,299), (225,299), (226,275), (227,275), (228,9), (229,9), (230,9), (231,9), (232,190), (233,190), (234,9), (234,175), (234,37), (235,9), (235,110), (236,190), (236,60), (237,118), (238,118), (239,118), (240,118), (241,100), (242,100), (243,118), (243,276), (243,96), (244,118), (244,247), (245,100), (245,167), (246,123), (247,123), (248,123), (249,123), (250,84), (251,84), (252,123), (252,346), (252,137), (253,123), (253,180), (254,84), (254,347), (255,223), (256,223), (256,192), (257,289), (258,230), (259,230), (260,234), (261,234), (262,216), (263,123), (264,123), (265,84), (266,158), (266,234), (267,158), (267,234), (267,310), (268,8), (269,8), (269,6), (269,177), (270,158), (270,234), (271,158), (271,234), (271,310), (272,289), (273,289), (273,127), (274,8), (275,8), (275,6), (275,177), (276,84), (277,158), (278,216), (279,234), (279,158), (280,158), (281,216), (282,9), (283,289), (284,118), (285,84), (286,234), (287,8), (288,158), (289,158), (290,9), (291,216), (292,2), (293,2), (294,2), (294,173), (294,337), (295,271), (296,271), (297,271), (297,52), (298,85), (299,85), (300,85), (300,283), (301,93), (302,93), (303,93), (303,367), (304,309), (305,309), (306,309), (306,10), (307,341), (308,341), (309,341), (309,311), (310,271), (311,271), (311,147), (312,171), (313,171), (314,171), (314,339), (315,130), (316,130), (317,130), (317,112), (318,93), (319,93), (320,93), (320,217), (321,39), (322,39), (323,39), (323,195), (324,271), (325,61), (326,61), (327,62), (328,62), (329,271), (330,271), (331,39), (332,39), (333,69), (334,69), (335,309), (336,356), (337,85), (338,93), (339,2), (340,348), (341,155), (342,155), (343,356), (344,69), (345,239), (346,171), (347,21), (348,309), (349,235), (350,356), (351,2), (352,160), (353,11), (353,16), (354,11), (354,16), (355,253), (356,253), (357,253), (358,253), (359,253), (360,138), (361,138), (362,138), (362,270), (363,235), (364,235), (365,235), (365,350), (366,235), (366,35), (367,235), (367,92), (368,235), (368,237), (369,87), (370,87), (371,87), (371,336), (371,215), (371,95), (371,334), (372,21), (373,21), (374,21), (374,287), (375,21), (375,277), (376,21), (376,157), (377,21), (377,316), (378,21), (378,31), (379,21), (379,269), (380,21), (380,19), (381,21), (381,238), (382,21), (382,128), (383,21), (383,272), (384,21), (384,291), (385,21), (385,159), (386,21), (386,226), (387,21), (387,245), (388,227), (389,227), (390,227), (391,227), (392,227), (392,303), (392,174), (392,209), (392,42), (392,94), (392,71), (393,227), (393,303), (393,174), (393,209), (393,42), (393,94), (393,71), (394,227), (394,303), (394,174), (394,209), (394,42), (394,94), (394,71), (395,227), (395,303), (395,174), (395,209), (395,42), (395,94), (395,71), (396,227), (396,303), (396,174), (396,209), (396,42), (396,94), (396,71), (397,227), (397,303), (397,174), (397,209), (397,42), (397,94), (397,71), (398,227), (398,303), (398,174), (398,209), (398,42), (398,94), (398,71), (399,227), (399,303), (399,174), (399,209), (399,42), (399,94), (399,71), (400,76), (401,76), (402,49), (403,49), (404,76), (404,286), (405,76), (405,114), (406,76), (406,200), (407,76), (407,135), (408,76), (408,54), (409,49), (409,322), (410,49), (410,156), (411,76), (411,286), (412,76), (412,114), (413,76), (413,200), (414,76), (414,135), (415,76), (415,54), (416,49), (416,322), (417,49), (417,156), (418,356), (419,356), (420,356), (420,255), (421,356), (421,131), (422,356), (422,232), (423,356), (423,273), (424,356), (424,129), (425,178), (426,154), (427,297), (428,59), (429,45), (430,116), (431,280), (432,150), (433,213), (434,136), (435,13), (436,239), (437,171), (438,130), (439,356), (440,93), (441,2), (442,306), (443,87), (444,363), (445,46), (446,126), (447,26), (448,317), (449,77), (450,343), (451,39), (452,155), (453,256), (454,285), (455,122), (456,351), (457,222), (458,98), (459,170), (460,299), (461,220), (462,227), (463,290), (464,196), (465,11), (466,249), (467,357), (468,211), (469,38), (470,76), (471,50), (472,161), (473,219), (474,253), (475,15), (476,121), (477,323), (478,59), (478,48), (478,203), (478,120), (478,0), (478,358), (478,83), (479,59), (479,48), (479,203), (479,120), (479,0), (479,358), (479,83), (480,323), (481,122), (482,250), (483,178), (484,222), (485,138), (486,154), (487,18), (488,150), (489,170), (490,47), (491,220), (492,213), (493,77), (494,130), (495,87), (496,343), (497,39), (498,356), (499,249), (500,85), (501,13), (502,357), (503,211), (504,38), (505,155), (506,76), (507,285), (508,317), (509,72), (510,280), (511,136), (512,253), (513,317), (514,85), (515,85), (516,284), (517,284), (518,185), (518,335), (519,185), (519,335), (520,185), (520,335), (521,185), (521,335), (522,185), (522,335), (523,335), (523,251), (524,335), (524,251), (525,335), (525,251), (526,335), (526,251), (527,335), (527,251), (528,353), (528,362), (529,353), (529,362), (530,353), (530,362), (531,353), (531,362), (532,353), (532,362), (533,89), (533,104), (533,359), (534,89), (534,104), (534,359), (535,89), (535,104), (535,359), (536,89), (536,104), (536,359), (537,89), (537,104), (537,359), (538,186), (538,338), (538,359), (539,186), (539,338), (539,359), (540,186), (540,338), (540,359), (541,186), (541,338), (541,359), (542,186), (542,338), (542,359), (543,338), (543,186), (543,17), (544,338), (544,186), (544,17), (545,338), (545,186), (545,17), (546,338), (546,186), (546,17), (547,338), (547,186), (547,17), (548,307), (548,23), (548,17), (549,307), (549,23), (549,17), (550,307), (550,23), (550,17), (551,307), (551,23), (551,17), (552,307), (552,23), (552,17), (553,104), (553,89), (553,107), (554,104), (554,89), (554,107), (555,104), (555,89), (555,107), (556,104), (556,89), (556,107), (557,104), (557,89), (557,107), (558,107), (558,117), (559,107), (559,117), (560,107), (560,117), (561,107), (561,117), (562,107), (562,117), (563,23), (563,152), (563,354), (564,23), (564,152), (564,354), (565,23), (565,152), (565,354), (566,23), (566,152), (566,354), (567,23), (567,152), (567,354), (568,340), (568,115), (569,340), (569,115), (570,340), (570,115), (571,340), (571,115), (572,340), (572,115), (573,201), (573,151), (574,201), (574,151), (575,201), (575,151), (576,201), (576,151), (577,201), (577,151), (578,146), (578,340), (578,184), (579,146), (579,340), (579,184), (580,146), (580,340), (580,184), (581,146), (581,340), (581,184), (582,146), (582,340), (582,184), (583,151), (583,279), (583,201), (584,151), (584,279), (584,201), (585,151), (585,279), (585,201), (586,151), (586,279), (586,201), (587,151), (587,279), (587,201), (588,97), (588,65), (589,97), (589,65), (590,97), (590,65), (591,97), (591,65), (592,97), (592,65), (593,5), (593,57), (593,97), (594,5), (594,57), (594,97), (595,5), (595,57), (595,97), (596,5), (596,57), (596,97), (597,5), (597,57), (597,97), (598,57), (598,262), (599,57), (599,262), (600,57), (600,262), (601,57), (601,262), (602,57), (602,262), (603,262), (603,146), (603,5), (604,262), (604,146), (604,5), (605,262), (605,146), (605,5), (606,262), (606,146), (606,5), (607,262), (607,146), (607,5), (608,184), (608,246), (608,75), (609,184), (609,246), (609,75), (610,184), (610,246), (610,75), (611,184), (611,246), (611,75), (612,184), (612,246), (612,75), (613,115), (613,246), (613,75), (614,115), (614,246), (614,75), (615,115), (615,246), (615,75), (616,115), (616,246), (616,75), (617,115), (617,246), (617,75), (618,132), (618,56), (618,78), (619,132), (619,56), (619,78), (620,132), (620,56), (620,78), (621,132), (621,56), (621,78), (622,132), (622,56), (622,78), (623,29), (623,132), (624,29), (624,132), (625,29), (625,132), (626,29), (626,132), (627,29), (627,132), (628,329), (628,326), (628,304), (629,329), (629,326), (629,304), (630,329), (630,326), (630,304), (631,329), (631,326), (631,304), (632,329), (632,326), (632,304), (633,304), (633,29), (633,140), (634,304), (634,29), (634,140), (635,304), (635,29), (635,140), (636,304), (636,29), (636,140), (637,304), (637,29), (637,140), (638,43), (638,298), (638,319), (639,43), (639,298), (639,319), (640,43), (640,298), (640,319), (641,43), (641,298), (641,319), (642,43), (642,298), (642,319), (643,319), (643,329), (643,298), (644,319), (644,329), (644,298), (645,319), (645,329), (645,298), (646,319), (646,329), (646,298), (647,319), (647,329), (647,298), (648,166), (648,43), (648,78), (649,166), (649,43), (649,78), (650,166), (650,43), (650,78), (651,166), (651,43), (651,78), (652,166), (652,43), (652,78), (653,302), (653,224), (654,302), (654,224), (655,302), (655,224), (656,302), (656,224), (657,302), (657,224), (658,53), (658,152), (658,79), (659,53), (659,152), (659,79), (660,53), (660,152), (660,79), (661,53), (661,152), (661,79), (662,53), (662,152), (662,79), (663,140), (663,352), (663,32), (664,140), (664,352), (664,32), (665,140), (665,352), (665,32), (666,140), (666,352), (666,32), (667,140), (667,352), (667,32), (668,224), (668,53), (668,302), (669,224), (669,53), (669,302), (670,224), (670,53), (670,302), (671,224), (671,53), (671,302), (672,224), (672,53), (672,302), (673,119), (673,80), (673,312), (674,119), (674,80), (674,312), (675,119), (675,80), (675,312), (676,119), (676,80), (676,312), (677,119), (677,80), (677,312), (678,312), (678,80), (678,119), (679,312), (679,80), (679,119), (680,312), (680,80), (680,119), (681,312), (681,80), (681,119), (682,32), (682,326), (682,102), (683,32), (683,326), (683,102), (684,32), (684,326), (684,102), (685,32), (685,326), (685,102), (686,32), (686,326), (686,102), (687,102), (687,298), (687,166), (688,102), (688,298), (688,166), (689,102), (689,298), (689,166), (690,102), (690,298), (690,166), (691,352), (691,152), (691,79), (692,352), (692,152), (692,79), (693,352), (693,152), (693,79), (694,352), (694,152), (694,79), (695,352), (695,152), (695,79), (696,236), (697,236), (698,193), (699,193), (700,314), (701,314), (702,260), (703,260), (704,231), (705,231), (706,182), (707,182), (708,162), (709,162), (710,55), (711,55), (712,236), (713,236), (714,193), (715,193), (716,314), (717,314), (718,260), (719,260), (720,231), (721,231), (722,182), (723,162), (724,162), (725,55), (726,55), (727,236), (728,236), (729,193), (730,193), (731,314), (732,314), (733,260), (734,260), (735,231), (736,231), (737,182), (738,182), (739,162), (740,162), (741,55), (742,55), (743,236), (744,236), (745,193), (746,193), (747,314), (748,314), (749,260), (750,260), (751,231), (752,231), (753,182), (754,182), (755,162), (756,162), (757,55), (758,55), (759,125), (760,125), (761,344), (762,344), (763,325), (764,325), (765,125), (766,125), (767,344), (768,344), (769,325), (770,325), (771,125), (772,125), (773,344), (774,344), (775,325), (776,325), (777,300), (778,300), (779,125), (780,125), (781,344), (782,344), (783,325), (784,325), (785,300), (786,300), (787,300), (788,300), (789,300), (790,300), (791,274), (792,113), (793,292), (794,292), (795,292), (796,292), (797,12), (798,257), (799,168), (800,168), (800,12), (801,40), (802,12), (803,12), (804,168), (805,233), (806,40), (807,40), (808,40), (809,257), (810,1), (811,168), (812,292), (813,257), (814,168), (815,333), (816,242), (817,248), (818,248), (819,248), (820,248), (821,199), (822,199), (823,199), (824,199), (825,143), (826,143), (827,164), (828,181), (829,331), (830,181), (831,331), (832,321), (833,243), (834,305), (835,305), (836,321), (837,364), (838,194), (839,318), (840,243), (841,243), (842,364), (843,294), (844,66), (845,318), (846,318), (847,294), (848,364), (849,294), (850,294), (851,243), (852,315), (853,321), (854,70), (855,70), (856,294), (857,243), (858,66), (859,3), (860,3), (861,181), (862,181), (862,258), (863,181), (863,67), (864,181), (864,24), (865,181), (865,258), (866,181), (866,67), (867,181), (867,24), (868,294), (869,294), (869,355), (870,294), (870,355), (871,41), (871,124), (872,342), (873,124), (874,124), (874,105), (875,124), (876,124), (876,105), (877,342), (877,288), (878,342), (878,288), (879,33), (880,33), (881,282), (882,282), (883,164), (884,164), (884,189), (885,164), (885,265), (886,164), (886,189), (887,164), (887,265), (888,124), (889,124), (889,73), (890,124), (890,73), (891,33), (892,282), (893,282), (894,196), (895,196), (896,196), (897,196), (898,196), (899,196), (900,196), (901,196), (902,220), (902,357), (903,220), (903,357), (904,220), (904,357), (905,220), (905,357), (906,220), (906,357), (907,220), (907,360), (907,357), (908,220), (908,264), (908,357), (909,220), (909,357), (910,220), (910,357), (911,220), (911,163), (911,357), (912,205), (913,205), (913,293), (914,205), (914,293), (915,205), (915,153), (915,293), (916,170), (917,170), (918,170), (919,170), (920,170), (920,82), (921,170), (921,361), (922,170), (922,63), (923,170), (923,106), (924,170), (925,351), (926,351), (927,351), (928,351), (929,351), (929,169), (929,330), (930,351), (930,58), (930,44), (931,250), (932,250), (933,250), (933,214), (934,250), (934,206), (935,250), (935,308), (936,249), (937,249), (938,249), (939,249), (940,249), (940,176), (941,249), (942,249), (943,266), (944,266), (945,266), (945,278), (946,266), (946,4), (947,266), (947,252), (948,27), (949,27), (949,133), (950,27), (950,14), (951,11), (952,11), (953,11), (953,74), (954,11), (954,109), (955,11), (956,11), (956,228), (957,257), (958,122), (959,122), (960,285), (961,285), (962,285), (962,324), (963,285), (963,81), (964,50), (965,50), (965,202), (966,222), (967,222), (968,72), (969,11), (970,290), (971,38), (972,38), (973,299), (974,299), (975,290), (976,122), (977,122), (978,98), (979,98), (980,98), (981,250), (982,222), (983,222), (984,211), (985,211), (986,250), (987,222), (988,98), (989,299), (990,227), (991,290), (992,196), (993,351), (994,211), (995,122), (996,38), (997,122), (998,357), (999,250), (1000,222), (1001,299), (1002,220), (1003,290), (1004,197), (1005,197), (1006,349), (1007,349), (1008,323), (1009,323), (1010,323), (1011,149), (1012,149), (1013,275), (1014,365), (1015,113), (1016,113), (1017,113), (1017,210), (1018,113), (1018,210), (1019,221), (1020,254), (1021,254), (1022,328), (1023,328), (1024,36), (1025,36), (1026,366), (1027,366), (1028,366), (1029,366), (1030,366), (1031,366), (1032,366), (1033,366), (1034,366), (1035,366), (1036,366), (1037,366), (1038,99), (1039,99); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `semester_schedules` ( `ss_id` INT(11) NOT NULL AUTO_INCREMENT, `creator_id` INT(11) NOT NULL, `created_at` date NOT NULL, `name` TINYTEXT COLLATE utf8_unicode_520_ci NOT NULL, `description` mediumtext COLLATE utf8_unicode_520_ci NOT NULL, `likes` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ss_id`), FOREIGN KEY (`creator_id`) REFERENCES students(`s_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; DELIMITER $$ CREATE TRIGGER `add_current_date_for_ss` BEFORE INSERT ON `semester_schedules` FOR EACH ROW SET new.`created_at` = CURRENT_DATE$$ DELIMITER ; INSERT INTO `semester_schedules` (`creator_id`, `created_at`, `name`, `description`, `likes`) VALUES (17679, '2017-01-05', 'First Semester Introduction', 'Which courses you should take on your first year?', 25), (17679, '2017-04-14', 'Second Year CS Courses', 'Basics and Mandatories', 13), (13856, '2017-03-28', 'ECON Third Semester', 'A very fined list of courses you should take', 9), (20960, '2017-05-24', 'Freshman Second Semester', 'This will definetly help you in your first add-drop', 9); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `long_term_schedules` ( `lts_id` INT(11) NOT NULL AUTO_INCREMENT, `creator_id` INT(11) NOT NULL, `created_at` date NOT NULL, `name` TINYTEXT COLLATE utf8_unicode_520_ci NOT NULL, `description` mediumtext COLLATE utf8_unicode_520_ci NOT NULL, `likes` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`lts_id`), FOREIGN KEY (`creator_id`) REFERENCES students(`s_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; DELIMITER $$ CREATE TRIGGER `add_current_date_for_lts` BEFORE INSERT ON `long_term_schedules` FOR EACH ROW SET new.`created_at` = CURRENT_DATE$$ DELIMITER ; INSERT INTO `long_term_schedules` (`creator_id`, `created_at`,`name`, `description`, `likes`) VALUES (12385, '2017-01-12', 'schcs', 'schedule for cs students for 4 years', 11), (15381, '2017-01-22', 'schecon', 'schedule for econ students for 4 years', 22), (15896, '2017-03-16', 'schmgmt', 'schedule for management students for 7 years', 26), (17891, '2017-02-08', 'schart', 'schedule for art students for 4 years', 6), (19131, '2017-02-26', 'schpsy', 'schedule for psychology students for 4 years', 9), (1, '2017-01-01', 'Here is a schedule for your second year', 'LTS = Long Term Schedule | SS = Semester Schedule | Like it if you find it useful or share with your friends. You can also write a comment for it.', 45),(20960, '2017-05-24', 'Generic CS 2nd Year Courses', 'These are probably will be the courses you end up picking', 5); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `reviews` ( `r_id` INT NOT NULL AUTO_INCREMENT, `review_text` TEXT NOT NULL, `course_rating` INT NOT NULL, `instructor_rating` INT NOT NULL, `cdn` INT NOT NULL, `term` VARCHAR(16) NOT NULL, `creator_id` INT(11) NOT NULL, `i_id` INT NOT NULL, PRIMARY KEY (`r_id`), FOREIGN KEY (`cdn`, `term`) REFERENCES courses(`cdn`, `term`), FOREIGN KEY (`creator_id`) REFERENCES students(`s_id`), FOREIGN KEY (`i_id`) REFERENCES instructors(`i_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `lts_contains_ss` ( `lts_id` INT(11) NOT NULL, `ss_id` INT(11) NOT NULL, PRIMARY KEY (`lts_id`, `ss_id`), FOREIGN KEY (`lts_id`) REFERENCES `long_term_schedules`(`lts_id`), FOREIGN KEY (`ss_id`) REFERENCES `semester_schedules`(`ss_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; INSERT INTO `lts_contains_ss` (`lts_id`, `ss_id`) VALUES (1, 1), (1, 2), (6, 2), (7, 2), (1, 4), (6, 4); -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `s_has_lts` ( `s_id` INT(11) NOT NULL, `lts_id` INT(11) NOT NULL, PRIMARY KEY (`s_id`, `lts_id`), FOREIGN KEY (`s_id`) REFERENCES `students`(`s_id`), FOREIGN KEY (`lts_id`) REFERENCES `long_term_schedules`(`lts_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `s_has_ss` ( `s_id` INT(11) NOT NULL, `ss_id` INT(11) NOT NULL, PRIMARY KEY (`s_id`, `ss_id`), FOREIGN KEY (`s_id`) REFERENCES `semester_schedules`(`ss_id`), FOREIGN KEY (`ss_id`) REFERENCES `students`(`s_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; -- -------------------------------------------------------- CREATE TABLE IF NOT EXISTS `ss_contains_c` ( `ss_id` INT(11) NOT NULL, `cdn` INT NOT NULL, `term` VARCHAR(16) NOT NULL, PRIMARY KEY (`ss_id`, `cdn`, `term`), FOREIGN KEY (`ss_id`) REFERENCES `semester_schedules`(`ss_id`), FOREIGN KEY (`cdn`, `term`) REFERENCES `courses`(`cdn`, `term`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci; -- -- -- -- -- VIEWS -- -- -- -- -- /* This will show SSs and LTSs together chronologically */ DELIMITER // CREATE VIEW `latest_schedules` AS SELECT false AS `is_long`, ss.`ss_id` AS `id`, ss.`name`, ss.`description`, ss.`likes`, ss.`created_at`, stu.`s_id`, stu.`name` AS `s_name`, stu.`surname` AS `s_surname` FROM `semester_schedules` ss, `students` stu WHERE stu.`s_id` = ss.`creator_id` UNION SELECT true AS `is_long`, lts.`lts_id` AS `id`, lts.`name`, lts.`description`, lts.`likes`, lts.`created_at`, stu.`s_id`, stu.`name` AS `s_name`, stu.`surname` AS `s_surname` FROM `long_term_schedules` lts, `students` stu WHERE stu.`s_id` = lts.`creator_id` ORDER BY `created_at` DESC// DELIMITER ; -- PROCEDURES <file_sep>/app/Repositories/MonoScheduleRepository.php <?php namespace App\Repositories; use App\Models\MonoSchedule; class MonoScheduleRepository extends Repository { public function model() { return MonoSchedule::class; } }<file_sep>/app/Repositories/MeetingRepository.php <?php namespace App\Repositories; use App\Models\Meeting; class MeetingRepository extends Repository { public function model() { return Meeting::class; } }<file_sep>/app/Repositories/InstructorRepository.php <?php namespace App\Repositories; use App\Models\Instructor; class InstructorRepository extends Repository { public function model() { return Instructor::class; } }<file_sep>/app/Repositories/Interfaces/RepositoryInteface.php <?php namespace App\Repositories\Interfaces; use Illuminate\Database\Eloquent\Scope; interface RepositoryInterface { public function all($columns = ['*']); public function paginate($perPage = 15, $columns = ['*']); public function create(array $data); public function update(array $data, $id, $attribute = 'id'); public function delete($id); public function find($id, $columns = ['*']); // public function findBy($field, $value, $columns = ['*']); public function where($field, $value, $columns = ['*']); public function with(string ...$relations); public function scope(Scope ...$scopes); }<file_sep>/app/Models/Course.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Course extends Model { public $timestamps = null; public function requirements() { return $this->hasMany(Requirement::class, 'course_code', 'code'); } public function required_courses() { return $this->hasManyThrough(Course::class, Requirement::class, 'course_code', 'code', 'code'); // TODO: Change this to the new belongsToMany relationship coming in Laravel 5.5 // return $this->belongsToMany(Course::class, 'requirements', 'code', 'requirement'); } public function instructors() { return $this->belongsToMany(Instructor::class)->withPivot('primary'); } public function meetings() { return $this->hasMany(Meeting::class); } public function reviews() { return $this->hasMany(Review::class); } public function completed_users() { return $this->belongsToMany(User::class, 'completed_courses', 'course_id', 'user_id'); } public function in_mono_schedules() { return $this->belongsToMany(MonoSchedule::class, 'mono_has_courses', 'course_id', 'mono_schedule_id'); } } <file_sep>/app/Models/User.php <?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'given_name', 'family_name', 'email', 'avatar_url' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'remember_token', // 'google_token', ]; public function completed_courses() { return $this->belongsToMany(Course::class, 'completed_courses', 'user_id', 'course_id'); } public function reviews() { return $this->hasMany(Review::class); } public function liked_reviews() { return $this->belongsToMany(Review::class, 'review_likes', 'user_id', 'review_id'); } public function mono_schedules() { return $this->hasMany(MonoSchedule::class); } public function mono_schedules_liked() { return $this->belongsToMany(MonoSchedule::class, 'mono_schedule_likes', 'user_id', 'mono_schedule_id'); } public function mono_schedules_applied() { return $this->belongsToMany(MonoSchedule::class, 'mono_schedule_applied', 'user_id', 'mono_schedule_id')->withPivot('active'); } public function active_mono_schedule() { return $this->mono_schedules_applied()->where('active', '=', true); } public function poly_schedules() { return $this->hasMany(PolySchedule::class); } public function poly_schedules_liked() { return $this->belongsToMany(PolySchedule::class, 'poly_schedule_likes', 'user_id', 'poly_schedule_id'); } public function poly_schedules_applied() { return $this->belongsToMany(PolySchedule::class, 'poly_schedule_applied', 'user_id', 'poly_schedule_id')->withPivot('active'); } public function active_poly_schedule() { return $this->poly_schedules_applied()->where('active', '=', true); } } <file_sep>/database/migrations/2017_00_01_111518_create_requirements_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRequirementsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('requirements', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->string('course_code')->index(); $table->string('requirement')->index(); $table->primary(['course_code', 'requirement']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('requirements'); } } <file_sep>/app/Repositories/PolyScheduleRepository.php <?php namespace App\Repositories; use App\Models\PolySchedule; class PolyScheduleRepository extends Repository { public function model() { return PolySchedule::class; } }<file_sep>/app/Repositories/Repository.php <?php namespace App\Repositories; use App\Repositories\Exceptions\WrongRepositoryModelException; use App\Repositories\Interfaces\RepositoryInterface; use Illuminate\Container\Container as App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; abstract class Repository implements RepositoryInterface { private $app; protected $model; function __construct(App $app) { $this->app = $app; $this->make_model(); } /** * Specify Models class name * @return string $model_class_name */ abstract public function model (); protected function make_model () { $model = $this->app->make( $this->model() ); if( ! $model instanceof Model ) { throw new WrongRepositoryModelException( $this->model() .' is not a valid Models for '. __CLASS__ ); } $this->model = $model; } public function all($columns = ['*']) { return $this->model->get( $columns ); } public function paginate($perPage = 15, $columns = ['*']) { return $this->model->paginate( $perPage, $columns ); } public function create(array $data) { return $this->model->create( $data ); } public function update(array $data, $id, $attribute = 'id' ) { return $this->model->where( $attribute, '=', $id )->update( $data ); } public function delete($id) { return $this->model->destroy( $id ); } public function find($id, $columns = ['*']) { return $this->model->find( $id, $columns ); } public function where($field, $value, $columns = ['*']) { return $this->model->where( $field, '=', $value )->get( $columns ); } public function with(string ...$relations) { $this->model = $this->model->with( ...$relations ); return $this; } public function scope(Scope ...$scopes) { $model = $this->model; foreach ($scopes as $scope) { $model->$scope(); } $this->model = $model; return $this; } }<file_sep>/app/Http/Controllers/RequirementController.php <?php namespace App\Http\Controllers; use App\Repositories\RequirementRepository; use Illuminate\Http\Request; class RequirementController extends Controller { protected $requirement_repo; public function __construct (RequirementRepository $requirement_repository) { $this->requirement_repo = $requirement_repository; } public function show (int $course_id) { return $this->requirement_repo->show($course_id); } } <file_sep>/app/Http/Controllers/PolyScheduleController.php <?php namespace App\Http\Controllers; use App\Models\PolySchedule; use App\Repositories\PolyScheduleRepository; use Illuminate\Http\Request; class PolyScheduleController extends Controller { protected $poly_schedule_repo; function __construct (PolyScheduleRepository $poly_schedule_repository) { $this->poly_schedule_repo = $poly_schedule_repository; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response * @internal param PolySchedule $polySchedule */ public function show(int $id) { return $this->poly_schedule_repo->show($id); } /** * Show the form for editing the specified resource. * * @param \App\Models\PolySchedule $polySchedule * @return \Illuminate\Http\Response */ public function edit(PolySchedule $polySchedule) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\PolySchedule $polySchedule * @return \Illuminate\Http\Response */ public function update(Request $request, PolySchedule $polySchedule) { // } /** * Remove the specified resource from storage. * * @param \App\Models\PolySchedule $polySchedule * @return \Illuminate\Http\Response */ public function destroy(PolySchedule $polySchedule) { // } } <file_sep>/Project Plan/Features.md # Features _Will list all the features, later.._ ___ ## To Do #### Schedules + If a user applied (used) their own schedule, that schedule should have a mark for this. + `Might be a thumbs up over creator's picture` + On first login there should be a page for user to enter courses they already take. After giving their information, should be asked if they want to make a schedule out of it. + `This way user can learn how to create a schedule and in th end create thier first schedule` + `Also a description or comment on how it went should requested too` <file_sep>/app/Models/Requirement.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Requirement extends Model { protected $primaryKey = 'requirement'; public $timestamps = null; public function course() { return $this->hasOne(Course::class, 'course_code'); } }<file_sep>/database/migrations/2017_04_03_095848_create_poly_schedule_applied_pivot_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePolyScheduleAppliedPivotTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('poly_schedule_applied', function (Blueprint $table) { $table->unsignedInteger('poly_schedule_id')->index(); $table->foreign('poly_schedule_id')->references('id')->on('poly_schedules')->onDelete('cascade'); $table->unsignedInteger('user_id')->index(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->boolean('active'); $table->primary(['poly_schedule_id', 'user_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('poly_schedule_applied'); } } <file_sep>/resources/assets/js/helpers.ts function more_course( event ) : void { let more_button = event.target; let course = more_button.parentElement; more_button.classList.toggle('active'); course.classList.toggle('active'); let delay = window.getComputedStyle( course ).getPropertyValue('--transition-time'); let delay_num = Number( delay.substr(0, delay.length-1) ) * 1000 -100; window.setTimeout( () => { course.nextElementSibling.classList.toggle('active') }, delay_num); } window.onload = () => { let more_course_buttons = document.querySelectorAll('section.course_card > .more'); more_course_buttons.forEach( element => { element.addEventListener( 'click', more_course ); }); };<file_sep>/app/Repositories/CourseRepository.php <?php namespace App\Repositories; use App\Models\Course; class CourseRepository extends Repository { public function model() { return Course::class; } }<file_sep>/app/Models/Review.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Review extends Model { public function user() { return $this->belongsTo(User::class); } public function course() { return $this->belongsTo(Course::class); } public function instructor() { return $this->belongsTo(Instructor::class); } public function users_liked() { return $this->belongsToMany(User::class, 'review_likes', 'review_id', 'user_id'); } } <file_sep>/app/Repositories/ReviewRepository.php <?php /** * Created by PhpStorm. * User: Berk * Date: 31.07.2017 * Time: 18:49 */ namespace App\Repositories; use App\Models\Review; class ReviewRepository extends Repository { public function model() { return Review::class; } }<file_sep>/database/migrations/2017_04_01_131759_create_poly_schedule_course_pivot_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePolyScheduleCoursePivotTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('poly_has_mono', function (Blueprint $table) { $table->unsignedInteger('poly_schedule_id')->index(); $table->foreign('poly_schedule_id')->references('id')->on('poly_schedules')->onDelete('cascade'); $table->unsignedInteger('mono_schedule_id')->index(); $table->foreign('mono_schedule_id')->references('id')->on('mono_schedules')->onDelete('cascade'); $table->primary(['poly_schedule_id', 'mono_schedule_id']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('poly_has_mono'); } } <file_sep>/app/Models/Instructor.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Instructor extends Model { public $timestamps = null; public function courses() { return $this->belongsToMany(Course::class); } public function meetings() { return $this->belongsToMany(Meeting::class); } public function reviews() { return $this->hasMany(Review::class); } } <file_sep>/database/factories/ModelFactory.php <?php /* |-------------------------------------------------------------------------- | Models Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Models factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\Models\User::class, function (Faker\Generator $faker) { return [ 'given_name' => $faker->firstName(), 'family_name' => $faker->lastName(), 'email' => function ($self) { return $self['given_name'] . $self['family_name'] . '@sab<EMAIL>.edu'; }, 'avatar_url' => 'http://lorempixel.com/240/240/people', 'remember_token' => str_random(10), ]; }); $factory->define(App\Models\Instructor::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name(), 'email' => function ($self) { return str_replace( ' ', '.', $self['name'] ) . '@sabanciuniv.edu'; }, ]; }); $factory->define(App\Models\Requirement::class, function (Faker\Generator $faker) { static $max = 30; static $counter = 0; $counter++; return [ 'course_code' => $counter * 100, 'requirement' => $faker->numberBetween(0, $max) * 100, ]; }); $factory->define(App\Models\Course::class, function (Faker\Generator $faker) { static $counter = 0; $counter++; return [ 'cdn' => $counter, 'term' => 'Fall 2016-2017', 'code' => $counter * 100, 'title' => $faker->text(30), 'section' => $faker->randomLetter(), 'type' => 'course', 'faculty' => $faker->randomElement(['FMAN', 'FASS', 'FENS']), 'ECTS' => $faker->randomDigit(), 'su_credit' => $faker->randomDigit(), 'capacity' => $faker->numberBetween(20, 100), 'remaining' => function(array $self) { return $self['capacity']; }, 'catalog_entry_link' => null, 'detailed_information_link' => null, 'rating' => $faker->randomFloat(null, 5.0, 1.0), 'number_of_ratings' => $faker->numberBetween(5, 25), ]; }); $factory->define(App\Models\Meeting::class, function (Faker\Generator $faker) { return [ 'day' => $faker->randomElement(['M', 'T', 'W', 'R', 'F']), 'start_time' => $faker->time(), 'end_time' => $faker->time(), 'type' => 'meeting', 'start_date' => $faker->date(), 'end_date' => $faker->date(), 'schedule_type' => 'schedule_type', ]; }); $factory->define(App\Models\Review::class, function (Faker\Generator $faker) { return [ 'body' => $faker->text(), 'course_rating' => $faker->numberBetween( 1, 5 ), 'instructor_rating' => $faker->numberBetween( 1, 5 ), ]; }); $factory->define(App\Models\MonoSchedule::class, function (Faker\Generator $faker) { return [ 'name' => $faker->text(25), 'description' => $faker->text(), ]; }); $factory->define(App\Models\PolySchedule::class, function (Faker\Generator $faker) { return [ 'name' => $faker->text(25), 'description' => $faker->text(), ]; });
d09ae6b1e2ba3bba9b4854cb95b3272abfeba48b
[ "Markdown", "SQL", "TypeScript", "PHP" ]
37
PHP
bekorn/betterweb
5198d78fcbdd51166ce191cb5d4b87fa4e05e232
5e36624266cfa4f1341bb6ded039b79a3fb0f7ec
refs/heads/main
<repo_name>ArshiaSoni/Multiplayer-Game<file_sep>/Form.js class Form{ constructor(){ this.title = createElement('h1'); this.input = createInput('Name'); this.button = createButton('Play'); this.greeting = createElement('h2'); } hide(){ // hide all the elements this.title.hide(); this.input.hide(); this.button.hide(); this.greeting.hide(); } display(){ this.title.html('Car Racing Game'); this.title.position((displayWidth- 50)/2, 0); this.input.position((displayWidth- 50)/2, 150); this.button.position((displayWidth- 50)/2, 200); this.button.mousePressed(() => { this.input.hide(); this.button.hide(); // get name of the player, increase pC as it starts from 0 and update the database var name = this.input.value(); this.greeting.html('Hello ' + name); this.greeting.position((displayWidth- 50)/2, 150); player.name = name; playerCount ++; player.index = playerCount; player.updatePlayerCount(playerCount); player.updatePlayerInfo(); }) } }<file_sep>/sketch.js var database; var player, form, game; var allPlayers; var resetButton; var gameState, playerCount, carsAtEnd; var cars, car1, car2, car3, car4; var tracks, car1_img, car2_img, car3_img, car4_img; function preload(){ tracks = loadImage("track.jpg"); car1_img = loadImage("car1.png"); car2_img = loadImage("car2.png"); car3_img = loadImage("car3.png"); car4_img = loadImage("car4.png"); } function setup(){ createCanvas(displayWidth- 50, displayHeight - 100); database = firebase.database(); console.log(database); game = new Game(); game.getGameState(); game.start(); // easy reseting of values resetButton = createButton('Reset'); resetButton.position(50, 50); } function draw(){ background(146, 124, 111); imageMode (CENTER); image (tracks, (displayWidth- 50)/2, (displayHeight - 100)/2, displayWidth- 50, displayHeight*5); resetButton.mousePressed(() =>{ console.log("Reset button pressed"); game.updateGameState(0); player.updatePlayerCount(0); player.updateCarsAtEnd(0); database.ref('players').remove(); }) if(playerCount == 4){ game.updateGameState(1); } if(gameState == 1){ clear (); game.play(); } if(gameState == 2){ game.end(); // If you update gameState in database then car doesn't stop some glitch //game.updateGameState(2); } drawSprites(); }<file_sep>/Game.js class Game{ constructor(){ } getGameState(){ var gameStateRef = database.ref('gameState'); gameStateRef.on("value", (data) =>{ gameState = data.val(); console.log("GameState in dB is : " + gameState); }) } updateGameState(state){ database.ref('/').update({ gameState: state }) } start(){ // as the gameState value is not fetched var gameStateRef = database.ref('gameState'); gameStateRef.on("value", (data) =>{ gameState = data.val(); if(gameState == 0){ console.log("in start"); player = new Player(); player.getPlayerCount(); form = new Form(); form.display(); } }) car1 = createSprite(350, 600); car1.addImage(car1_img); car2 = createSprite(550, 600); car2.addImage(car2_img); car3 = createSprite(750, 600); car3.addImage(car3_img); car4 = createSprite(950, 600); car4.addImage(car4_img); cars = [car1, car2, car3, car4]; } play(){ form.hide(); background(146, 124, 111); imageMode (CENTER); image (tracks, (displayWidth- 50)/2, (displayHeight - 100)/2, displayWidth- 50, displayHeight*5); Player.getPlayerInfo(); player.getCarsAtEnd(); // for allPlayers JSON var plr; var ySpacing = 50; // for cars array var index = 0; // x is needed to capture x coordinate for drawing the circle not to display car var x = 350; // starting position of all cars var y = 600; for(plr in allPlayers){ // fill the data from database into cars array for y position for all players so that position of cars are consistent cars[index].x = x; y = 600 - allPlayers[plr].distance; cars[index].y = y; // spot the car player index has the no eg 1, 2, 3, 4 and index starts from 0 for cars array if(player.index == index + 1){ camera.position.y = cars[index].y; fill ("red"); circle(x, y, 60); } // so that only the current car text is in red else fill ("black"); // update the x position for car and index for cars array x += 200; index ++; // redundant text (allPlayers[plr].name + " : " + allPlayers[plr].distance, (displayWidth- 50)/2, ySpacing); ySpacing += 50; } // move cars up if(keyIsDown(UP_ARROW)){ player.distance += 50; player.updatePlayerInfo(); } // ranks if(player.distance >= 2000){ gameState = 2; player.rank ++; // update rank in database for each player player.updatePlayerInfo(); player.updateCarsAtEnd(player.rank); } } end(){ alert("Game Ends"); alert("Rank is: " + player.rank); } } <file_sep>/Player.js class Player{ constructor(){ this.name = null; this.distance = 0; // to see the index clearly this.index = 0; this.rank = 0; } getPlayerCount(){ var playerCountRef = database.ref('playerCount'); playerCountRef.on("value", (data) =>{ playerCount = data.val(); console.log("PlayerCount in dB is : " + playerCount); }) } updatePlayerCount(count){ database.ref('/').update({ playerCount: count }) } // we want player info at once without refering to each player in a loop so create a static function that can be called for class static getPlayerInfo(){ database.ref('players').on("value", (data) => { allPlayers = data.val(); }) } updatePlayerInfo(){ database.ref('players/player' + this.index).update({ name: this.name, distance: this.distance, rank: this.rank, index: this.index }) } getCarsAtEnd(){ var carsRef = database.ref('carsAtEnd'); carsRef.on("value", (data) => { carsAtEnd = data.val(); console.log("Cars at end in dB : " + carsAtEnd); this.rank = carsAtEnd; }) } // no need to create a static function each player will update his own rank updateCarsAtEnd(rank){ database.ref('/').update({ carsAtEnd: rank }) } }
4d5a3db2ea3d48732704b7603857526fe4761f48
[ "JavaScript" ]
4
JavaScript
ArshiaSoni/Multiplayer-Game
7ba49801e57cee360f6c222ae2c0fdc02ffbb1fa
a11bdbade88191b4b5caefbc846db7c22ab064cc
refs/heads/master
<file_sep>#!/bin/bash # Author: <NAME> # Created Date: 18/01/2017 # http://www.otaviovargas.com # Script of https://github.com/lamw/ghettoVCB ################################################################## # Definindo Parâmetros ################################################################## #Lista de Hypervisions hypervision=( "Digie o IP do Hypervision" ) #Inicializando a data no formato do Brasil data=`date +%d-%m-%Y` #Inicializando as variáveis globais #Return da funçao: escolheStorage RETURNescolheStorage="" #Pasta onde será colocado os logs pastaLog="log" ################################################################## # Funções ################################################################## #Verifica se o script já foi instalado, caso não, instala instalar(){ arq="/usr/bin/clona" if [[ ! -h "$arq" ]] then localScript=`pwd` `ln -s $localScript/clona.sh /usr/bin/clona` ssh-keygen if [[ ! -e $pastaLog ]]; then mkdir $pastaLog fi echo "Instalação Concluida!" fi } #As primeiras linhas do arquivo de log cabecarioDoLog(){ echo "###############################################################################" >> $execEm/log/log-$data.txt echo "#" echo "# Clona 6.5 $hora | $data" >> log/log-$data.txt echo "#" echo "###############################################################################" >> $execEm/log/log-$data.txt } # Atualiza os certificados dos Hypervisions para um só, para comunicar sem senha. # É necessário que já tenha criado o certificado ssl atualizarTodosCertificados() { for hyper in "${hypervision[@]}" do echo "Atualizando certificado do hypervision: $hyper" >> $execEm/log/log-$data.txt ssh $hyper "mkdir -p /etc/ssh/keys-root/" >> $execEm/log/log-$data.txt scp /root/.ssh/id_rsa* $hyper:/etc/ssh/keys-root/ >> $execEm/log/log-$data.txt ssh $hyper "cat /etc/ssh/keys-root/id_rsa.pub >> /etc/ssh/keys-root/authorized_keys" >> $execEm/log/log-$data.txt done } # Lista para o usuário os storages disponíves do hypervision escolhido anteriormente, para fazer o backup escolherStorage(){ clear j=0 opcao=0 h=$1 stg=(`ssh $h "ls -la /vmfs/volumes/" | grep "\->" | awk '{print $9}'`) echo "Escolha o Storage:" for lstg in "${stg[@]}" do echo "$j- $lstg" j=$((j+1)) done echo printf 'Opcao:' read -r opcao RETURNescolheStorage=${stg[opcao]} } # Comando que envia e executa o script gettoVCB.sh executar () { #Zerar a variável, caso nao haja máquina virtual específica execm="" # Hypervision desejado exech=$1 # Caminho do storage execs=$2 #Opcao (-a para todas as vms ou -m para uma vm específica) execm=$3 #local onde será realizado o backup echo "/vmfs/volumes/$execs/BACKUP/" > $execEm/ghettoVCB-master/destino # Acessa o Hypervision e remove a pasta antiga do script, se houver ssh $exech "rm -rf /sbin/ghettoVCB-master" # Remove possíveis resíduos de backups anteriores ssh $exech "rm -rf /tmp/ghettoVCB.work" # Copia os arquivos do servidor de backup para o Hypervision desejado scp -r $execEm/ghettoVCB-master $exech:/sbin/ # Dá permissão para que o script possa ser executado ssh $exech "chmod +x /sbin/ghettoVCB-master/ghettoVCB.sh" # Executa de fato o script, passando os parametros recebidos para o gettoVCB.sh # Lembrando que existe 1 alteração no script gettoVCB.sh para receber o caminho do storage ssh $exech "nohup /sbin/ghettoVCB-master/ghettoVCB.sh $execm" } #Menu Principal menuPrincipal() { clear echo "###############################################################################" echo "#" echo "# Clona 6.5" echo "# ESX/ESXi 3.5, 4.x+, 5.x & 6.x" echo "#" echo "# Author: <NAME>, baseado no script de <NAME>" echo "# http://www.otaviovargas.com | http://www.virtuallyghetto.com/" echo "# Documentação: Documentação.txt | http://communities.vmware.com/docs/DOC-8760" echo "# Criado: 18/01/2017" echo "#" echo "###############################################################################" echo echo "Menu:" echo " 1 Backup de apenas uma maquina virutal" echo " 2 Backup de todas as maquinas virtuais de um Hypervision" echo " 3 Sair" echo printf 'Opcao:' read -r opcao case $opcao in 1) menu1;; 2) menu2;; 3) ;; esac } # Menu 1: Para escolher a máquina virutal para fazer o backup menu1() { clear echo "Maquinas Virtuais:" i=0 opcao=-1 for hyper in "${hypervision[@]}" do echo "[$hyper]" vms=(`ssh $hyper "vim-cmd vmsvc/getallvms" | sed '1d' | awk '{print $2}'`) for vmlist in "${vms[@]}" do vmlista[i]=$vmlist h1[i]=$hyper echo "$i- $vmlist" i=$((i+1)) done echo done printf 'Opcao:' read -r opcao1 escolherStorage ${h1[$opcao1]} executar ${h1[$opcao1]} $RETURNescolheStorage "-m ${vmlista[$opcao1]}" } # Menu 2: Seleciona o hypervision para realizar o backup menu2() { count=0 echo "Hypervisions:" for hyper in "${hypervision[@]}" do echo " $count- $hyper " count=$((count+1)) done printf 'Opcao:' read -r opcao2 escolherStorage ${hypervision[opcao2]} executar ${hypervision[opcao2]} $RETURNescolheStorage "-a" } ################################################################## # Main ################################################################## instalar execEm="$(dirname "$(realpath /usr/bin/clona)")" cabecarioDoLog clear echo "Atualizando os certificado dos hypervisions..." atualizarTodosCertificados clear menuPrincipal <file_sep># Script Clona Shell Script Este Script servia para facilitar o clone de máquinas virtuais em VMware com licença free, pois os mesmos não possuíam na ferramenta o modo clona liberado, sendo possível apenas por linha de comando. Seu funcionamento baseava em listar todas as máquias virtuais de todos os Hypervisions listados no Script, criando assim um índice que facilitava a seleção de qual VM seria clonada, e para qual storage ela se destinaria.
a53a5f307416ec12f45ac6940f48e2ab5f0a6904
[ "Markdown", "Shell" ]
2
Shell
vmotavio/Script-Clona
056a67508f67e798bfe8d72314bba7315637e968
265f5a9874d256d02e158a6eb2a479a8c6f7e171
refs/heads/master
<file_sep>package jave; import java.util.Scanner; public class jave1 { public static void main(String args[]){ Scanner a=new Scanner(System.in); int x,i=1; double y,z,sum; while(i!=0){ System.out.println("나이, 체중, 신장을 빈칸으로 분리하여 순서대로 입력하세요"); x=a.nextInt(); y=a.nextDouble(); z=a.nextDouble(); sum=x+y+z; System.out.println("당신의 나이는 "+x+"살입니다."); System.out.println("당신의 체중은"+y+"kg입니다."); System.out.println("당신의 신장은"+z+"cm입니다."); System.out.println("당신의 신장은"+sum+"입니다."); System.out.println("종료하고 싶으면 0을 누르세요"); i=a.nextInt(); } } } <file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct t_rec{ int id; char name[16]; double ave; int game; struct t_rec *next; struct t_rec *front; } Student; Student *head=NULL; Student *tale=NULL; void ShowList(){ Student *p; printf("Items in the list\n"); p=head; while(p!=NULL){ printf("%4d %16s %4.3lf %4d \n",p->id, p->name, p->ave, p->game); p=p->next; } return; } void Show(){ Student *p; printf("Items in the list\n"); p=tale; while(p!=NULL){ printf("%4d %16s %4.3lf %4d \n",p->id, p->name, p->ave, p->game); p=p->front; } return; } void Append(int n, char *s, double d, int g){ Student *p; if(head==NULL){ head=(Student*) malloc(sizeof(Student)); head->id=n; head->game=g; head->ave=d; strcpy(head->name,s); head->next=NULL; head->front=NULL; } else{ p=head; while(p->next!=NULL) p=p->next; p->next=(Student*) malloc(sizeof(Student)); p->next->front=p; p=p->next; p->id=n; p->game=g; p->ave=d; strcpy(p->name,s); tale=p; p->next=NULL; } return; } void InsertAfterMax(int id, char *s, double d, int g){ double max=0.0; Student *p, *t; p=head; while(p->next!=NULL){ if(max<p->ave) max=p->ave; p=p->next; } if(head->ave==max){ t=head->next; head->next=(Student*) malloc(sizeof(Student)); head->next->id=id; head->next->game=g; head->next->ave=d; strcpy(head->next->name,s); head->next->next=t; } else{ p=head; while(p->ave==max){ t=p->next->next; p=p->next; } p=(Student*) malloc(sizeof(Student)); p->id=id; p->game=g; p->ave=d; strcpy(p->name,s); p->next=t; } return; } main(){ Student *m; Append(1, "애니프로스트", 0.96, 98); Append(4, "잭말론", 0.567, 43); Append(3, "맥테일러", 0.876, 43); Append(8, "길그리썸", 0.365, 89); Append(9, "브렌다리존스", 0.789, 43); Append(6, "칼라이트만", 0.212, 69); Append(5, "질리안포스터", 0.333, 38); Append(7, "올리비아벤슨", 0.756, 67); Append(10, "엘리엇스테이블러", 0.555, 54); ShowList(); Show(); getchar(); } <file_sep>package jave; import java.util.Scanner; public class jave2 { public static void main(String args[]){ Scanner a=new Scanner(System.in); int q,w,e,r; System.out.println("정수를 입력하세요"); q=a.nextInt(); w=q/3600; e=q%3600; r=e%60; e=e/60; System.out.println(q+"초는 "+w+"시간"+e+"분"+r+"초입니다."); } }
39c870451ce7e22577d72c880a4d521a165ba331
[ "Java", "C" ]
3
Java
benneb6787/benne
1e5a3b17c291960e342e8a6a916ec704b3d83fc2
b1ce0616b176606f6cbc618b543633b2ee667289
refs/heads/master
<file_sep>页面逻辑: * 初始界面为index.php,跳转到activityList.html,显示活动列表 * 活动列表列出网站上所有活动,每个活动可进入查看界面查看详细信息 viewActivity.php -> viewActivityInfo.html * 若用户不是此活动的参加者,可在查看界面中申请加入此活动 (申请应由活动管理员或者超级管理员审核,未实现) * 注册/登陆 register/login.php -> register/login.html,结束后跳转到活动列表 * 创建活动 addActivity.php/html,创建结束后跳转到活动列表 * 活动管理 manageActivity.php/html * 活动管理界面只显示当前登陆用户所参加的活动 * 若用户为活动的参加者,可以选择查看活动信息或者退出活动 * 若用户为活动的管理员,还可以选择删除活动 * 若当前登陆用户为超级管理员,活动管理界面右上方有一个管理员入口 manageActivityManager.php/html * 管理员界面列出网站上所有活动,每个活动有管理选项 * 点击管理选项后进入有边栏的页面,默认进入第一个,infoManager.php/html * infoManager页面对活动信息作出修改(未实现) * 可通过边栏跳转到用户管理界面 attendentManager.php/html * 用户管理界面列出所有用户和他们的基本信息,每个用户有三种状态:未参加,参加者,管理员 * 未参加者可以被添加为参加者或管理员 * 参加者可以被添加为管理员或退出活动 * 管理员可以被降为普通用户或退出活动 * 签到:当前活动开始时(begin_time)开放签到入口 * 在user_activity表中,加一列signin表示是否签到成功,初始化为0表示未签到,1表示已签到 * 在活动主页面上,首先检查该用户是否signin,如果signin在页面上(比如右上角)显示“签到成功!”,否则放一个二维码,二维码是网址 http://我们的IP/signin.php?activities_id=xxx 进行的编码。如果用户扫这个二维码,会跳转到这一个页面吧 * 在signin.php中,根据SESSION可以获得user_id,根据GET可以获得activity_id,然后调用签到函数(user_activity.php中) * 在user_activity.php中,加一个函数表示签到,参数是据user_id和activity_id,可以找到这条记录并修改该记录的signin值为1 * 最后header跳转到活动主页面,此时主页面右上角应该显示的是“签到成功!” <file_sep><?php include_once("../../../lib/common.php"); include_once("../../../lib/activity.php"); session_start(); $param = $_POST; $param['uid'] = $_SESSION['uid']; $ret = addActivities($param); if ($ret['status'] === 0) { //print("succeed"); header("Location: ../../index.php"); exit(); } else { //header("Location: ../../addActivity.php"); echo "<script>alert('已有相同的会议名称');</script>"; echo "<script>location.href='../../addActivity.php'</script>"; exit(); } ?> <file_sep><?php require_once("vendor/autoload.php"); use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $objSpreadsheet = new Spreadsheet(); $sheet = $objSpreadsheet->getActiveSheet(); $sheet->setCellValue('A1', '晨蕾'); $writer = new Xlsx($objSpreadsheet); $writer->save('export.xlsx'); ?> <file_sep><?php include_once("../lib/common.php"); $smarty3->display("./html/register.html"); ?> <file_sep><?php include_once("../../../lib/common.php"); include_once("../../../lib/activity.php"); session_start(); $activity_id = intval($_GET['activity_id']); # whether to show the "back_to_info_change" button $from_info_change = intval($_GET['from_info_change']); $activity = getActivities(array("id" => $activity_id)); $list = $activity['list']; $smarty3->assign('list', $list); $smarty3->assign('from_info_change', $from_info_change); if(!empty($_SESSION['username'])) { $smarty3->assign('login', true); //$smarty3->assign('uid', $uid); $uid = $_SESSION['uid']; $smarty3->assign('user_id', $uid); if (checkActivityAttendent($uid, $activity_id) === 1) {$smarty3->assign('attendence', true);} else{$smarty3->assign('attendence', false);} } else{$smarty3->assign('login', false);} $smarty3->display('../../html/viewActivityInfo.html'); ?> <file_sep><?php include_once("../../../lib/common.php"); include_once("../../../lib/activity.php"); session_start(); $param = $_POST; $activity_id = $param['activity_id']; $ret = changeActivityInfo($param); if ($ret['status'] === 0) { header("Location: ./viewActivity.php?activity_id=". $activity_id . "&from_info_change=1"); exit(); } else { header("Location: ../infoManager.php?activity_id=". $activity_id); exit(); } ?><file_sep><?php include_once("../../lib/common.php"); include_once("../../lib/activity.php"); $param = empty($_GET) ? $_POST : $_GET; $activityname = $param['activityname']; if (checkActivitynameUsed($activityname)) echo "已存在同名活动"; else echo ""; ?><file_sep><?php include_once(__DIR__ . "/config.php"); // smarty3 include_once(WEB_ROOT . "../third_party/smarty3/main.php"); ?> <file_sep><?php include_once("common.php"); include_once("user_activity.php"); /** * get activities which meet conditions * @param filter: array * @return array */ function getActivities($filter=array()) { $select = "select * from activities "; $where = "where true "; if (!empty($filter['id'])) { $id = $filter['id']; $where = $where . "and id = $id "; } if (!empty($filter['name'])) { $name = $filter['name']; $where = $where . "and name = '$name' "; } if (!empty($filter['abbr'])) { $abbr = $filter['abbr']; $where = $where . "and abbr = '$abbr' "; } if (!empty($filter['begin_date'])) { $beginDate = $filter['begin_date']; $where = $where . "and begin_date >= $beginDate "; } if (!empty($filter['end_date'])) { $endDate = $filter['end_date']; $where = $where . "and end_date <= $endDate "; } $order = "order by id desc"; $sql = $select . $where . $order; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); $ret = array( "num" => $result->num_rows, "list" => $result->fetch_all(MYSQLI_ASSOC) ); $conn->close(); return $ret; } /** * add a new activity * @param array consist of info * @return mixed */ function addActivities($params){ $ret = array( 'status' => 1, 'err_msg' => '' ); $name = $params['name']; $abbr = isset($params['abbr']) ? $params['abbr'] : ''; $begin_date = isset($params['begin_date']) ? $params['begin_date'] : ''; $end_date = isset($params['end_date']) ? $params['end_date'] : ''; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); $sql = $conn->prepare("insert into activities (name, abbr, begin_date, end_date) values (?, ?, ?, ?)"); if ($sql === false) { echo($conn->error); exit(); } $begin_date_pass = date('Y-m-d H:i:s',strtotime($begin_date)); $end_date_pass = date('Y-m-d H:i:s',strtotime($end_date)); $sql->bind_param("ssss", $name, $abbr, $begin_date_pass, $end_date_pass); $result = $sql->execute(); if ($result === true) { $activityId = $conn->insert_id; $userId = $params['uid']; $sql = "insert into user_activity (user_id, activity_id, role) values ($userId, $activityId, 1)"; $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } } else { $ret['err_msg'] = $conn->error; //echo($conn->error); //ret(); } $conn->close(); return $ret; } /** * delete an activity by id * @param $id * @return mixed */ function deleteActivity($id) { $ret = array( 'status' => 1, 'err_msg' => '' ); $delete_ret = deleteRecordById($id); if ($delete_ret['status'] === 1) { $ret['err_msg'] = $delete_ret['err_msg']; } else { $sql = "delete from activities where id = $id"; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } } $conn->close(); return $ret; } /** * change the activity information according to params * @param $params * @return mixed */ function changeActivityInfo($params){ $ret = array( 'status' => 1, 'err_msg' => '' ); $activity_id = $params['activity_id']; if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "update activities set"; $name = $params['name']; $abbr = $params['abbr']; $begin_date = $params['begin_date']; $end_date = $params['end_date']; $description = $params['description']; $website_address = $params['website_address']; if (!empty($name)) { $sql = $sql . " name = '$name',"; } if (!empty($abbr)) { $sql = $sql . " abbr = '$abbr',"; } if (!empty($begin_date)) { $sql = $sql . " begin_date = '$begin_date',"; } if (!empty($begin_date)) { $sql = $sql . " end_date = '$end_date',"; } if (!empty($description)) { $sql = $sql . " description = '$description',"; } if (!empty($website_address)) { $sql = $sql . " website_address = '$website_address',"; } $sql = substr($sql, 0, strlen($sql)-1); $sql = $sql . " where id = $activity_id"; #echo($sql); #exit(); $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } /** * check whether the activityname is occupied * @param activityname * @return true: occupied * @return false: not occupied */ function checkActivitynameUsed($activityname) { $ret = getActivities(array("name"=>$activityname)); if ($ret['num'] === 0) { return false; } else { return true; } } ?><file_sep><?php include_once("common.php"); /** * get user's infomation by his/her username * @param username * @return array|null */ function getUserByUsername($username) { if (!isset($username)) { return null; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); $sql = $conn->prepare("select * from users where username = ?"); $sql->bind_param("s", $username); $sql->execute(); $result = $sql->get_result(); $info = null; if ($result->num_rows > 0) { $info = $result->fetch_assoc(); } $conn->close(); return $info; } /** * check whether the username is occupied * @param username * @return true: username is occupied * false: username has not been occupied */ function checkUsernameUsed($username) { $usr = getUserByUsername($username); if (is_null($usr)) { return false; } else { return true; } } /** * check whether the user name and password consistent * @param username and password * @return status=1 if there is something wrong * status=0 name and password consistent */ function checkUser($username, $password=null) { $ret = array( 'status' => 1, 'err_msg' => '', 'uid' => -1, 'role' => 0 ); // username can not be empty if (!isset($username)) { $ret['err_msg'] = 'empty_username'; return $ret; } // username does not exist $userInfo = getUserByUsername($username); if ($userInfo === null) { $ret['err_msg'] = 'false_username'; return $ret; } // wrong password if ($password !== $userInfo['password']) { $ret['err_msg'] = 'false_password'; return $ret; } $ret['status'] = 0; $ret['uid'] = $userInfo['id']; $ret['role'] = $userInfo['role']; return $ret; } /** * register a new user * @param array consist of info * @return mixed */ function addUser($params) { $ret = array( 'status' => 1, 'err_msg' => '', 'uid' => -1 ); $username = $params['username']; $password = $params['<PASSWORD>']; $email = isset($params['email']) ? $params['email'] : ''; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); $sql = $conn->prepare("insert into users (username, password, email) values (?, ?, ?)"); $sql->bind_param("sss", $username, $password, $email); $result = $sql->execute(); if ($result === true) { $ret['status'] = 0; $ret['uid'] = $conn->insert_id; } else { $ret['err_msg'] = $conn->error; } $conn->close(); return $ret; } ?><file_sep>CREATE DATABASE IF NOT EXISTS webdb; USE webdb; CREATE TABLE IF NOT EXISTS users ( id int(10) unsigned NOT NULL AUTO_INCREMENT, username varchar(20) COLLATE utf8mb4_general_ci NOT NULL, password varchar(30) COLLATE utf8mb4_general_ci NOT NULL, email varchar(50) COLLATE utf8mb4_general_ci NOT NULL, role int(10) DEFAULT 0 NOT NULL, extra_json varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL, PRIMARY KEY (id), UNIQUE (username) ); set sql_mode='ALLOW_INVALID_DATES'; CREATE TABLE IF NOT EXISTS activities ( id int(10) unsigned NOT NULL AUTO_INCREMENT, name varchar(100) COLLATE utf8mb4_general_ci NOT NULL, abbr varchar(40) COLLATE utf8mb4_general_ci DEFAULT NULL, begin_date timestamp NOT NULL, end_date timestamp NOT NULL, description text DEFAULT NULL, website_address varchar(200) COLLATE utf8mb4_general_ci DEFAULT NULL, PRIMARY KEY (id), UNIQUE (name) ); ALTER TABLE activities ADD COLUMN add_member int(10) DEFAULT 0 NOT NULL; CREATE TABLE IF NOT EXISTS user_activity ( user_id int(10) unsigned NOT NULL, activity_id int(10) unsigned NOT NULL, PRIMARY KEY(user_id, activity_id), extra_json varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL, role int(10) DEFAULT 0 NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (activity_id) REFERENCES activities(id) ); ALTER TABLE user_activity ADD COLUMN signin int(10) DEFAULT 0 NOT NULL; commit; <file_sep><?php /** * 取消用户在活动中的管理员权限 */ include_once("../../../lib/common.php"); include_once("../../../lib/user_activity.php"); session_start(); $user_id = intval($_GET['user_id']); $activity_id = intval($_GET['activity_id']); // 检查user是否已经是activity的管理员 if (empty($user_id) || checkActivityManager($user_id, $activity_id) === 0) { header("Location: ../attendentManager.php?activity_id=". $activity_id); exit(); } $ret = cancelActivityManager($activity_id, $user_id); if ($ret['status'] === 0) { header("Location: ../attendentManager.php?activity_id=" . $activity_id); exit(); } else { echo($ret['err_msg']); exit(); } ?> <file_sep><?php /** * 为活动的参加者添加管理员权限 */ include_once("../../../lib/common.php"); include_once("../../../lib/user_activity.php"); session_start(); $user_id = intval($_GET['user_id']); $activity_id = intval($_GET['activity_id']); // 检查user是否是activity的参加者 if (empty($user_id) || checkActivityAttendent($user_id, $activity_id) === 0) { echo('user'+$user_id+' is not a participant of activity'+$activity_id); exit(); } //检测user是否已经签到过了 if (check_sign_in($activity_id, $user_id) === 1) { #$msg = 'user'+$user_id+' has already signed in activity'+$activity_id; $msg = '您已签到,请勿重复签到'; $smarty3->assign('msg', $msg); $smarty3->display("../../html/successfulSignin.html"); exit(); } //执行签到操作 $ret = add_sign_in($activity_id, $user_id); if ($ret['status'] === 0) { $msg = '您已成功签到'; $smarty3->assign('msg', $msg); $smarty3->display("../../html/successfulSignin.html"); } else { echo($ret['err_msg']); exit(); } ?> <file_sep><?php include_once("common.php"); include_once("activity.php"); /** * get activities by user_id * @param $user_id * @return array */ function getActivitiesByUserId($user_id) { $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); $sql = "select * from user_activity where user_id = $user_id order by activity_id desc"; if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); $ret = array( "num" => $result->num_rows, "list" => array() ); while ($row = $result->fetch_assoc()) { $activity_id = $row['activity_id']; $activities = getActivities(array("id" => $activity_id)); $activities['list'][0]['role'] = $row['role']; $ret['list'][] = $activities['list'][0]; } $conn->close(); return $ret; } /** * get participants by activity_id * @param $activity_id * @return array */ function getUserIdByActivities($activity_id) { $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); $sql = "select * from user_activity where activity_id = $activity_id order by role, user_id desc"; if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); $ret = array( "num" => $result->num_rows, "list" => array() ); while ($row = $result->fetch_assoc()){ $user['user_id'] = $row['user_id']; $user_id = $row['user_id']; $user['role'] = $row['role']; $user['signin'] = $row['signin']; $sql = "select * from users where id = $user_id"; $result_user = $conn->query($sql); while ($row_user = $result_user->fetch_assoc()) { $user['email'] = $row_user['email']; $user['username'] = $row_user['username']; } $ret['list'][] = $user; } $conn->close(); return $ret; } /** * get users who do not currently participate in activity_id * used to show all users in attendent managament page * @param $activity_id * @return array */ function getOtherUserIdByActivities($activity_id) { $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); $sql = "select * from user_activity where activity_id = $activity_id order by user_id desc"; if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); $sql_other = "select * from users "; $count = 0; while ($row = $result->fetch_assoc()){ if ($count == 0) $sql_other = $sql_other . "where id != " . $row['user_id']; else $sql_other = $sql_other . " and id != " . $row['user_id']; $count = $count + 1; } //echo($sql_other); //exit(); $result_other = $conn->query($sql_other); $ret = array( "num" => $result_other->num_rows, "list" => array() ); while ($row_other = $result_other->fetch_assoc()) { $user['user_id'] = $row_other['id']; $user['email'] = $row_other['email']; $user['username'] = $row_other['username']; $ret['list'][] = $user; } $conn->close(); return $ret; } /** * check whether the user is the manager of the activity * @param $user_id, $activity_id * @return 1 manager 0 attendent */ function checkActivityManager($user_id, $activity_id) { $sql = "select * from user_activity where user_id = $user_id and activity_id = $activity_id"; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); if ($result === false || $result->num_rows === 0) { //$ret = false; die("User-activity pair not found."); } $row = $result->fetch_assoc(); $conn->close(); return intval($row['role']); } /** * check whether user is the participant of the activity * @param $user_id, $activity_id * @return 1 manager or attendent 0 not */ function checkActivityAttendent($user_id, $activity_id){ $sql = "select * from user_activity where user_id = $user_id and activity_id = $activity_id"; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); if ($result === false || $result->num_rows === 0) return 0; return 1; } /** * check whether user_id has already signed in activity_id * @param $activity_id, $user_id * @return 1 already sign in 0 not */ function check_sign_in($activity_id, $user_id){ $sql = "select * from user_activity where user_id = $user_id and activity_id = $activity_id and signin = 1"; $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $result = $conn->query($sql); if ($result === false || $result->num_rows === 0) return 0; return 1; } /** * let user_id sign into activity_id * @param $activity_id, $user_id * @return array */ function add_sign_in($activity_id, $user_id){ $ret = array( 'status' => 1, 'err_msg' => '' ); if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } if (empty($user_id)) { $ret['err_msg'] = 'empty user id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "update user_activity set signin = 1 where activity_id = $activity_id and user_id = $user_id"; $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } /** * delete an item by activity_id or/and user_id * @param $activity_id, $user_id * @return array */ function deleteRecordById($activity_id, $user_id = NULL) { $ret = array( 'status' => 1, 'err_msg' => '' ); if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "delete from user_activity where activity_id = $activity_id "; if (!empty($user_id)) { $sql = $sql . "and user_id = $user_id"; } $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } /** * make user_id the manager of activity_id * @param $activity_id, $user_id * @return array */ function addActivityManager($activity_id, $user_id){ $ret = array( 'status' => 1, 'err_msg' => '' ); if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } if (empty($user_id)) { $ret['err_msg'] = 'empty user id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "update user_activity set role = 1 where activity_id = $activity_id and user_id = $user_id"; $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } /** * make user_id(not activity's participant) the manager of activity_id * @param $activity_id, $user_id * @return array */ function addActivityManagerNon($activity_id, $user_id){ $ret = array( 'status' => 1, 'err_msg' => '' ); if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } if (empty($user_id)) { $ret['err_msg'] = 'empty user id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "insert into user_activity (user_id, activity_id, role) values($user_id, $activity_id, 1);"; $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } /** * cancel the manager priority of user_id on activity_id * @param $activity_id, $user_id * @return array */ function cancelActivityManager($activity_id, $user_id){ $ret = array( 'status' => 1, 'err_msg' => '' ); if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } if (empty($user_id)) { $ret['err_msg'] = 'empty user id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "update user_activity set role = 0 where activity_id = $activity_id and user_id = $user_id"; $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } /** * make user_id user of activity_id * @param $activity_id, $user_id * @return array */ function addActivityUser($activity_id, $user_id){ $ret = array( 'status' => 1, 'err_msg' => '' ); if (empty($activity_id)) { $ret['err_msg'] = 'empty activity id'; return $ret; } if (empty($user_id)) { $ret['err_msg'] = 'empty user id'; return $ret; } $conn = new mysqli(SERVERNAME, USERNAME, PASSWORD, DBNAME); if ($conn->connect_error) { die($conn->connect_error); } $sql = "insert into user_activity (user_id, activity_id, role) values($user_id, $activity_id, 0);"; $result = $conn->query($sql); if ($result === false) { $ret['err_msg'] = $conn->error; } else { $ret['status'] = 0; } $conn->close(); return $ret; } ?><file_sep># Project on Computer Network ### Authors \- Fiona730 \- ChillySong \- Tianye ### Description ### Usage **How to run SQL script**<br> Suppose SQL script is stored in `/path/to/sql/setup.sql`<br> 1. Run mysql server 2. Enter the client, e.g. ``` mysql -u <Username> -p ``` 3. Run the SQL script ``` source /path/to/sql/setup.sql ``` <file_sep>{%extends file="./tpl/layout.html"%} {%block name="css"%} <link href="/css/login.css" rel="stylesheet" type="text/css" media="all"> <link href="/css/link.css" rel="stylesheet" type="text/css" media="all"> {%/block%} {%block name="title"%}<title>活动信息</title>{%/block%} {%block name="body"%} <body> <div class="mid-class"> <div class="art-right-w3ls"> <div id="" style="background-color:rgba(100,149,237,0.6);font-size:25px;position: absolute;color:rgba(255,255,255,1);padding:40px 50px 50px 50px;width:1000px"> <h3 style="margin:10px;">{%$msg%}</h3> <p style=" text-align:right;font-size:15px;"><a href="/manageActivity.php">返回信息管理界面</a></p> </div> </div> </div> </body> {%/block%} {%block name="javascript"%} {%/block%}<file_sep><?php include_once("../../../lib/common.php"); include_once("../../../lib/user.php"); session_start(); $param = $_POST; $ret = addUser($param); if ($ret['status'] === 0) { $_SESSION['username'] = $_POST['username']; $_SESSION['uid'] = $ret['uid']; $_SESSION['role'] = 0; header("Location: ../../index.php"); exit(); } else { header("Location: ../../register.php"); exit(); } ?> <file_sep><?php include_once("../../lib/common.php"); include_once("../../lib/user_activity.php"); session_start(); $activity_id = intval($_GET['activity_id']); $other_users = getOtherUserIdByActivities($activity_id); $other_list = $other_users['list']; $smarty3->assign('other_list', $other_list); $smarty3->assign('activity_id', $activity_id); if(!empty($_SESSION['username'])) { $smarty3->assign('login', true); $smarty3->assign('username', $_SESSION['username']); $smarty3->assign('role', $_SESSION['role']); } else{$smarty3->assign('login', false);} $smarty3->display('../html/attendentManager_others.html'); ?> <file_sep><?php include_once("../../lib/common.php"); include_once("../../lib/user.php"); $param = empty($_GET) ? $_POST : $_GET; $username = $param['username']; if (checkUsernameUsed($username)) echo "用户名已被使用"; else echo ""; ?> <file_sep><?php /** * 这个是只给管理员删除活动所用的API, 会删除activity中的表项,如果只想删除某个用户 * 参与某个活动的记录,应该调用deleteRecord.php */ include_once("../../../lib/common.php"); include_once("../../../lib/activity.php"); include_once("../../../lib/user_activity.php"); session_start(); $uid = $_SESSION['uid']; $role = intval($_SESSION['role']); $activity_id = $_GET['activity_id']; // 身份验证,只有超级管理员与该活动的管理员才能进行删除 if (!($role === 1 || checkActivityManager($uid, $activity_id) === 1)) { header("Location: manageActivity.php"); exit(); } $ret = deleteActivity($activity_id); if ($ret['status'] === 0) { if ($role === 1) header("Location: ../../index.php"); else header("Location: ../../manageActivity.php"); exit(); } else { echo($ret['err_msg']); exit(); } ?><file_sep><?php include_once("../../../lib/common.php"); include_once("../../../lib/activity.php"); include_once("../../../lib/user_activity.php"); require_once("../../../third_party/PHPSpreadSheet/vendor/autoload.php"); use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $param = $_POST; $activity_id = $param['activity_id']; $ret = getUserIdByActivities($activity_id); /* 使用 PHPSpreadSheet库创建xlsx文件 */ $objSpreadsheet = new Spreadsheet(); $objSpreadsheet->getActiveSheet() ->setCellValue('A1', '用户ID') ->setCellValue('B1', '用户名') ->setCellValue('C1', '用户身份') ->setCellValue('D1', '邮箱'); for ($i = 0; $i < $ret['num']; $i++) { $user = $ret['list'][$i]; if ($user['role'] == 0) { $user['role'] = '参加者'; } else { $user['role'] = '管理员'; } $objSpreadsheet->getActiveSheet() ->setCellValue('A' . ($i + 2), $user['user_id']) ->setCellValue('B' . ($i + 2), $user['username']) ->setCellValue('C' . ($i + 2), $user['role']) ->setCellValue('D' . ($i + 2), $user['email']); } $objSpreadsheet->getActiveSheet()->setTitle('参会者信息'); $objSpreadsheet->setActiveSheetIndex(0); $tmp = tempnam('.', 'phpxltmp'); $writer = new Xlsx($objSpreadsheet); //$writer->save('export.xlsx'); $writer->save($tmp); $fp = fopen($tmp, 'r'); $file_size = filesize($tmp); Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: " . $file_size); Header("Content-Disposition: attachment; filename=参会者信息.xlsx"); $buffer = 1024; $file_count = 0; while (!feof($fp) && $file_count < $file_size) { $file_con = fread($fp, $buffer); $file_count += $buffer; echo $file_con; } fclose($fp); unlink($tmp); ?><file_sep><?php /** * 删除某个用户参与活动的记录 */ include_once("../../../lib/common.php"); include_once("../../../lib/user_activity.php"); session_start(); $uid = intval($_SESSION['uid']); $user_id = intval($_GET['user_id']); $activity_id = intval($_GET['activity_id']); // 身份验证,get中获取的user_id应该与session中的一致 if (empty($user_id) || $uid !== $user_id) { header("Location: ../../manageActivity.php"); exit(); } $ret = deleteRecordById($activity_id, $user_id); if ($ret['status'] === 0) { header("Location: ../../manageActivity.php"); exit(); } else { echo($ret['err_msg']); exit(); } ?> <file_sep><?php include_once("../../../lib/common.php"); include_once("../../../lib/user.php"); session_start(); $username = $_POST['username']; $password = $_POST['<PASSWORD>']; $ret = checkUser($username, $password); // login success if ($ret['status'] === 0) { $_SESSION['uid'] = $ret['uid']; $_SESSION['username'] = $username; $_SESSION['role'] = intval($ret['role']); header("Location: ../../index.php"); exit(); } // login fail else { header("Location: ../../login.php"); exit(); } ?> <file_sep><?php include_once("../lib/user.php"); /* $username = $_GET[user]; $ret = checkUsernameUsed($username); if ($ret) { echo "Username " . $username . " is used"; } else { echo "Username " . $username . " is not used"; } */ echo $_GET[user]; ?> <file_sep><?php include_once("../../lib/common.php"); include_once("../../lib/user_activity.php"); session_start(); $activity_id = intval($_GET['activity_id']); #$activity_id = intval(1); $users = getUserIdByActivities($activity_id); $list = $users['list']; $smarty3->assign('list', $list); $smarty3->assign('activity_id', $activity_id); if(!empty($_SESSION['username'])) { $smarty3->assign('login', true); $smarty3->assign('username', $_SESSION['username']); $smarty3->assign('role', $_SESSION['role']); } else{$smarty3->assign('login', false);} $smarty3->display('../html/signInState.html'); ?> <file_sep>### 开机启动 + 打开php-fpm ```bash  php-fpm --fpm-config /usr/local/etc/php-fpm.conf --prefix /usr/local/var ``` + 打开nginx: ```bash nginx -c /usr/local/etc/nginx/nginx.conf nginx -s reload ``` + 打开mysql ```bash /usr/local/Cellar/mysql/8.0.15/bin/mysql.server restart ``` ### .gitignore * When you add something into a .gitignore file, try this: ``` git add [uncommitted changes you want to keep] && git commit git rm -r --cached . git add . git commit -m "fixed untracked files" ``` * If you remove something from a .gitignore file, and the above steps don't work, try this: ``` git add -f [files you want to track again] git commit -m "Refresh removing files from .gitignore file." // For example, if you want the .java type file to be tracked again, // The command should be: // git add -f *.java ``` ### activityList.html的css样式说明 `style.css`: ```css .content { float: left; padding: 1.875em; width: 100%; } /* 位于card类的外一层*/ ``` `bootstrap.min.css`: ```css .card { background-color: #fff; /* 背景颜色 */ border: 1px solid rgba(0, 0, 0, .125); /* 边框粗细、线型、颜色 */ border-radius: .25rem /* 边框四角曲率 */ } /* 衬在表格下方的区域的属性,位于content类的内一层,table类的外一层 */ .table { background-color: transparent /* 表格背景颜色 */ } /* 表格属性,位于card类的内一层 */ ``` `bootstrap.min.css`定义了几种表格类的属性,例如`table-hover`表示带有悬停效果的表格样式。只要在html的`table`标签的`class`中添加`table-hover`即可使用。一张表格可以同时属于多个类,因此这些效果可以叠加。 ### 环境配置 **For Ubuntu** 安装配置nginx+php+mysql: https://blog.51cto.com/13791715/2161170 **For mac** (1) 下载nginx,配置nginx配置文件 https://segmentfault.com/a/1190000014610688 ``` server { listen 8080; server_name localhost; #charset koi8-r; root /Users/songchenlei/Desktop/Project-on-Computer-Network/project/web; #access_log logs/host.access.log main; location / { index index.php; #autoindex on; autoindex_exact_size off; autoindex_localtime on; } location ~ \.php$ { #proxy_pass http://127.0.0.1; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } ``` (2) 安装下载php-fmp https://blog.csdn.net/ivan820819/article/details/54970330 https://lzw.me/a/mac-osx-php-fpm-nginx-mysql.html (3) 下载smarty,将lib文件夹复制到web目录下,创建tpls目录,并在该目录下创建templates、templates_c、configs、cache目录。创建一个main.php,可以看我本地的代码, smarty库已经在`project/smarty3`中,不需要重新下载,只需要修改配置文件`project/config.php` 分隔符设置的是{%和%} https://www.open-open.com/solution/view/1319016010156 (4) 安装配置MySQL 修改密码`ALTER USER 'root'@'localhost' IDENTIFIED BY 'chichichi!';` ```sql ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<PASSWORD>'; ``` **For Windows** http://www.nginx.cn/4514.html 或使用Win10内置的WSL功能,安装Ubuntu子系统,再按Linux的方法进行安装和配置 ### Mysql表说明 + users + role 1 表示管理员(需要手动在MySQL数据库内修改) 0 表示普通用户,注册时默认均为普通用户 + activities + user_activity + role 1 表示当前用户为该活动的管理员 0 表示普通与会人员 ### 一些ideas + 保持客户端登录状态 + session + 表单的一些验证,如密码、确认密码一致;密码长度;用户名… 用js + common.php 中WEB_ROOT改成自己电脑上的配置 + 防止sql注入:使用预处理语句 + Php.ini 中 magic_quotes_gpc=on, display_errors=off + 数字类型的sql字段,将str转为int + Smarty有自动cache机制,可能会导致显示的数据与后台不同步 + login里面记住密码、忘记密码 + 现阶段可以实现管理员删除activity的操作,接下去可以在删除活动时,发送消息给所有与会人员 + 超级管理员的activity页面,可以设置删除/修改等操作 + 个人profile,以及个人信息的修改 + 弹窗/确认栏的美化 + deleteRecord.php 用户删除参与会议的记录,只需要修改user_activity表 + 千万注意!!!!从MySQL中取出的值,就算是int型,在php中也是str,必须用intval()函数进行转化 + 可以设置某些用户为活动的管理人员 5/4 * 统一界面的中英文 * activities增加了description和web address两项,要在注册活动时加入这两项 * 查看活动信息界面的美化(太丑了…) * 管理员权限 * 现在只有超级管理员可以设置活动管理员,要让活动的管理员也能给自己的活动加管理员(即增加一个普通用户对自己管理的活动的管理界面) * 管理员之间(超级管理员vs活动管理员,活动创建者vs活动管理员)是否需要分优先级 * 超级管理员添加删除用户账号功能 * 导出活动参加者的数据为JSON文件 & 导入JSON文件一次性添加多个活动参加者 * 活动开始时间必须早于结束时间的约束 * 后续还可以实现活动时间的分段以及每个时间段不同安排<file_sep><?php include_once("../lib/common.php"); include_once("../lib/activity.php"); session_start(); if (!empty($_SESSION['username'])) { $smarty3->assign('login', true); $smarty3->assign('username', $_SESSION['username']); $smarty3->assign('role', $_SESSION['role']); } else { $smarty3->assign('login', false); } $activities = getActivities(); $list = $activities['list']; $smarty3->assign('list', $list); $smarty3->display('./html/activityList.html'); ?>
6321621d9fc159f20f775e01ce1392a56193547c
[ "Markdown", "SQL", "HTML", "PHP" ]
27
Markdown
songclei/Project-on-Computer-Network
9d4e39c87299f6549323a3de00ec467f770d359a
95164611f1508196afc24e3361839f97c80664a8
refs/heads/master
<repo_name>tahir565/Task-Manager-Back-end<file_sep>/models/book.js var mongoose = require('mongoose'); var Request = require('./request'); var bookSchema = new mongoose.Schema({ title: { type: String, required: true, trim: true, }, author: { type: String, trim: true }, version: { type: String, trim: true, required: true }, description: { type: String, trim: true, }, owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true } }); bookSchema.pre('remove', async function (next) { book = this; await Request.deleteMany({ $or: [{ requestedBookId: book._id }, { exchangeBookId: book._id }] }); next(); }); var Book = new mongoose.model('Book', bookSchema); module.exports = Book; <file_sep>/routers/request.js var express = require('express'); var mongoose = require('mongoose'); var Request = require('../models/request'); var Book = require('../models/book') var auth = require('../middleware/auth'); var router = new express.Router(); router.post('/requestExchange/:id', auth, async (req, res) => { bookId = req.params.id; request = new Request({ requestedBookId: bookId, userId: req.user._id }); book = await Book.findById({ _id: bookId }); if (!book || book.owner.equals(req.user._id)) { return res.status(400).send({ error: 'Book is not found!' }); } try { await request.save(); res.status(201).send(request) } catch (e) { res.status(400).send(e.message); } }); router.post('/accept/:id', auth, async (req, res) => { requestId = req.params.id; status = req.body.status; request = await Request.findById({ _id: requestId }); if (!request) { return res.status(400).send({ error: 'Request is not found!' }); } if (req.body.exchangeBookId) { book = await Book.findById({ _id: req.body.exchangeBookId }); if (!book || book.owner.equals(req.user._id)) { return res.status(400).send({ error: 'Book is not found!' }); } try { request.exchangeBookId = req.body.exchangeBookId; await request.save(); res.status(201).send(request) } catch (e) { res.status(400).send(e.message); } } else { try { request.status = status; await request.save(); res.status(201).send(request) } catch (e) { res.status(400).send(e.message); } } }); router.get('/requests', auth, async (req, res) => { my_requests = await Request.find({ userId: req.user._id }); requests = await Request.find({ userId: { $ne: req.user._id } }).populate('requestedBookId', 'owner'); requests = requests.filter(request => request.requestedBookId.owner.equals(req.user._id)); res.send({ my_requests, requests }); }); router.delete('/request/:id', auth, async (req, res) => { try { request = await Request.findByIdAndDelete({ _id: req.params.id }); res.status(200).send(request); } catch (e) { res.status(400).send(e.message); } }); module.exports = router;<file_sep>/models/request.js var mongoose = require('mongoose'); var requestsSchema = new mongoose.Schema({ requestedBookId: { type: mongoose.Schema.Types.ObjectId, ref: 'Book', required: true }, userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, exchangeBookId: { type: mongoose.Schema.Types.ObjectId, ref: 'Book', }, status: { type: String, default: 'Requested', } }); var Request = new mongoose.model('Request', requestsSchema); module.exports = Request;
b99f36db30eed6cb688497209c58e44e6d1dbdc7
[ "JavaScript" ]
3
JavaScript
tahir565/Task-Manager-Back-end
a6c8556562a7751154a0d2c232a56d4c8c6b9212
a9419b5430b8e69e6becce9a041247f15257f873
refs/heads/master
<file_sep>#include <iostream> #include <cmath> #include <fstream> using namespace std; void f(double* ys, double* y, const double eta){ ys[0] = y[1]; ys[1] = (eta-y[0]*y[0])*y[0]; } int main(){ double y[2]; double k1[2]; double k2[2]; double k3[2]; double eta = 0.5; double dx = 0.01; double temp[2]; y[0] = 0.00001; y[1] = sqrt(eta)*y[0]; int N=100/dx; ofstream out("data.txt"); for(int i=0; i<N; i++){ f(k1,y,eta); temp[0]= y[0] + dx*0.5*k1[0]; temp[1]= y[1] + dx*0.5*k1[1]; f(k2, temp, eta); temp[0]= y[0] + dx*(-k1[0]+2*k2[0]); temp[1]= y[1] + dx*(-k1[1]+2*k2[1]); f(k3, temp , eta); y[0]= y[0] + (dx/6)*(k1[0]+4*k2[0]+k3[0]); y[1]= y[1] + (dx/6)*(k1[1]+4*k2[1]+k3[1]); out << i*dx << "\t" << y[0] << "\t" << y[1] << endl; //cout << k1[0] << endl; } out.close(); return 0; }
501387248fef3bfcc986994e00d47c91179dbe61
[ "C++" ]
1
C++
klimpetrov/lab7
a12dabdc5ffaff6975850d7497484a43e3bac052
a72d623ab88dbbbceeeaecb2f27a6d516db54efd
refs/heads/master
<repo_name>kashifanawab/repoo<file_sep>/JavaIf.java class JavaIf { public static void main(String[] args) { String City= "London"; if (City == "London") { System.out.println("Best Tourist place to visit"); } } }
19700f0153f7ecbe2d572753c607410d8f1864e1
[ "Java" ]
1
Java
kashifanawab/repoo
c037762679cd5fa3cc504140a1dcacae0407c680
87838373f09fa2ab4886e70f4e7f9ad39dec0b3e
refs/heads/master
<file_sep>#%% import numpy as np import Utility as util import pandas as pd import matplotlib.pyplot as plt import os import sqlite3 as sql import ast from scipy.linalg import svd # %% data,data_movies = get_user_movie_rating() cold_users = data_movies[:1000] warm_users = data_movies[1000:] cold_users[1] R = cold_users user_ratings_mean = np.mean(R, axis = 1) R_demeaned = R - user_ratings_mean.reshape(-1, 1) from scipy.sparse.linalg import svds U,sigma,_ = svds(R_demeaned, k = 50) P = np.dot(U,np.diag(sigma)) R = warm_users user_ratings_mean = np.mean(R, axis = 1) R_demeaned = R - user_ratings_mean.reshape(-1, 1) _, _, Q = svds(R_demeaned, k = 50) Q=Q.T lam,alpha = 1,0.1 #change it please def g_elo_actual(a,b): if(a>b): return 1 if(a==b): return 0.5 else: return 0 def g_logistic(a,b): return 1/(1+np.exp(-(a-b))) def g_linear(a,b): return (a-b) def update(p,i,j,r,f): count_r = np.count_nonzero(warm_users[:][j]==r) rui = cold_users[i][j] P_ = np.reshape(P[i][:],(-1,1)).T Q_ = np.reshape(Q[:][j],(-1,1)) # print (P_.shape,Q_.shape) rcap = np.dot(P_,Q_) grad = 2 * Q[i][f] * count_r * (g_linear(rui,r) - g_linear(rcap,r)) + (2 * lam * P[i][f]) return (p - grad) def func(cold_users,P,Q,r_max = 5,k=50): for temp in range(2): for i in range(len(cold_users)): for j in range(len(cold_users[0])): if (cold_users[i][j] != 0): for r in range(r_max): for f in range(k): P[i][f] = update(P[i][f],i,j,r,f) return P P = func(cold_users,P,Q) <file_sep>#%% # Code for analysing and preprocessing of data #%% import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import sqlite3 as sql import ast from scipy.linalg import svd #%% def get_data(f_name): movies = pd.read_csv(f_name+'movies.csv') users = pd.read_csv(f_name+'users.csv') ratings = pd.read_csv(f_name+'ratings.csv') return movies,users,ratings def create_movies_table(df): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("SELECT count(*) from sqlite_master where type = 'table' and name = 'movies_data';") flag = cur.fetchall()[0][0] if flag == 0 : cur.execute("CREATE TABLE if not exists movies_data (M_id INT PRIMARY KEY, Title TEXT, Genres TEXT);") df = df[['movie_id','title','genres']] for id,rows in df.iterrows(): cur.execute("INSERT INTO movies_data(M_id, Title, Genres) values(?,?,?);",rows) db.commit() print ("movies_data table was created with entries") else : print ("movies_data table already exists") db.close() def create_users_table(df): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("SELECT count(*) from sqlite_master where type = 'table' and name = 'users_data';") flag = cur.fetchall()[0][0] if flag == 0 : cur.execute("CREATE TABLE if not exists users_data (U_id INT PRIMARY KEY, Gender TEXT, Age INT);") df = df[['user_id','gender','age']] for id,rows in df.iterrows(): cur.execute("INSERT INTO users_data(U_id, Gender, Age) values(?,?,?);",rows) db.commit() print ("users_data table was created with entries") else : print("users_data table already exists") db.close() def create_ratings_table(df): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("SELECT count(*) from sqlite_master where type = 'table' and name = 'ratings_data';") flag = cur.fetchall()[0][0] if flag == 0 : cur.execute("CREATE TABLE if not exists ratings_data (U_id INT, M_id INT, rating INT);") df = df[['user_id','movie_id','rating']] for id,rows in df.iterrows(): cur.execute("INSERT INTO ratings_data(U_id, M_id, rating) values(?,?,?);",rows) db.commit() print ("ratings_data table was created with entries") else : print ("ratings_data table already exists") db.close() def Drop_table(t_name): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("DROP TABLE if exists "+t_name +";") db.close() def analysis_user(): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("Select cnt,count(*) as num_users from (select U_id,count(*) as cnt from ratings_data group by U_id order by cnt ) group by cnt") data1 = cur.fetchall() db.close() return np.asarray(data1) def analysis_rating(): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("select rating from ratings_data") data2 = cur.fetchall() db.close() return np.asarray(data2) def get_user_movie_rating(): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("select U_id,'{'||group_concat(M_id|| ':' || rating , ',')||'}' as movie_list from ratings_data group by U_id limit 6040;") data = cur.fetchall() db.close() dict = {int(data[i][0]):ast.literal_eval(data[i][1]) for i in range (len(data))} data_movies = np.full((6041,3953),0) for keys in dict: data_movies[keys][0] = len(dict[keys]) for k in dict[keys]: data_movies[keys][k] = dict[keys][k] data_movies = sorted(data_movies, key= lambda entry : entry[0]) return dict,data_movies #%% # Drop_table('ratings_data') # Drop_table('movies_data') # Drop_table('users_data') #%% # movies,users,ratings = get_data('../Data/') #%% # print(movies.head(10)) # print(movies.shape) # print(users.head(10)) # print(users.shape) # print(ratings.head(10)) # print(ratings.shape) # #%% # create_movies_table(movies) # create_users_table(users) # create_ratings_table(ratings) #%% <file_sep>#%% # Code for analysing and preprocessing of data #%% import numpy as np import pandas as pd import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import os import sqlite3 as sql import ast from scipy.linalg import svd #%% def get_data(f_name): movies = pd.read_csv(f_name+'movies.csv') users = pd.read_csv(f_name+'users.csv') ratings = pd.read_csv(f_name+'ratings.csv') return movies,users,ratings def create_movies_table(df): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("SELECT count(*) from sqlite_master where type = 'table' and name = 'movies_data';") flag = cur.fetchall()[0][0] if flag == 0 : cur.execute("CREATE TABLE if not exists movies_data (M_id INT PRIMARY KEY, Title TEXT, Genres TEXT);") df = df[['movie_id','title','genres']] for id,rows in df.iterrows(): cur.execute("INSERT INTO movies_data(M_id, Title, Genres) values(?,?,?);",rows) db.commit() print ("movies_data table was created with entries") else : print ("movies_data table already exists") db.close() def create_users_table(df): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("SELECT count(*) from sqlite_master where type = 'table' and name = 'users_data';") flag = cur.fetchall()[0][0] if flag == 0 : cur.execute("CREATE TABLE if not exists users_data (U_id INT PRIMARY KEY, Gender TEXT, Age INT);") df = df[['user_id','gender','age']] for id,rows in df.iterrows(): cur.execute("INSERT INTO users_data(U_id, Gender, Age) values(?,?,?);",rows) db.commit() print ("users_data table was created with entries") else : print ("users_data table already exists") db.close() def create_ratings_table(df): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("SELECT count(*) from sqlite_master where type = 'table' and name = 'ratings_data';") flag = cur.fetchall()[0][0] if flag == 0 : cur.execute("CREATE TABLE if not exists ratings_data (U_id INT, M_id INT, rating INT);") df = df[['user_id','movie_id','rating']] for id,rows in df.iterrows(): cur.execute("INSERT INTO ratings_data(U_id, M_id, rating) values(?,?,?);",rows) db.commit() print ("ratings_data table was created with entries") else : print ("ratings_data table already exists") db.close() def Drop_table(t_name): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("DROP TABLE if exists "+t_name +";") db.close() #%% movies,users,ratings = get_data('../Data/') #%% print(movies.head(10)) print(movies.shape) print(users.head(10)) print(users.shape) print(ratings.head(10)) print(ratings.shape) #%% create_movies_table(movies) create_users_table(users) create_ratings_table(ratings) #%% def analysis_user(): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("Select cnt,count(*) as num_users from (select U_id,count(*) as cnt from ratings_data group by U_id order by cnt ) group by cnt") data1 = cur.fetchall() db.close() return np.asarray(data1) def analysis_rating(): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("select rating from ratings_data") data2 = cur.fetchall() db.close() return np.asarray(data2) def get_user_movie_rating(): db = sql.connect(os.path.abspath('../Data/Movie.db')) cur = db.cursor() cur.execute("select U_id,'{'||group_concat(M_id|| ':' || rating , ',')||'}' as movie_list from ratings_data group by U_id limit 6040;") data = cur.fetchall() db.close() dict = {int(data[i][0]):ast.literal_eval(data[i][1]) for i in range (len(data))} data_movies = np.full((6041,3953),0) for keys in dict: data_movies[keys][0] = len(dict[keys]) for k in dict[keys]: data_movies[keys][k] = dict[keys][k] data_movies = sorted(data_movies, key= lambda entry : entry[0]) return dict,data_movies #%% data,data_movies = get_user_movie_rating() cold_users = data_movies[:1000] warm_users = data_movies[1000:] # cold_users[1] R = np.asarray(cold_users,dtype='float64') cold_users = R[:,1:] R = R[:,1:] # user_ratings_mean = np.mean(R, axis = 1) # R_demeaned = R - user_ratings_mean.reshape(-1, 1) from scipy.sparse.linalg import svds U,sigma,_ = svds(R, k = 50) P = np.dot(U,np.diag(sigma)) R = np.asarray(warm_users,dtype='float64') warm_users = R[:,1:] R = R[:,1:] #user_ratings_mean = np.mean(R, axis = 1) #R_demeaned = R - user_ratings_mean.reshape(-1, 1) _, _, Q = svds(R, k = 50) Q=Q.T lam,alpha = 1,0.01 #change it please def g_elo_actual(a,b): if(a>b): return 1 if(a==b): return 0.5 else: return 0 def g_logistic(a,b): return 1/(1+np.exp(-(a-b))) def g_linear(a,b): return (a-b) def update(p,i,j,r,f , count_r): rui = cold_users[i][j] P_ = np.reshape(P[i][:],(-1,1)).T Q_ = np.reshape(Q[:][j],(-1,1)) # print (P_.shape,Q_.shape) rcap = np.dot(P_,Q_) grad = 2 * Q[i][f] * count_r * (g_linear(rui,r) - g_linear(rcap,r)) + (2 * lam * P[i][f]) return (p - alpha * grad) def func(cold_users,P,Q,r_max = 5,k=50): count_r = np.empty(( r_max , len(cold_users[0]))) for r in range(r_max): for j in range(len(cold_users)): count_r[r][j] = np.count_nonzero(warm_users[:][j]==r) for temp in range(2): print(temp) for i in range(len(cold_users)): for j in range(len(cold_users[0])): if (cold_users[i][j] != 0): for r in range(r_max): for f in range(k): P[i][f] = update(P[i][f],i,j,r,f , count_r[r][j]) return P def SVD(): R = np.asarray(data_movies, dtype='float64') R = R[:, 1:] user_ratings_mean = np.mean(R, axis = 1) R_demeaned = R - user_ratings_mean.reshape(-1, 1) U, sigma, Vt = svds(R_demeaned, k=50) sigma_d = np.diag(sigma) predicted = np.dot(np.dot(U, sigma_d), Vt) + user_ratings_mean.reshape(-1, 1) return predicted def MF(): R = np.asarray(data_movies, dtype='float64') R = R[:, 1:] MF_K = 10 MF_P = np.random.normal(scale=1. / MF_K, size=(np.size(R , 0), MF_K)) MF_Q = np.random.normal(scale=1. / MF_K, size=(np.size(R , 1), MF_K)) b_u = np.zeros(np.size(R , 0)) b_i = np.zeros(np.size(R , 1)) b = np.mean(R[np.where(R != 0)]) samples = [ (i, j, R[i, j]) for i in range(np.size(R , 0)) for j in range(np.size(R , 1)) if R[i, j] > 0 ] iterations = 10 for i in range(iterations): np.random.shuffle(samples) for i, j, r in samples: # Computer prediction and error prediction = b + b_u[i] + b_i[j] + MF_P[i, :].dot(MF_Q[j, :].T) e = (r - prediction) beta = 0.1 # Update biases b_u[i] += alpha * (e - beta * b_u[i]) b_i[j] += alpha * (e - beta * b_i[j]) # Update user and item latent feature matrices MF_P[i, :] += alpha * (e * MF_Q[j, :] - beta * MF_P[i, :]) MF_Q[j, :] += alpha * (e * MF_P[i, :] - beta * MF_Q[j, :]) xs, ys = R.nonzero() predicted = b + b_u[:, np.newaxis] + b_i[np.newaxis:, ] + MF_P.dot(MF_Q.T) error = 0 cnt = 0 for x, y in zip(xs, ys): cnt = cnt + 1 error += pow(R[x, y] - predicted[x, y], 2) print(np.sqrt(error / cnt)) xs, ys = R.nonzero() predicted = b + b_u[:, np.newaxis] + b_i[np.newaxis:, ] + MF_P.dot(MF_Q.T) error = 0 cnt = 0 for x, y in zip(xs, ys): cnt = cnt + 1 error += pow(R[x, y] - predicted[x, y], 2) print(np.sqrt(error / cnt)) return b + b_u[:, np.newaxis] + b_i[np.newaxis:, ] + MF_P.dot(MF_Q.T) #P = func(cold_users,P,Q) predicted= SVD() R = np.asarray(data_movies, dtype='float64') R = R[:, 1:] xs, ys = R.nonzero() error = 0 cnt = 0 for x, y in zip(xs, ys): cnt = cnt + 1 error += pow(R[x, y] - predicted[x, y], 2) print(np.sqrt(error / cnt)) #print(P.shape) print(P2.shape) print(P) #print(P2) <file_sep>#%% import numpy as np import Utility as util import pandas as pd import matplotlib.pyplot as plt import os import sqlite3 as sql import ast from scipy.linalg import svd from scipy.sparse.linalg import svds # %% Helper-Functions def g_elo_actual(a,b): if(a>b): return 1 if(a==b): return 0.5 else: return 0 def g_logistic(a,b): return 1/(1+np.exp(-(a-b))) def g_linear(a,b): return (a-b) def get_P(user_data,k): U,sigma,_ = svds(user_data, k=k) #print(sigma) P = np.dot(U,np.diag(sigma)) return np.asarray(P) def get_Q(user_data,k): _, _, Q = svds(user_data,k=k) Q=Q.T return np.asarray(Q) def update(p,Q,u,i,r,k,rw,rc,alpha,lam): omega = np.sum(rw[:,i]==r) rui = rc[u][i] P_ = np.reshape(p,(-1,1)).T Q_ = np.reshape(Q[i,:],(-1,1)) rcap = np.dot(P_,Q_) gact = g_elo_actual(rui,r) gexp = g_logistic(rcap,r) grad = omega * Q[i,:]*(gact-gexp) + lam * (P_) P_ += alpha * grad return np.reshape(P_.T,(k)) def rapare(P,Q,rc,rw,rmax,epochs,k,alpha,lam,res_mse,lam_step,lam_change,alpha_step,alpha_change): old_mse = 0 for epc in range(epochs): if(epc%lam_step==0): lam+=lam_change if(epc%alpha_step==0): alpha -= alpha_change*alpha for u in range(rc.shape[0]): for i in range(rc.shape[1]): if(rc[u][i]!= 0): for r in range (1,rmax+1): P[u] = update(P[u],Q,u,i,r,k,rw,rc,alpha,lam) r_est = np.dot(P,Q.T) r_est[r_est<=0]=0 r_est[r_est>=5]=5 r_est[rc==0]=0 mse = np.sqrt(np.sum((r_est-rc)**2)/np.sum(rc>0)) print('Epoch:',epc,' RMSE:' , mse, ' change: ', old_mse-mse) old_mse = mse res_mse.append(mse) save_plot(res_mse,'training_varAlph.png') return P,res_mse def save_plot(mse,f_name): path='./'+f_name x = np.arange(0,len(mse),1) fig = plt.figure() plt.plot(x,mse) plt.plot() fig.savefig(path,dpi=fig.dpi) #%% Hyperparams epochs = 200 lam = 0.05 lam_step = 20 lam_change = 0.001 k = 100 # number of components alpha = 0.05 alpha_step = 25 alpha_change = 0.1 rmax = 5 #%% get_data data,data_movies = util.get_user_movie_rating() r = np.asarray(data_movies,dtype=np.float32)[:,1:] rc = np.asarray(data_movies[:1000],dtype=np.float32)[:,1:] rw = np.asarray(data_movies[1000:],dtype=np.float32)[:,1:] #%% computing Latent factors # P = np.random.rand(rc.shape[0],k) #P = np.load('500epc_p.npy') P = get_P(rc,k) Q = get_Q(r,k) #%% Rmse = [] P,Rmse = rapare(P,Q,rc,rw,rmax,epochs,k,alpha,lam,Rmse,lam_step,lam_change,alpha_step,alpha_change) #np.save('try_1.38539_P.npy',P) <file_sep>#%% import numpy as np import Utility as util import pandas as pd import matplotlib.pyplot as plt import os import sqlite3 as sql import ast from scipy.linalg import svd from scipy.sparse.linalg import svds # %% Helper-Functions def g_elo_actual(a,b): if(a>b): return 1 if(a==b): return 0.5 else: return 0 def g_logistic(a,b): return 1/(1+np.exp(-(a-b))) def g_linear(a,b): return (a-b) def get_P(user_data,k): U,sigma,_ = svds(user_data, k=k) P = np.dot(U,np.diag(sigma)) return np.asarray(P) def get_Q(user_data,k): _, _, Q = svds(user_data,k=k) Q=Q.T return np.asarray(Q) def update(p,Q,u,i,r,rw,rc,alpha,lam): omega = np.sum(rw[:,i]==r) rui = rc[u][i] P_ = np.reshape(p,(-1,1)).T Q_ = np.reshape(Q[i,:],(-1,1)) rcap = np.dot(P_,Q_) gact = g_elo_actual(rui,r) gexp = g_logistic(rcap,r) grad = omega*Q[i,:]*(gact-gexp) + lam*(P_) P_ -= alpha*grad return np.reshape(P_.T,(50)) def rapare(P,Q,rc,rw,rmax,epochs,k,alpha,lam): res_mse = [] for epc in range(epochs): for u in range(rc.shape[0]): for i in range(rc.shape[1]): if(rc[u][i]!= 0): for r in range (1,rmax+1): P[u] = update(P[u],Q,u,i,r,rw,rc,alpha,lam) print(epc) r_est = np.dot(P,Q.T) r_est[r_est<=0]=0 r_est[r_est>=5]=5 r_est[rc==0]=0 # r_est = np.round(r_est) mse = np.sqrt(np.sum((r_est-rc)**2)/np.sum(rc>0)) print('RMSE:' , mse ) res_mse.append(mse) save_plot(res_mse,epochs,'training.png') return P,res_mse def save_plot(mse,epochs,f_name): path='./'+f_name x = np.arange(0,epochs,1) fig = plt.figure() plt.plot(x,mse) plt.xlabel('Iteration') plt.ylabel('RMSE') plt.title('Cold Start User scenario on MovieLens') plt.plot() fig.savefig(path,dpi=fig.dpi) #%% Hyperparams epochs = 10 lam = 1 k = 50 # number of components alpha = 0.1 rmax = 5 #%% get_data data,data_movies = util.get_user_movie_rating() r = np.asarray(data_movies,dtype=np.float32)[:,1:] rc = np.asarray(data_movies[:1000],dtype=np.float32)[:,1:] rw = np.asarray(data_movies[1000:],dtype=np.float32)[:,1:] #%% computing Latent factors # P = np.random.rand(rc.shape[0],k) P = np.load('500epc_p.npy') # P = get_P(rc,k) Q = get_Q(r,k) #%% # P,Rmse = rapare(P,Q,rc,rw,rmax,epochs,k,alpha,lam) # np.save('500epc_p.npy',P) r_est = np.dot(P,Q.T) r_est[r_est<=0]=0 r_est[r_est>=5]=5 r_est = np.round(r_est) r_est[rc==0]=-1 np.sum(r_est==rc) # np.sum(rc>-1) mse = np.sqrt(np.sum((r_est-rc)**2)/np.sum(rc>0)) print('RMSE:' , mse ) # REVIEW: epoch = 500 var = 1800 r_est[rc==0]=-1 x,y = np.asarray(np.where(rc==r_est)) inx = np.random.permutation(len(x)) x = x[inx] y = y[inx] mse=[] for epc in range(epoch): x1,y1 = np.asarray(np.where(rc>0)) inx1 = np.random.permutation(len(x1)) x1 = x1[inx1[:var-epc*2]] y1 = y1[inx1[:var-epc*2]] rc_tst = [] rc_est_tst = [] x_t = np.concatenate((x,x1),axis = -1) y_t = np.concatenate((y,y1),axis = -1) for i in range(len(x_t)): rc_tst.append(rc[x_t[i]][y_t[i]]) rc_est_tst.append(r_est[x_t[i]][y_t[i]]) rc_tst = np.array(rc_tst) rc_est_tst = np.array(rc_est_tst) print(len(x_t)) mse_tst = np.sqrt(np.sum((rc_est_tst-rc_tst)**2)/len(x)) mse.append(mse_tst) print('RMSE:' , mse_tst ) save_plot(mse,epoch,'result.png') <file_sep>import math import numpy as np import pandas as pd import matplotlib.pyplot as plt # Reading ratings file ratings = pd.read_csv('ratings.csv', sep='\t', encoding='latin-1', usecols=['user_id', 'movie_id', 'user_emb_id', 'movie_emb_id', 'rating']) max_userid = ratings['user_id'].drop_duplicates().max() max_movieid = ratings['movie_id'].drop_duplicates().max() # Reading ratings file users = pd.read_csv('users.csv', sep='\t', encoding='latin-1',usecols=['user_id', 'gender', 'zipcode', 'age_desc', 'occ_desc']) # Reading ratings file movies = pd.read_csv('movies.csv', sep='\t', encoding='latin-1', usecols=['movie_id', 'title', 'genres']) print max_movieid print max_userid shuffled_ratings = ratings.sample(frac=1., random_state=0) # Shuffling users Users = shuffled_ratings['user_emb_id'].values print 'Users:', Users, ', shape =', Users.shape # Shuffling movies Movies = shuffled_ratings['movie_emb_id'].values print 'Movies:', Movies, ', shape =', Movies.shape # Shuffling ratings Ratings = shuffled_ratings['rating'].values print 'Ratings:', Ratings, ', shape =', Ratings.shape K_FACTORS = 100 # The number of dimensional embeddings for movies and users TEST_USER = 2000 # A random test user (user_id = 2000) from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint from keras.models import Model inp1 = Input((1,)) x1 = Embedding(6040,100,input_length=1)(inp1) x1 = Reshape((100,))(x1) x1 = Reshape((100,))(x1) inp2 = Input((1,)) x2 = Embedding(3952,100,input_length=1)(inp2) x2 = Reshape((100,))(x2) x3 = dot([x1,x2],axes=1) model = Model([inp1,inp2],x3) model.compile(loss='mse',optimizer='adamax') callbacks = [EarlyStopping('val_loss', patience=2), ModelCheckpoint('weights.h5', save_best_only=True)] # Use 30 epochs, 90% training data, 10% validation data history = model.fit([Users, Movies], Ratings, nb_epoch=30, validation_split=.1, verbose=1, callbacks=callbacks)<file_sep>#%% import numpy as np import Utility as util import pandas as pd import matplotlib.pyplot as plt import os import sqlite3 as sql import ast from scipy.linalg import svd from scipy.sparse.linalg import svds from MF import ProductRecommender # %% Helper-Functions def save_plot(mse,epochs,f_name): path='./'+f_name x = np.arange(0,epochs,1) fig = plt.figure() plt.plot(x,mse) plt.plot() fig.savefig(path,dpi=fig.dpi) #%% Hyperparams epochs = 100 lam = 0 k = 20 # number of components alpha = 0.1 rmax = 5 #%% get_data data,data_movies = util.get_user_movie_rating() r = np.asarray(data_movies,dtype=np.float32)[:,1:] rc_train = np.asarray(data_movies[:900],dtype=np.float32)[:,1:] rc_test = np.asarray(data_movies[900:1000],dtype=np.float32)[:,1:] rw = np.asarray(data_movies[1000:],dtype=np.float32)[:,1:] #%% model = ProductRecommender() model.fit(rc_train) #%% computing Latent factors #%% P,Rmse = rapare(P,Q,rc,rw,rmax,epochs,k,alpha,lam) # np.save('600epc_p.npy',P) # r_est = np.dot(P,Q.T) # r_est[r_est<=0]=0 # r_est[r_est>=5]=5 # r_est = np.round(r_est) # r_est[rc==0]=0 # np.sum(r_est==rc) # np.sum(rc>-1) # mse = np.sqrt(np.sum((r_est-rc)**2)/np.sum(rc>0)) # print('RMSE:' , mse ) # REVIEW: # x,y = np.asarray(np.where(rc>0)) # x.shape # y.shape
d0bec8bef83351988a4f3c6514231b20dedddda0
[ "Python" ]
7
Python
YashP16/Mitigating_coldStart_users
b5654d5f6b5338fb6b6d1490cbc96afb332bbbf8
d1fb5f56f919ab981a3c3af6686a65276db8aa93
refs/heads/master
<repo_name>gohovd/base-exp<file_sep>/js.js // Collect HTML Element let tbox = document.getElementById("testbox"); // BUTTON let baseIn = document.getElementById("base"); // INPUT, BASE let exponentIn = document.getElementById("exponent"); // INPUT, EXPONENT let output = document.getElementById("output"); // OUTPUT RESULTS (STRINGS) HERE // Define function const makeNoise = function() { console.log("Pling bb!"); } let result = 1; const power = function(base, exponent) { if(base > 0 && exponent > 0) { result = 1; for (let count = 0; count < exponent; count++) { result *= base; } output.innerHTML = base + "*" + exponent + " = " + result; } else { result = "Please pass legal args."; output.innerHTML = result; } output.classList.add("outputTxt"); return result; } // Attach the function a response to click event on the html element tbox.addEventListener("click", function() { power(baseIn.value, exponentIn.value); }, false); function multiplier(factor) { return number => number * factor; } let twice = multiplier(2); console.log(twice);
371a6cf52f7d5f3303056982db2f60db273a2aa2
[ "JavaScript" ]
1
JavaScript
gohovd/base-exp
ca74fbfd1a41809e568c66c05e4a542cc3056a2e
01f07b21234d513fac9729de0156531331a68f5f
refs/heads/master
<repo_name>uschor/training_kraken_hebrew_print<file_sep>/src/train_kraken_print.py #!/usr/bin/python # coding= utf-8 import json import codecs import os import errno from bs4 import BeautifulSoup def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def fill_ketos(ketos_file_name, text_file_name, output_file_name): ketos_doc = codecs.open(ketos_file_name, 'r', 'utf-8').read() soup = BeautifulSoup(ketos_doc, 'html.parser') text_file = codecs.open(text_file_name, 'r', 'utf-8') line_num = 0 while True: line_text = text_file.readline() line_text = line_text.rstrip() if not line_text: break line_num += 1 line = soup.find(id="line_" + `line_num`) if line: line.append(line_text) output = codecs.open(output_file_name, 'w', 'utf-8') output.write(unicode(soup)) output.close() text_file.close() def generate_images(bible_book_file, work_dir): mkdir_p(work_dir) json_string = codecs.open(bible_book_file, 'r', 'utf-8').read() parsed_json = json.loads(json_string) chapters = parsed_json['text'] for i in range(len(chapters)): print('Working on chapter ' + `i`) image_text_file_name = work_dir + '/image_' + `i` + '.txt' image_file_name = work_dir + '/image' + `i` + '.png' text_file_name = work_dir + '/text_' + `i` + '.txt' ketos_file_name = work_dir + '/ketos_' + `i` + '.html' ketos_filled_file_name = work_dir + '/ketos_filled_' + `i` + '.html' image_text_file = codecs.open(image_text_file_name , 'w', 'utf-8') text_file = codecs.open(text_file_name , 'w', 'utf-8') # Prepare a file per chapter, according to this answer https://unix.stackexchange.com/a/138809 image_text_file.write('text 30,150 "') chapter = chapters[i] for line in chapter: line = line.replace(u'\u05be', ' ') text_file.write(line) text_file.write('\n') words = line.split() for n in range(len(words) - 1, -1, -1): image_text_file.write(words[n][::-1]) image_text_file.write(' ') image_text_file.write('\n') image_text_file.write('"') image_text_file.close() text_file.close() print("\tGenerating image") os.system('convert -size 4000x5000 xc:white -font "Arial" -pointsize 64 -fill black -draw @' + image_text_file_name + ' ' + image_file_name) print("\tRunning Ketos") os.system('ketos transcribe -o ' + ketos_file_name + ' ' + image_file_name) fill_ketos(ketos_file_name, text_file_name, ketos_filled_file_name) generate_images('Genesis - he - Tanach with Text Only.json', 'work') #generate_images('3_chapters.json', 'work') <file_sep>/README.md Train a printed-Hebrew Kraken model, according to the [instructions here](http://kraken.re/training.html). The goal is to quickly test Kraken on Hebrew (i.e. not HTR of a manuscript). Since Kraken requires at least 800 lines transcribed text, and the process provided by Kraken is manual, an automation script was developed, to run all the preparations of the lines image-text pairs. After the training set is ready, the Kraken model training can be run. # Source text The training text used is Genesis book, taken from [Sefaria](https://www.sefaria.org.il/Genesis?lang=he). The text is in Creative Commons license, taken from (http://www.tanach.us/Tanach.xml) # Requirements On a Debian Linux (Ubuntu 16.04 works well), install Kraken along with the Python installation and Vagrant image required for the training. [Instruction here](http://kraken.re/). The script requires: ## Beautiful Soup 4 Python module: `pip install beautifulsoup4` ## ImageMagic to convert text into images: `sudo apt-get install imagemagick` # Training set preparation Run the script `src/train_kraken_print.py` The script does the following: * Breaks the Genesis JSON file into chapters, and for each chapter: * Extracts the verses into text file, verse per line. * Generates an image, big enough for Kraken - 5000x8000px, using ImageMagic. Since ImageMagic doesn't seem to support LTR, the Hebrew words are reversed. It's simplistic, but works for pure-Hebrew text. For mixed text, bidirectional support is required. * Runs the Kraken *ketos* utility, to generate the HTML file, intended for manual transcription * Fills the HTML transcription file automatically, with the text from the matching text file. Running the script generates HTML files of the transcribed images to *./work/ketos_filled_\*.html*, along with byproducts. ## Extract lines image-text pairs Now that the transcription file are ready, run the Kraken command: `ketos extract --reorder --output training --normalization NFD work/ketos_filled_*` The files will be generated into *training/* directory. # Kraken training Get and run the Kraken Vagrant virtual machine. Make sure to run Vagrant in the same directory in which the *train_kraken_script.py* script was run: `vagrant init openphilology/kraken` `vagrant up` `vagrant ssh` In the Kraken VM, run the training command: `./train.sh /vagrant/training heb_print` It will take the training set, and train a model called *heb_print*.
49703a77d30d90a91daf0d174e934c9acc8b17ee
[ "Markdown", "Python" ]
2
Python
uschor/training_kraken_hebrew_print
cad64b81b32abef6687654bbb58db8d938d42218
556d147864588ed88b668acc3bc05bf130998744
refs/heads/develop
<repo_name>bigbrain25/wearemasters<file_sep>/src/pages/Collectible.js import React from "react"; import { Link } from "react-router-dom"; import Footer from "../components/Footer"; import Carousel from "react-multi-carousel"; import newImg from "../assets/img/new.jpg"; import MusicCard from "../components/cards/Music"; import artis from "../assets/img/artis.gif"; import NavigateBeforeIcon from "@material-ui/icons/NavigateBefore"; const Collectible = () => { const trackList = [ { id: 1, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", link: "#", }, { id: 2, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", link: "#", }, { id: 3, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/KBPFHbreehLr7iQYTAeAmAoQqM4GwlRJk9O9x9bLpBy1uVqtJEZTTEXkJ2-0bClw1zvFAmEDhXHctKAdW8tp2LwpMSMSROsUlyjS1A=s0", link: "#", }, { id: 4, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", link: "#", }, { id: 5, title: "Blue Woman Series", artist: "Ayoola -2ETH/$3000", thumbnail: newImg, link: "#", }, { id: 6, title: "Blue Woman Series", artist: "Ayoola -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/SYy6eHKIOJF3y_-0dmyuRxwBAuKV4lt9dg_W2_QlqvGG4bDb67WVszlSY2Znhe7XlbwZg7d7OQ2EP1cqEFBWEXLn85AtRmi7HxzNuA=s0", link: "#", }, { id: 7, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/PA-k72Ijyr6EVhOcT1XMSKfR3fLd24JaAQvXG8pTKzVsVBW2iFPv7TMg-6ZaRFZKbFsqgRfyTou44qAE-8J83fN3v8netgtb00bB=s0", link: "#", }, { id: 1, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", link: "#", }, { id: 2, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", link: "#", }, { id: 3, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/KBPFHbreehLr7iQYTAeAmAoQqM4GwlRJk9O9x9bLpBy1uVqtJEZTTEXkJ2-0bClw1zvFAmEDhXHctKAdW8tp2LwpMSMSROsUlyjS1A=s0", link: "#", }, { id: 4, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", link: "#", }, { id: 5, title: "Blue Woman Series", artist: "Ayoola -2ETH/$3000", thumbnail: newImg, link: "#", }, { id: 6, title: "Blue Woman Series", artist: "Ayoola -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/SYy6eHKIOJF3y_-0dmyuRxwBAuKV4lt9dg_W2_QlqvGG4bDb67WVszlSY2Znhe7XlbwZg7d7OQ2EP1cqEFBWEXLn85AtRmi7HxzNuA=s0", link: "#", }, { id: 7, title: "Kissed by the sun", artist: "Dorgu -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/PA-k72Ijyr6EVhOcT1XMSKfR3fLd24JaAQvXG8pTKzVsVBW2iFPv7TMg-6ZaRFZKbFsqgRfyTou44qAE-8J83fN3v8netgtb00bB=s0", link: "#", }, { id: 1, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", link: "#", }, { id: 2, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", link: "#", }, { id: 3, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/KBPFHbreehLr7iQYTAeAmAoQqM4GwlRJk9O9x9bLpBy1uVqtJEZTTEXkJ2-0bClw1zvFAmEDhXHctKAdW8tp2LwpMSMSROsUlyjS1A=s0", link: "#", }, { id: 4, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", link: "#", }, { id: 5, title: "Kaleidoscope Woman", artist: "IPneuma -2ETH/$3000", thumbnail: newImg, link: "#", }, { id: 6, title: "Blue Woman Series", artist: "Ayoola -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/SYy6eHKIOJF3y_-0dmyuRxwBAuKV4lt9dg_W2_QlqvGG4bDb67WVszlSY2Znhe7XlbwZg7d7OQ2EP1cqEFBWEXLn85AtRmi7HxzNuA=s0", link: "#", }, { id: 7, title: "Kissed by the sun", artist: "Dorgu -2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/PA-k72Ijyr6EVhOcT1XMSKfR3fLd24JaAQvXG8pTKzVsVBW2iFPv7TMg-6ZaRFZKbFsqgRfyTou44qAE-8J83fN3v8netgtb00bB=s0", link: "#", }, ]; const responsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: { max: 4000, min: 3000 }, items: 3, partialVisibilityGutter: 0, }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 5, partialVisibilityGutter: 0, }, tablet: { breakpoint: { max: 1024, min: 650 }, items: 2, partialVisibilityGutter: 0, }, mobile: { breakpoint: { max: 650, min: 0 }, items: 1, partialVisibilityGutter: 0, }, }; const tracks = trackList.map((card) => { return <MusicCard key={card.id} card={card} />; }); return ( <div> <Link to="/"> <a className="py-2 bg-gray-700 w-full h-10 fixed z-50 bg-opacity-90" alt="#" href="#" > <div className="bg-gray-400 ml-3 bg-gray-600 w-6 h-6 rounded"> <NavigateBeforeIcon style={{ color: "#fff" }} /> </div> </a> </Link> <div className="px-10"> <h1 className="text-white font-black pt-20">Collectibles/ Meetbits</h1> <div className="flex pt-48 pb-12"> <div className="w-full"> <img src={artis} className="w-3/4 h-96 rounded" alt="img" /> </div> <div className="w-full text-white mt-16"> <p> - has been televised since Nigeria won it’s independence from the British in 1960. Our living rooms or parlors have become the arena citizens of our nascent nation have sat to watch the deconstruction of the dream our founding fathers had. We’ve seen civil war, coup’s , skirmishes and the dominance of our military. The deconstruction of a nation is mixed media reminding us how far we’ve come as a people. </p> <div className="flex"> <button className="py-2 px-10 font-black uppercase rounded bg-appRed text-white mt-8"> Bid now </button> <p className="mt-8 ml-8 py-2">- 2ETH/$3000</p> </div> </div> </div> <hr className="border border-gray-200 opacity-60 dark:border-sideBar" /> <div> <div className="flex justify-between items-center mt-16"> <h2 className="text-xl capitalize font-black text-bordyColor dark:text-gray-100"> new week, new goals </h2> </div> <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel> <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel> <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel>{" "} <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel>{" "} <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel>{" "} <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel>{" "} <Carousel arrows={false} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel> </div> </div> <div className="box fixed bottom-0 left-0 w-full z-50"> <div className="items-center h-16 bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 ... py-4 px-4 sm:flex space-y-4 sm:space-y-0 text-gray-100"> <button className="mb-8">x</button> <div className="space-y-1 ml-6"> <h2 className="text-base sm:text-xl font-semibold"> We are building a community of 1000+ Digital Artists </h2> </div> <div className="ml-auto"> <Link to="/sign-up" className="bg-gray-100 font-medium px-12 capitalize py-2 text-gray-600 flex focus:outline-none rounded" > Join Now </Link> </div> </div> </div> <Footer /> </div> ); }; export default Collectible; <file_sep>/src/components/NewUpdateProfileModal.js // import React, { useState } from "react"; // import NewUpdateProfile from "../pages/NewUpdateProfile"; // import Popup from "./Modal"; // const NewUpdateProfileModal = () => { // const [isToggled, setIsToggled] = useState(true); // const toggleModal = () => setIsToggled(!isToggled); // return ( // <div> // {isToggled && ( // <Popup isOpen={isToggled} nClose={toggleModal}> // <NewUpdateProfile /> // </Popup> // )} // </div> // ); // }; // export default NewUpdateProfileModal; <file_sep>/src/actions/assetActions.js import axios from "axios"; import { spinnerService } from "@chevtek/react-spinners"; import { CLEAR_ERRORS, GET_ETH_RATE, ETH_RATE_LOADING, GET_ASSETS, GET_ASSET, GET_ALL_ASSETS, ASSET_LOADING, GET_ERRORS, } from "./types"; import swal from "@sweetalert/with-react"; // Get Assets export const getAssets = () => (dispatch) => { dispatch(setAssetLoading()); axios .get("/api/assets") .then((res) => dispatch({ type: GET_ASSETS, payload: res.data, }) ) .catch((err) => dispatch({ type: GET_ASSETS, payload: null, }) ); }; // Get Assets export const getAllAssets = () => (dispatch) => { dispatch(setAssetLoading()); axios .get("/api/assets/all") .then((res) => dispatch({ type: GET_ALL_ASSETS, payload: res.data, }) ) .catch((err) => dispatch({ type: GET_ALL_ASSETS, payload: null, }) ); }; // Get Assets By Username export const getAssetsByUsername = () => (dispatch) => { dispatch(setAssetLoading()); axios .get("/api/assets") .then((res) => dispatch({ type: GET_ASSETS, payload: res.data, }) ) .catch((err) => dispatch({ type: GET_ASSETS, payload: null, }) ); }; // Get Assets By ID export const getAssetByID = (id) => (dispatch) => { dispatch(setAssetLoading()); axios .get(`/api/assets/${id}`) .then((res) => dispatch({ type: GET_ASSET, payload: res.data, }) ) .catch((err) => dispatch({ type: GET_ASSET, payload: null, }) ); }; // GET ETH RATE export const getETHRate = () => (dispatch) => { dispatch(setETHRateLoading()); axios .get("/api/assets/rate/get-eth-rate/") .then((res) => { console.log(res); dispatch({ type: GET_ETH_RATE, payload: res.data, }); }) .catch((err) => { dispatch({ type: GET_ETH_RATE, payload: {}, }); }); }; // Upload Art export const uploadArt = (uploadData, history) => (dispatch) => { spinnerService.hide("uploadNotLoading"); spinnerService.show("uploadLoading"); dispatch(clearErrors()); axios .post("/api/assets/upload-digital-art", uploadData) .then((res) => { spinnerService.hide("uploadLoading"); spinnerService.show("uploadNotLoading"); swal( "Upload Successful!", "Your upload was successful, you will get a notification when your submission is approved.", "success" ).then(() => { history.push("/account"); }); }) .catch((err) => { spinnerService.show("uploadNotLoading"); spinnerService.hide("uploadLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Update Asset export const updateAsset = (assetData, history) => (dispatch) => { spinnerService.hide("updateAssetNotLoading"); spinnerService.show("updateAssetLoading"); dispatch(clearErrors()); axios .post("/api/assets/update-asset", assetData) .then((res) => { spinnerService.hide("updateAssetLoading"); spinnerService.show("updateAssetNotLoading"); swal( "Update Successful!", "Asset update was successful!", "success" ).then(() => { history.push("/assets"); }); }) .catch((err) => { spinnerService.show("updateAssetNotLoading"); spinnerService.hide("updateAssetLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); window.scrollTo(0, 1); }); }; // Set Asset Loading State export const setAssetLoading = () => { return { type: ASSET_LOADING, }; }; // ETH Rate Loading export const setETHRateLoading = () => { return { type: ETH_RATE_LOADING, }; }; // Clear errors export const clearErrors = () => { return { type: CLEAR_ERRORS, }; }; <file_sep>/src/actions/authActions.js import axios from "axios"; import setAuthToken from "../utils/setAuthToken"; import jwt_decode from "jwt-decode"; import { spinnerService } from "@chevtek/react-spinners"; import swal from "@sweetalert/with-react"; // import Noty from "noty"; // import "noty/lib/noty.css"; // import "noty/lib/themes/mint.css"; import { GET_ERRORS, GET_MESSAGES, SET_CURRENT_USER, CLEAR_ERRORS, } from "./types"; // Register User export const registerUser = (userData) => (dispatch) => { dispatch(clearErrors()); spinnerService.hide("registerNotLoading"); spinnerService.show("registerLoading"); axios .post("/api/users/register", userData) .then((res) => { spinnerService.hide("registerLoading"); swal( "Account Created Successfully!", "Your account have been created sucessfully!", "success" ); // Save to localStorage const { token } = res.data; // Set token to ls localStorage.setItem("jwtToken", token); // Set token to Auth header setAuthToken(token); // Decode token to get user data const decoded = jwt_decode(token); // Set current user dispatch(setCurrentUser(decoded)); }) .catch((err) => { spinnerService.hide("registerLoading"); spinnerService.show("registerNotLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Login - User Login export const loginUser = (userData, history) => (dispatch) => { dispatch(clearErrors()); spinnerService.hide("loginNotLoading"); spinnerService.show("loginLoading"); axios .post("/api/users/login", userData) .then((res) => { spinnerService.hide("loginLoading"); spinnerService.show("loginNotLoading"); // Save to LocalStorage const { token } = res.data; // Set token to Local Storage localStorage.setItem("jwtToken", token); // Set token to Auth Header setAuthToken(token); // Decode token to get user data const decoded = jwt_decode(token); // Set Current User dispatch(setCurrentUser(decoded)); }) .catch((err) => { console.log(err); spinnerService.hide("loginLoading"); spinnerService.show("loginNotLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Register Shipper export const registerAsset = (assetData, history) => (dispatch) => { dispatch(clearErrors()); spinnerService.hide("assetRegistrationNotLoading"); spinnerService.show("assetRegistrationLoading"); axios .post("/api/users/register-asset", assetData) .then((res) => { spinnerService.hide("assetRegistrationLoading"); swal( "Success!", "New asset registration was successful!", "success" ).then(() => { history.push("/account"); }); }) .catch((err) => { spinnerService.hide("assetRegistrationLoading"); spinnerService.show("assetRegistrationNotLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Account Activation export const activateAccount = (codeData, history) => (dispatch) => { spinnerService.hide("activationNotLoading"); spinnerService.show("activationLoading"); axios .post(`/api/users/activate-account`, codeData) .then((res) => { spinnerService.show("activationNotLoading"); spinnerService.hide("activationLoading"); dispatch(logoutUser()); swal( "Activation Successful!", "Your account activation was successful, kindly proceed to Login.", "success" ); // new Noty({ // type: "success", // text: "Activation successful, Please Login.", // timeout: 7500, // progressBar: true, // }).show(); dispatch({ type: GET_MESSAGES, payload: res.data, }); history.push("/account"); }) .catch((err) => { spinnerService.show("activationNotLoading"); spinnerService.hide("activationLoading"); swal("Error!", "Account activation unsuccessful", "error"); // new Noty({ // type: "error", // text: "Account activation unsuccessful!", // timeout: 5000, // progressBar: true, // }).show(); dispatch({ type: GET_ERRORS, payload: err.response.data, }); history.push("/account"); }); }; // Resend Activation Token export const resendActivationToken = (history) => (dispatch) => { spinnerService.hide("resendActivationNotLoading"); spinnerService.show("resendActivationLoading"); axios .post("/api/users/resend-activation-token") .then((res) => { spinnerService.show("resendActivationNotLoading"); spinnerService.hide("resendActivationLoading"); swal( "Success!", "We sent a new verification code to your email address. Kindly proceed to activate your account.", "success" ).then(() => { history.push("/account"); }); }) .catch((err) => { spinnerService.show("resendActivationNotLoading"); spinnerService.hide("resendActivationLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Update Personal Information export const updatePersonalInfo = (personalInfo, history) => (dispatch) => { spinnerService.hide("updatePersonalInfoNotLoading"); spinnerService.show("updatePersonalInfoLoading"); axios .post("/api/users/update-personal-information", personalInfo) .then((res) => { // Save to LocalStorage const { token } = res.data; // Set token to Local Storage localStorage.setItem("jwtToken", token); // Set token to Auth Header setAuthToken(token); // Decode token to get user data const decoded = jwt_decode(token); // Set Current User dispatch(setCurrentUser(decoded)); spinnerService.hide("updatePersonalInfoLoading"); spinnerService.show("updatePersonalInfoNotLoading"); swal("Success!", "Personal information updated successfully!", "success"); // .then(() => { // logoutUser(); // history.push("/login"); // }); }) .catch((err) => { spinnerService.hide("updatePersonalInfoLoading"); spinnerService.show("updatePersonalInfoNotLoading"); // new Noty({ // type: "error", // text: "Error updating Personal Info", // timeout: 5000, // progressBar: true, // }).show(); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Change Password export const updatePassword = (passwordData, history) => (dispatch) => { spinnerService.hide("updatePasswordNotLoading"); spinnerService.show("updatePasswordLoading"); axios .post("/api/users/change-password", passwordData) .then((res) => { spinnerService.hide("updatePasswordLoading"); spinnerService.show("updatePasswordNotLoading"); swal( "Success!", "You have successfully changed your password", "success" ).then(() => { dispatch(logoutUser()); history.push("/login"); }); }) .catch((err) => { spinnerService.hide("updatePasswordLoading"); spinnerService.show("updatePasswordNotLoading"); swal("Error!", err.response.data.error, "error"); // new Noty({ // type: "error", // text: err.response.data.error, // timeout: 5000, // progressBar: true, // }).show(); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Forget Password export const forgotPassword = (emailData, history) => (dispatch) => { spinnerService.hide("forgotPasswordNotLoading"); spinnerService.show("forgotPasswordLoading"); axios .post("/api/users/forgot-password", emailData) .then((res) => { spinnerService.hide("forgotPasswordLoading"); spinnerService.show("forgotPasswordNotLoading"); swal("Success!", res.data.msg, "success").then(() => { history.push("/login"); }); }) .catch((err) => { spinnerService.hide("forgotPasswordLoading"); spinnerService.show("forgotPasswordNotLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Reset Password export const resetPassword = (passwordData, history) => (dispatch) => { spinnerService.hide("resetPasswordNotLoading"); spinnerService.show("resetPasswordLoading"); axios .post("/api/users/reset-password", passwordData) .then((res) => { spinnerService.hide("resetPasswordLoading"); spinnerService.show("resetPasswordNotLoading"); swal("Success!", res.data.msg, "success").then(() => { history.push("/login"); }); }) .catch((err) => { spinnerService.hide("resetPasswordLoading"); spinnerService.show("resetPasswordNotLoading"); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Set Logged in User export const setCurrentUser = (decoded) => { return { type: SET_CURRENT_USER, payload: decoded, }; }; export const clearErrorMessages = () => (dispatch) => { dispatch(clearErrors()); }; // Clear Errors export const clearErrors = () => { return { type: CLEAR_ERRORS, }; }; // Log User Out export const logoutUser = () => (dispatch) => { // Remove token from localStorage localStorage.removeItem("jwtToken"); // Remove auth header for future requests setAuthToken(false); // Set current user to {} which will set isAuthenticated to false dispatch(setCurrentUser({})); }; <file_sep>/src/pages/Account.js /* eslint-disable */ import React, { Component } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import Avatar from "react-avatar"; import { logoutUser, activateAccount, resendActivationToken, } from "../actions/authActions"; import { CountdownCircleTimer } from "react-countdown-circle-timer"; import NavigateBeforeIcon from "@material-ui/icons/NavigateBefore"; import { getCurrentProfile } from "../actions/profileActions"; import { getAssets, getETHRate } from "../actions/assetActions"; import { compose } from "redux"; import { withStyles } from "@material-ui/core"; import Carousel from "react-multi-carousel"; import Masonry, { ResponsiveMasonry } from "react-responsive-masonry"; import Footer from "../components/Footer"; import swal from "@sweetalert/with-react"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, table: { minWidth: 650, }, }); const minuteSeconds = 60; const hourSeconds = 3600; const daySeconds = 86400; const timerProps = { isPlaying: true, size: 120, strokeWidth: 6, }; const renderTime = (dimension, time) => { return ( <div className="time-wrapper"> <div className="time">{time}</div> <div>{dimension}</div> </div> ); }; const stratTime = Date.now() / 1000; // use UNIX timestamp in seconds const endTime = stratTime + 1043248; // use UNIX timestamp in seconds const remainingTime = endTime - stratTime; const days = Math.ceil(remainingTime / daySeconds); const daysDuration = days * daySeconds; const getTimeSeconds = (time) => (minuteSeconds - time) | 0; const getTimeMinutes = (time) => ((time % hourSeconds) / minuteSeconds) | 0; const getTimeHours = (time) => ((time % daySeconds) / hourSeconds) | 0; const getTimeDays = (time) => (time / daySeconds) | 0; const UrgeWithPleasureComponent = () => ( <CountdownCircleTimer isPlaying duration={10} colors={[ ["#004777", 0.33], ["#F7B801", 0.33], ["#A30000", 0.33], ]} > {({ remainingTime }) => remainingTime} </CountdownCircleTimer> ); class Account extends Component { constructor() { super(); this.state = { code: "", errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { window.scrollTo(0, 1); this.props.getAssets(); this.props.getCurrentProfile(); } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } resendCode(e) { e.preventDefault(); this.props.resendActivationToken(this.props.history); } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } onSubmit(e) { e.preventDefault(); if (this.state.code.length !== 6) { swal("Error!", "Authorization code provided must be 6 digits.", "error"); return; } const codeData = { code: this.state.code, }; this.props.activateAccount(codeData, this.props.history); } render() { const { errors } = this.state; const { classes } = this.props; const { user } = this.props.auth; const { profile, profileLoading } = this.props.profile; const { assets, assetLoading } = this.props.asset; const collection = [ { img: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", }, { img: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", }, { img: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", }, { img: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", }, { img: "https://lh3.googleusercontent.com/KBPFHbreehLr7iQYTAeAmAoQqM4GwlRJk9O9x9bLpBy1uVqtJEZTTEXkJ2-0bClw1zvFAmEDhXHctKAdW8tp2LwpMSMSROsUlyjS1A=s0", }, { img: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", }, ]; const creation = [ { img: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", }, { img: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", }, ]; const responsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: { max: 4000, min: 3000 }, items: 1, partialVisibilityGutter: 0, }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 1, partialVisibilityGutter: 0, }, tablet: { breakpoint: { max: 1024, min: 650 }, items: 1, partialVisibilityGutter: 0, }, mobile: { breakpoint: { max: 650, min: 0 }, items: 1, partialVisibilityGutter: 0, }, }; const getCollections = collection.map((img) => { return ( <div className="w-full px-2 py-2"> <img src={img.img} className="object-cover w-full"></img> </div> ); }); const getCreations = creation.map((img) => { return ( <div className="w-full h-track"> <img src={img.img} className="object-cover w-full h-full"></img> </div> ); }); const Navigation = ({ goToSlide, ...rest }) => { const { carouselState: { currentSlide }, } = rest; return ( <div className="carousel-button-group absolute top-0 right-0 left-0 text-center"> {" "} <button onClick={() => goToSlide(0)} className={ currentSlide === 0 ? "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none border-b border-gray-400" : "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none" } > {" "} creations{" "} </button> <button onClick={() => goToSlide(1)} className={ currentSlide === 1 ? "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none border-b border-gray-400" : "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none" } > series </button> </div> ); }; return ( //<div> // {user.isVerified === true ? ( <div> <Link to="/"> <a className="py-2 bg-gray-700 w-full h-10 fixed z-50 bg-opacity-90" alt="#" href="#" > <div className="bg-gray-400 ml-3 bg-gray-600 w-6 h-6 rounded"> <NavigateBeforeIcon style={{ color: "#fff" }} /> </div> <div className="flex justify-end pr-4 relative -top-6"> <Link to="/login" onClick={this.onLogoutClick.bind(this)} className="uppercase py-1 px-4 text-xs font-medium rounded text-white bg-appRed" > log out </Link> </div> </a> </Link> <div className="relative"> <div className="max-w-7xl mx-auto text-bordyColor dark:text-gray-100 py-16 relative lg:px-8 px-10"> <div className="grid grid-cols-12 gap-4 ml-20"> <div className="col-span-12 sm:col-span-8 lg:col-span-5"> <div className="w-24 h-24"> <Avatar name={`${user.firstName} ${user.lastName}`} size="100" round="100%" className="mx-auto" /> </div> <h4 className="mt-4" style={{ fontWeight: "700", fontSize: "25px" }} > {user.firstName + " " + user.lastName}{" "} </h4> <div className="flex space-x-6"> <p>Followers: 0</p> <p className="">Following: 0</p> <p className="">Creations: 0</p> </div> <div className="my-3"> <button className="text-appRed focus:outline-none" style={{ fontWeight: "600", fontSize: "20px" }} > @{user.username} </button> <div className="flex mt-4"> <p className="text-xl font-black">ETH Address :</p> <p className="ml-2 text-xs mt-1 pt-1">3khbfjvnjnkcjk........</p> </div> <p className="mt-2"> British in 1960. Our living rooms or parlors have become the arena citizens of our nascent nation have sat to watch the deconstruction of the dream our founding fathers had. We’ve seen </p> </div> <div className="mt-8 mb-6"> <Link to="/update-profile" className="bg-gray-100 rounded-sm py-2 px-4 text-sm font-medium text-gray-600 mr-2" > Edit Profile </Link> <Link to="/upload-art" className="bg-gray-100 rounded-sm py-2 px-4 text-sm font-medium text-gray-600 mr-2" > Upload Art </Link> <div className="mt-6"> <Link to="/next" className="bg-gray-100 w-full rounded-sm py-2 ml-1 px-12 text-sm font-medium text-gray-600" > Next Drop Timer </Link> </div> </div> </div> <div className="border bg-gray-400 h-full w-96 font-black text-7xl pt-10 text-center ml-36"> When Is Your Next Drop? <div className="relative top-28 flex w-full"> <CountdownCircleTimer {...timerProps} colors={[["#f8f8ff"]]} duration={daysDuration} initialRemainingTime={remainingTime} > {({ elapsedTime }) => renderTime( "days", getTimeDays(daysDuration - elapsedTime) ) } </CountdownCircleTimer> <CountdownCircleTimer {...timerProps} colors={[["#f8f8ff"]]} duration={daySeconds} initialRemainingTime={remainingTime % daySeconds} onComplete={(totalElapsedTime) => [ remainingTime - totalElapsedTime > hourSeconds, ]} > {({ elapsedTime }) => renderTime( "hours", getTimeHours(daySeconds - elapsedTime) ) } </CountdownCircleTimer> <CountdownCircleTimer {...timerProps} colors={[["#f8f8ff"]]} duration={hourSeconds} initialRemainingTime={remainingTime % hourSeconds} onComplete={(totalElapsedTime) => [ remainingTime - totalElapsedTime > minuteSeconds, ]} > {({ elapsedTime }) => renderTime( "minutes", getTimeMinutes(hourSeconds - elapsedTime) ) } </CountdownCircleTimer> <CountdownCircleTimer {...timerProps} colors={[["#f8f8ff"]]} duration={minuteSeconds} initialRemainingTime={remainingTime % minuteSeconds} onComplete={(totalElapsedTime) => [ remainingTime - totalElapsedTime > 0, ]} > {({ elapsedTime }) => renderTime("seconds", getTimeSeconds(elapsedTime)) } </CountdownCircleTimer> </div> </div> </div> <div className="grid grid-cols-12 mt-12"> <div className="col-span-12 relative"> <Carousel renderButtonGroupOutside={true} arrows={false} customButtonGroup={<Navigation />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-16" > <div className="mt-8"> <ResponsiveMasonry columnsCountBreakPoints={{ 350: 1, 750: 2, 900: 3 }} > <Masonry gutter="20">{getCollections}</Masonry> </ResponsiveMasonry> {/* <div className="grid grid-cols-4 gap-4">{getCollections}</div> */} </div> <div className="mt-8"> <div className="grid grid-cols-4 gap-4">{getCreations}</div> </div> </Carousel> </div> </div> </div> <Footer /> </div> </div> // ) : ( // <div> // <Helmet> // <meta charSet="utf-8" /> // <title>WeAreMasters - Upload Digital Art</title> // <link // href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" // rel="stylesheet" // integrity="<KEY>" // crossorigin="anonymous" // /> // </Helmet> // <div className="container" style={{ height: "100vh" }}> // <div className="row no-gutter"> // <div className="col-md-12 mt-4"> // <Link to="/account"> // <img // width="100" // src={logo} // alt="WeAreMasters Logo" // className="center-image mt-2 mb-4" // /> // </Link> // </div> // <div className="col-md-5 m-auto"> // <h2 className="text-center mb-4"> // <strong> // Welcome, {user.firstName}! <br /> // </strong> // </h2> // <form // className="need-validation" // onSubmit={this.onSubmit} // noValidate // > // <div className="mb-4 text-center"> // {errors.verification && ( // <div class="alert alert-danger" role="alert"> // {errors.verification} // </div> // )} // <label for="code" className="form-label"> // <strong style={{ fontSize: "20px" }}> // Enter 6 digit verification code sent to your email // </strong> // </label> // <input // type="number" // id="code" // name="code" // value={this.state.code} // onChange={this.onChange} // className={classnames( // "form-control form-control-lg text-center mt-2", // { // "is-invalid": errors.verification, // } // )} // placeholder="Enter 6 digit verification code" // autofocus // required // /> // </div> // <div className="d-grid gap-2"> // <button // className="btn btn-lg btn-primary mb-3" // type="submit" // > // <Spinner name="activationLoading"> // <Backdrop className={classes.backdrop} open={true}> // <CircularProgress color="inherit" /> // </Backdrop> // Processing... // </Spinner> // <Spinner name="activationNotLoading" show={true}> // Proceed to Verify Account // </Spinner> // </button> // </div> // </form> // <hr /> // <div className="row"> // <div className="col-md-6"> // <div className="d-grid gap-2"> // <button // className="btn btn-dark my-2" // onClick={this.resendCode.bind(this)} // > // <Spinner name="resendActivationLoading"> // <Backdrop className={classes.backdrop} open={true}> // <CircularProgress color="inherit" /> // </Backdrop> // Processing... // </Spinner> // <Spinner // name="resendActivationNotLoading" // show={true} // > // Resend Code // </Spinner> // </button> // </div> // </div> // <div className="col-md-6"> // <div className="d-grid gap-2"> // <button // className="btn btn-dark my-2" // onClick={this.onLogoutClick.bind(this)} // > // Log out // </button> // </div> // </div> // </div> // <hr className="mb-5" /> // </div> // </div> // </div> // </div> // )} //</div> ); } } Account.propTypes = { getCurrentProfile: PropTypes.func.isRequired, getAssets: PropTypes.func.isRequired, getETHRate: PropTypes.func.isRequired, activateAccount: PropTypes.func.isRequired, resendActivationToken: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, errors: state.errors, profile: state.profile, asset: state.asset, ethRate: state.ethRate, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getCurrentProfile, activateAccount, resendActivationToken, getAssets, logoutUser, getETHRate, }) )(Account); <file_sep>/src/pages/UploadArt.js /* eslint-disable */ import React, { Component } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { logoutUser } from "../actions/authActions"; import { getCurrentProfile } from "../actions/profileActions"; import classnames from "classnames"; import { compose } from "redux"; import { withStyles } from "@material-ui/core"; import CurrencyFormat from "react-currency-format"; import { client } from "filestack-react"; import { Spinner } from "@chevtek/react-spinners"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import { uploadArt } from "../actions/assetActions"; import { Helmet } from "react-helmet"; import { getETHRate } from "../actions/assetActions"; import exactMath from "exact-math"; import logo from "../assets/img/favicon.png"; const Validator = require("validator"); const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class UploadArt extends Component { constructor(props) { super(props); this.state = { title: "", price: "", image_url: "", animation_url: "", youtube_url: "", facebook_url: "", twitter_url: "", instagram_url: "", description: "", errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { window.scrollTo(0, 1); this.props.getCurrentProfile(); this.props.getETHRate(); } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } uploadImage(e) { e.preventDefault(); const apikey = "<KEY>"; const options = { accept: "image/*", maxFiles: 1, transformations: { crop: true, }, onFileUploadFinished: (res) => { this.setState({ image_url: res.url, }); }, }; const filestack = client.init(apikey, options); const picker = filestack.picker(options); picker.open(); } onSubmit(e) { e.preventDefault(); const uploadData = { title: this.state.title, price: this.state.price, image_url: this.state.image_url, animation_url: this.state.animation_url, youtube_url: this.state.youtube_url, facebook_url: this.state.facebook_url, twitter_url: this.state.twitter_url, instagram_url: this.state.instagram_url, description: this.state.description, }; this.props.uploadArt(uploadData, this.props.history); } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } render() { const { errors } = this.state; const { classes } = this.props; const { ethPrice, ethPriceLoading } = this.props.ethRate; const disableMathError = { invalidError: false }; let imageBox; if (!Validator.isEmpty(this.state.image_url)) { imageBox = ( <div className="col-md-6 m-auto"> <img src={this.state.image_url} alt="Digital Art Preview" className="image-preview" /> </div> ); } return ( <div> <Helmet> <meta charSet="utf-8" /> <title>WeAreMasters - Upload Digital Art</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous" /> </Helmet> <div className="container mt-20 mb-100"> <div className="row no-gutter"> <div className="col-md-12 mt-4"> <Link to="/account"> <img width="100" src={logo} alt="WeAreMasters Logo" className="center-image mt-2" /> </Link> </div> <div className="col-md-6 m-auto"> <hr /> <h2 className="text-center mb-4"> <strong>UPLOAD DIGITAL ART</strong> </h2> <form className="need-validation" onSubmit={this.onSubmit} noValidate > <div className="mb-4"> <label for="title" className="form-label"> <strong> Title of Digital Art (e.g Kaleidoscope Woman) </strong> </label> <input type="text" id="title" name="title" value={this.state.title} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.title, })} placeholder="e.g Kaleidoscope Woman by IPneuma" autofocus required /> {errors.title && ( <div className="invalid-feedback">{errors.title}</div> )} </div> <div className="mb-4"> <label for="price" className="form-label"> <strong> Price of Digital Art{" "} {ethPrice === null || ethPriceLoading ? null : ( <CurrencyFormat value={exactMath.mul( 1, ethPrice.amount, disableMathError )} displayType={"text"} thousandSeparator={true} decimalSeperator="." decimalScale={2} fixedDecimalScale={true} renderText={(value) => ( <span>(1 ETH = &#36;{value})</span> )} /> )} </strong> </label> <div className="input-group mb-4"> <span className="input-group-text"> <strong>ETH</strong> </span> <CurrencyFormat name="price" id="price" thousandSeparator={true} decimalSeperator="." decimalScale={2} fixedDecimalScale={true} value={this.state.price} className={classnames("form-control form-control-lg", { "is-invalid": errors.price, })} onValueChange={(values) => { const { value } = values; this.setState({ price: value, }); }} placeholder="e.g 2.75" required /> </div> {errors.price && ( <div style={{ color: "#dc3545", fontSize: "12px", marginTop: "-15px", fontWeight: "400", }} > {errors.price} </div> )} </div> <div className="mb-4"> {!Validator.isEmpty(this.state.image_url) ? ( imageBox ) : ( <div className="upload-image" onClick={this.uploadImage.bind(this)} > Click this area to Select Image for Digital Art </div> )} {errors.image_url && ( <div style={{ color: "#dc3545", fontSize: "12px", marginTop: "5px", fontWeight: "400", }} > {errors.image_url} </div> )} </div> <div className="mb-4"> <label for="name" className="form-label"> <strong>Animation URL for Digital Art</strong> </label> <input type="text" id="animation_url" name="animation_url" value={this.state.animation_url} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.animation_url, })} placeholder="e.g https://youtu.be/WEA9EB7Q5RY (optional)" required /> {errors.animation_url && ( <div className="invalid-feedback"> {errors.animation_url} </div> )} </div> <div className="mb-4"> <label for="youtube_url" className="form-label"> <strong>YouTube URL for Digital Art</strong> </label> <input type="text" id="youtube_url" name="youtube_url" value={this.state.youtube_url} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.youtube_url, })} placeholder="e.g https://youtu.be/WEA9EB7Q5RY (optional)" autofocus required /> {errors.youtube_url && ( <div className="invalid-feedback">{errors.youtube_url}</div> )} </div> <div className="mb-4"> <label for="facebook_url" className="form-label"> <strong>FaceBook URL for Digital Art</strong> </label> <input type="text" id="facebook_url" name="facebook_url" value={this.state.facebook_url} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.facebook_url, })} placeholder="e.g https://facebook.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.facebook_url && ( <div className="invalid-feedback"> {errors.facebook_url} </div> )} </div> <div className="mb-4"> <label for="twitter_url" className="form-label"> <strong>Twitter URL for Digital Art</strong> </label> <input type="text" id="twitter_url" name="twitter_url" value={this.state.twitter_url} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.twitter_url, })} placeholder="e.g https://twitter.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.twitter_url && ( <div className="invalid-feedback">{errors.twitter_url}</div> )} </div> <div className="mb-4"> <label for="instagram_url" className="form-label"> <strong>Instagram URL for Digital Art</strong> </label> <input type="text" id="instagram_url" name="instagram_url" value={this.state.instagram_url} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.instagram_url, })} placeholder="e.g https://instagram.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.instagram_url && ( <div className="invalid-feedback"> {errors.instagram_url} </div> )} </div> <div className="mb-4"> <label for="name" className="form-label"> <strong>Description of Digital Art</strong> </label> <textarea rows="5" id="description" name="description" value={this.state.description} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.description, })} placeholder="Enter full description for Digital Art" required ></textarea> {errors.description && ( <div className="invalid-feedback">{errors.description}</div> )} </div> <div className="d-grid gap-2"> <button className="btn btn-lg btn-primary" type="submit"> <Spinner name="uploadLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Processing... </Spinner> <Spinner name="uploadNotLoading" show={true}> Proceed to Submit Digital Art </Spinner> </button> </div> </form> <hr /> <div className="row"> <div className="col-md-6"> <div className="d-grid gap-2"> <Link to="/account" className="btn btn-dark my-2"> Back Home </Link> </div> </div> <div className="col-md-6"> <div className="d-grid gap-2"> <Link to="/market" className="btn btn-dark my-2"> Market Place </Link> </div> </div> </div> <hr className="mb-5" /> </div> </div> </div> </div> ); } } UploadArt.propTypes = { getCurrentProfile: PropTypes.func.isRequired, uploadArt: PropTypes.func.isRequired, getETHRate: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, profile: state.profile, ethRate: state.ethRate, errors: state.errors, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getCurrentProfile, uploadArt, logoutUser, getETHRate, }) )(UploadArt); <file_sep>/src/pages/Login.js /* eslint-disable */ import React, { Component } from "react"; import ModalVideo from "react-modal-video"; import { Link, withRouter } from "react-router-dom"; import login from "../assets/img/signup.jpg"; import logo from "../assets/img/logo-white.svg"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { loginUser } from "../actions/authActions"; import { Spinner } from "@chevtek/react-spinners"; import compose from "recompose/compose"; import { withStyles } from "@material-ui/core/styles"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import classnames from "classnames"; import "../assets/video.min.css"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class Login extends Component { constructor() { super(); this.state = { email: "", password: "", isOpen: false, errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { if (this.props.auth.isAuthenticated) { this.props.history.push("/account"); } } componentWillReceiveProps(nextProps) { if (nextProps.auth.isAuthenticated) { this.props.history.push("/account"); } if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } } onBlur = (field) => (e) => { e.preventDefault(); this.setState({ touched: { ...this.state.touched, [field]: true }, }); }; onChange(e) { this.setState({ [e.target.name]: e.target.value }); } onSubmit(e) { e.preventDefault(); const userData = { email: this.state.email, password: <PASSWORD>, }; this.props.loginUser(userData, this.props.history); } render() { const { errors } = this.state; const { classes } = this.props; return ( <div className="relative h-full flex items-center justify-center"> <div className="max-w-7xl mx-auto py-16 lg:px-8 px-4"> <div className="grid lg:grid-cols-12 gap-8 text-bordyColor dark:text-gray-200 items-center"> <div className="lg:col-span-4 lg:order-first order-last"> <div> <Link to="/"> <img src={logo} width="225px" className="mb-10" /> </Link> <h2 className="text-3xl sm:text-5xl sm:leading-extraLoose font-bold capitalize"> welcome Back! </h2> </div> <form className="mt-12 space-y-4" onSubmit={this.onSubmit} novalidate="novalidate" > <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400"> <label className="capitalize font-medium"> email address </label> <input type="email" id="email" name="email" placeholder="Enter your email address" value={this.state.email} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.email, } )} required /> {errors.email && ( <div className="form-error">{errors.email}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400"> <label className="capitalize font-medium">password</label> <input type="<PASSWORD>" id="password" name="<PASSWORD>" placeholder="Enter your password" value={this.state.password} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.password, } )} required /> {errors.password && ( <div className="form-error">{errors.password}</div> )} </div> <div className="flex justify-end text-xs space-y-2 text-bordyColor dark:text-gray-400"> <button className="font-medium underline"> Forgot your password? </button> </div> <div className="flex flex-col justify-center items-center space-y-4"> <button className="px-4 py-3 bg-appRed text-sm text-gray-100 font-semibold rounded-sm w-full"> <Spinner name="loginLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Signing in... </Spinner> <Spinner name="loginNotLoading" show={true}> Sign in </Spinner> </button> {/* <p className="text-sm">or</p> <div className="flex space-x-4 w-full"> <button className="flex items-center justify-center px-8 py-3 bg-gray-100 capitalize text-sm text-gray-600 font-semibold rounded-sm w-full"> <img src={fb} className="w-5 h-5 mr-4" alt="facebook" /> facebook </button> <button className="flex items-center justify-center px-8 py-3 bg-gray-100 capitalize text-sm text-gray-600 font-semibold rounded-sm w-full"> <img src={google} className="w-5 h-5 mr-4" alt="google" /> google </button> </div> */} <div className="pt-8 text-sm text-center w-full space-y-4"> <p>Don't have account?</p> <Link to="/sign-up" className="flex items-center justify-center px-8 py-3 bg-gray-100 text-sm text-gray-600 font-semibold rounded-sm w-full" > Create an Acccount </Link> </div> </div> </form> </div> <div className="lg:col-span-8"> <div className="relative w-full text-gray-100"> <img src={login} className="" alt="login" /> <div className="absolute w-full h-full bg-gradient-to-t from-black top-0 left-0 bg-opacity-60 flex px-8 pb-8 items-end justify-start"> <div className="max-w-sm"> <h3 className="text-3xl sm:text-5xl sm:leading-extraLoose font-semibold mb-2"> Night Sky </h3> <p className="mb-6"> The `night sky` depicts a time of reflection and how all our actions have consequences. </p> <React.Fragment> <ModalVideo channel="vimeo" autoplay isOpen={this.state.isOpen} videoId="355087595" onClose={() => setOpen(false)} /> <button className="px-12 py-3 bg-gray-100 rounded-full uppercase text-appRed font-medium focus:outline-none hover:bg-appRed hover:text-gray-100 duration-200" onClick={() => this.state({ isOpen: true })} > View video </button> </React.Fragment> </div> </div> </div> </div> </div> </div> </div> ); } } Login.propTypes = { loginUser: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, errors: state.errors, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { loginUser }) )(withRouter(Login)); <file_sep>/src/components/Hero.js /* eslint-disable */ import heroImg from "../assets/img/hero.png"; function Hero(props) { const { title, subHeading, price, type } = props.hero; return ( <div className="grid sm:grid-cols-2 gap-12 items-center relative"> <div className="absolute left-0 z-10 top-0 text-gray-700"> <svg> <defs> <pattern id="eab71dd9-9d7a-47bd-8044-256344ee00d0" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse" > <rect x="0" y="0" width="4" height="4" fill="currentColor" /> </pattern> </defs> <rect width="364" height="384" fill="url(#eab71dd9-9d7a-47bd-8044-256344ee00d0)" /> </svg> </div> <div className="flex flex-col order-last sm:order-first items-baseline justify-start sm:space-y-10 space-y-4 relative z-20 text-bordyColor dark:text-gray-100"> <h2 className="text-3xl xl:text-5xl uppercase font-normal xl:leading-extraLoose"> {title} </h2> <div className="flex flex-col sm:space-y-8 space-y-6"> <h3 className="text-2xl font-bold">{subHeading}</h3> <div className="flex space-x-8 items-center"> <a href="#" className="text-base xl:text-lg uppercase whitespace-nowrap font-black py-3 xl:py-4 px-6 xl:px-12 rounded text-gray-100 bg-appRed" > BID NOW </a> <div> <h3 className="text-xl sm:text-3xl font-bold">{price}</h3> <p>{type}</p> </div> </div> </div> </div> <div className="relative z-20 "> <img src={heroImg} alt="hero" className="max-w-full" /> </div> </div> ); } export default Hero; <file_sep>/src/pages/Asset.js /* eslint-disable */ import React, { Component } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { logoutUser } from "../actions/authActions"; import { getAssetByID, getETHRate, updateAsset } from "../actions/assetActions"; import classnames from "classnames"; import { compose } from "redux"; import { withStyles } from "@material-ui/core"; import exactMath from "exact-math"; import { Spinner } from "@chevtek/react-spinners"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import CurrencyFormat from "react-currency-format"; import { Helmet } from "react-helmet"; import logo from "../assets/img/favicon.png"; import isEmpty from "../validation/is-empty"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class Asset extends Component { constructor(props) { super(props); this.state = { name: "", token_id: "", contract_address: "", price: "", description: "", image: "", youtube: "", facebook: "", twitter: "", instagram: "", errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { window.scrollTo(0, 1); this.props.getETHRate(); this.props.getAssetByID(this.props.match.params.id); } componentDidUpdate(prevProps) { if (this.props.match.params.id !== prevProps.match.params.id) { this.props.getAssetByID(this.props.match.params.id); } } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } if (nextProps.asset.asset) { const asset = nextProps.asset.asset; // If asset field doesn't exist, make empty string asset.name = !isEmpty(asset.name) ? asset.name : ""; asset.token_id = !isEmpty(asset.token_id) ? asset.token_id : ""; asset.contract_address = !isEmpty(asset.contract_address) ? asset.contract_address : ""; asset.price = !isEmpty(asset.price) ? asset.price : ""; asset.description = !isEmpty(asset.description) ? asset.description : ""; asset.image = !isEmpty(asset.image) ? asset.image : ""; asset.twitter = !isEmpty(asset.twitter) ? asset.twitter : ""; asset.facebook = !isEmpty(asset.facebook) ? asset.facebook : ""; asset.youtube = !isEmpty(asset.youtube) ? asset.youtube : ""; asset.instagram = !isEmpty(asset.instagram) ? asset.instagram : ""; // Set component field state this.setState({ name: asset.name, token_id: asset.token_id, contract_address: asset.contract_address, price: asset.price, description: asset.description, image: asset.image, twitter: asset.twitter, facebook: asset.facebook, youtube: asset.youtube, instagram: asset.instagram, }); } } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } onSubmit(e) { e.preventDefault(); const assetData = { id: this.props.match.params.id, name: this.state.name, token_id: this.state.token_id, contract_address: this.state.contract_address, price: this.state.price, description: this.state.description, image: this.state.image, youtube: this.state.youtube, facebook: this.state.facebook, twitter: this.state.twitter, instagram: this.state.instagram, }; this.props.updateAsset(assetData, this.props.history); } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } render() { const { errors } = this.state; const { classes } = this.props; const { ethPrice, ethPriceLoading } = this.props.ethRate; const disableMathError = { invalidError: false }; return ( <div> <Helmet> <meta charSet="utf-8" /> <title>WeAreMasters - Update Profile</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous" /> </Helmet> <div className="container py-4"> <div className="row no-gutter"> <div className="col-md-4 m-auto mt-4"> <Link to="/account"> <img width="100" src={logo} alt="WeAreMasters Logo" className="center-image mt-2 mb-4" /> </Link> </div> <div className="col-md-12"> <div className="col-md-6 m-auto"> <h2 className="text-center mb-4"> <strong style={{ wordSpacing: "5px" }}> APPROVE DIGITAL ART </strong> </h2> <form className="need-validation" onSubmit={this.onSubmit} noValidate > {errors.error && ( <div class="alert alert-danger text-center" role="alert"> {errors.error} </div> )} <div className="mb-4"> <label for="name" className="form-label"> <strong>Title of Digital Art</strong> </label> <input type="text" id="name" name="name" value={this.state.name} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.name, })} placeholder="Enter title of Digital Art" autofocus required /> {errors.name && ( <div className="invalid-feedback">{errors.name}</div> )} </div> <div className="mb-4"> <label for="token_id" className="form-label"> <strong>Token ID for Digital Art</strong> </label> <input type="text" id="token_id" name="token_id" value={this.state.token_id} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.token_id, })} placeholder="Enter Token ID for Digital Art" autofocus required /> {errors.token_id && ( <div className="invalid-feedback">{errors.token_id}</div> )} </div> <div className="mb-4"> <label for="contract_address" className="form-label"> <strong>Contract Address for Digital Art</strong> </label> <input type="text" id="contract_address" name="contract_address" value={this.state.contract_address} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.contract_address, })} placeholder="Enter Contract Address for Digital Art" autofocus required /> {errors.contract_address && ( <div className="invalid-feedback"> {errors.contract_address} </div> )} </div> <div className="mb-4"> <label for="price" className="form-label"> <strong> Price of Digital Art in ETH{" "} {ethPrice === null || ethPriceLoading ? null : ( <CurrencyFormat value={exactMath.mul( 1, ethPrice.amount, disableMathError )} displayType={"text"} thousandSeparator={true} decimalSeperator="." decimalScale={2} fixedDecimalScale={true} renderText={(value) => ( <span>(1 ETH = &#36;{value})</span> )} /> )} </strong> </label> <div className="input-group mb-4"> <span className="input-group-text"> <strong>ETH</strong> </span> <input type="text" id="price" name="price" value={this.state.price} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.price, })} placeholder="e.g 2.5" autofocus required /> </div> {errors.price && ( <div className="invalid-feedback">{errors.price}</div> )} </div> <div className="mb-4"> <label for="description" className="form-label"> <strong>Description for Digital Art</strong> </label> <textarea rows="5" id="description" name="description" value={this.state.description} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.description, })} placeholder="Enter full description for your Digital Art" required ></textarea> {errors.description && ( <div className="invalid-feedback"> {errors.description} </div> )} </div> <div className="mb-4"> <label for="image" className="form-label"> <strong>Image URL for Digital Art</strong> </label> <input type="text" id="image" name="image" value={this.state.image} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.image, })} placeholder="e.g https://filestack.com/WEA9EB7Q5RY" autofocus required /> {errors.image && ( <div className="invalid-feedback">{errors.image}</div> )} </div> <div className="mb-4"> <label for="youtube" className="form-label"> <strong>YouTube URL for Digital Art</strong> </label> <input type="text" id="youtube" name="youtube" value={this.state.youtube} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.youtube, })} placeholder="e.g https://youtu.be/WEA9EB7Q5RY (optional)" autofocus required /> {errors.youtube && ( <div className="invalid-feedback">{errors.youtube}</div> )} </div> <div className="mb-4"> <label for="facebook" className="form-label"> <strong>FaceBook URL for Digital Art</strong> </label> <input type="text" id="facebook" name="facebook" value={this.state.facebook} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.facebook, })} placeholder="e.g https://facebook.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.facebook && ( <div className="invalid-feedback">{errors.facebook}</div> )} </div> <div className="mb-4"> <label for="twitter" className="form-label"> <strong>Twitter URL for Digital Art</strong> </label> <input type="text" id="twitter" name="twitter" value={this.state.twitter} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.twitter, })} placeholder="e.g https://twitter.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.twitter && ( <div className="invalid-feedback">{errors.twitter}</div> )} </div> <div className="mb-4"> <label for="instagram" className="form-label"> <strong>Instagram URL for Digital Art</strong> </label> <input type="text" id="instagram" name="instagram" value={this.state.instagram} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.instagram, })} placeholder="e.g https://instagram.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.instagram && ( <div className="invalid-feedback">{errors.instagram}</div> )} </div> <div className="d-grid gap-2"> <button className="btn btn-lg btn-primary" type="submit"> <Spinner name="updateAssetLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Processing... </Spinner> <Spinner name="updateAssetNotLoading" show={true}> Proceed to Approve Digital Art </Spinner> </button> </div> </form> <hr /> <div className="row"> <div className="col-md-6"> <div className="d-grid gap-2"> <Link to="/account" className="btn btn-dark my-2"> Back Home </Link> </div> </div> <div className="col-md-6"> <div className="d-grid gap-2"> <Link to="/market" className="btn btn-dark my-2"> Market Place </Link> </div> </div> </div> <hr className="mb-5" /> </div> </div> </div> </div> </div> ); } } Asset.propTypes = { getAssetByID: PropTypes.func.isRequired, updateProfile: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, asset: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, getETHRate: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, profile: state.profile, errors: state.errors, ethRate: state.ethRate, asset: state.asset, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getAssetByID, getETHRate, updateAsset, logoutUser, }) )(Asset); <file_sep>/src/components/cards/Music.js /* eslint-disable */ import { Menu, Transition } from "@headlessui/react"; import { Fragment } from "react"; // import play from "../../assets/icons/play.svg"; function classNames(...classes) { return classes.filter(Boolean).join(" "); } function Music(props) { const { title, artist, thumbnail, eth, pricing, price } = props.card; return ( <div className="cursor-pointer"> <div className="relative flex h-track"> <img src={thumbnail} alt="feature" className="rounded-md w-full object-cover" /> <div className="absolute px-4 py-4 w-full h-full flex items-end text-sm text-gray-100 font-medium justify-end"> {/* <button className="text-gray-100 w-8 h-8 rounded-full bg-gray-400 flex items-center justify-center flex-shrink-0 hover:appRed duration-300 focus:outline-none"> <img src={play} /> </button> */} <Menu as="div" className="relative inline-block text-left"> {({ open }) => ( <> <div> <Menu.Button className="text-gray-100 w-6 h-6 rounded-full bg-grey-400 flex items-center justify-center flex-shrink-0 hover:appRed duration-300 focus:outline-none"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots" viewBox="0 0 16 16" > <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z" /> </svg> </Menu.Button> </div> <Transition show={open} as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items static className="origin-top-right absolute z-50 right-0 mt-2 w-44 rounded-md shadow-lg bg-white bg-opacity-60 ring-1 ring-black ring-opacity-5 focus:outline-none" > <div className="py-1"> <Menu.Item> {({ active }) => ( <a href="#" className={classNames( active ? "bg-gray-100 text-gray-900" : "text-black font-black", "block px-4 py-2 text-sm" )} > Share To Twitter </a> )} </Menu.Item> <Menu.Item> {({ active }) => ( <a href="#" className={classNames( active ? "bg-gray-100 text-gray-900" : "text-black font-black", "block px-4 py-2 text-sm" )} > Share To Instagram </a> )} </Menu.Item> <Menu.Item> {({ active }) => ( <a href="#" className={classNames( active ? "bg-gray-100 text-gray-900" : "text-black font-black", "block px-4 py-2 text-sm" )} > Share To Facebook </a> )} </Menu.Item> <form method="POST" action="#"> </form> </div> </Menu.Items> </Transition> </> )} </Menu> {/* <button className="text-gray-100 w-8 h-8 rounded-full bg-appRed flex items-center justify-center flex-shrink-0 hover:appRed duration-300 focus:outline-none"> <svg className="w-6 h-6" viewBox="0 0 24 24"> <path fill="currentColor" d="M16,12A2,2 0 0,1 18,10A2,2 0 0,1 20,12A2,2 0 0,1 18,14A2,2 0 0,1 16,12M10,12A2,2 0 0,1 12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12M4,12A2,2 0 0,1 6,10A2,2 0 0,1 8,12A2,2 0 0,1 6,14A2,2 0 0,1 4,12Z" /> </svg> </button> */} </div> </div> <div className="flex justify-between flex-wrap text-bordyColor dark:text-gray-100"> <a href="#" className="flex flex-col capitalize text-sm my-2"> <p>{title}</p> <div className="flex justify-between"> <p>{artist}</p> <p className="ml-24">{price}</p> </div> </a> <div className="text-xs my-2 uppercase"> <p className="">{eth}</p> <p>{pricing}</p> </div> </div> </div> ); } export default Music; <file_sep>/src/components/Content.js /* eslint-disable */ import React from "react"; import Carousel from "react-multi-carousel"; import "react-multi-carousel/lib/styles.css"; import newImg from "../assets/img/new.jpg"; import fOne from "../assets/img/special/1.gif"; import fTwo from "../assets/img/special/2.gif"; import fThree from "../assets/img/special/3.gif"; import FeatureCard from "../components/cards/Feature"; import FeatureCardB from "../components/cards/FeatureB"; import MusicCard from "../components/cards/Music"; import RadioCard from "../components/cards/Radio"; import SpecialCard from "../components/cards/Special"; import Hero from "../components/Hero"; import artis from "../assets/img/artis.gif"; import Track from "../components/Track"; import { Link } from "react-router-dom"; function Content() { const featureList = [ { id: 1, artist: "Night Sky By", heading1: "Iconicevol", heading2: "BID - 0.11 ETH ($455.12)", title: "The `night sky` depicts a time of reflection and how all our actions have consequences.", img: fOne, link: "#", }, { id: 2, artist: "<NAME>", heading1: "Aradeinde", heading2: "BID - 1.75 ETH ($7,256.95)", title: "Explore the rich, vibrant sounds from across the continent.", img: fTwo, link: "#", }, { id: 3, artist: "Verstappen in Color By", heading1: "Osikhena x Simisola", heading2: "BID - 1.75 ETH ($7,256.95)", title: "Bensoul gets wrapped up in the thrill of the honeymoon phase.", img: fThree, link: "#", }, ]; const trackList = [ { id: 1, title: "Kaleidoscope Woman", artist: "IPneuma", price: "-2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", link: "#", }, { id: 2, title: "Kaleidoscope Woman", artist: "IPneuma", price: "-2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", link: "#", }, { id: 3, title: "Kaleidoscope Woman", artist: "IPneuma", price: "-2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/KBPFHbreehLr7iQYTAeAmAoQqM4GwlRJk9O9x9bLpBy1uVqtJEZTTEXkJ2-0bClw1zvFAmEDhXHctKAdW8tp2LwpMSMSROsUlyjS1A=s0", link: "#", }, { id: 4, title: "Kaleidoscope Woman", artist: "IPneuma", price: "-2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", link: "#", }, { id: 5, title: "Kaleidoscope Woman", artist: "IPneuma", price: "-2ETH/$3000", thumbnail: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", link: "#", }, ]; const artistList = [ { id: 1, artist: "mrmisang", thumbnail: "https://ipfs.pixura.io/ipfs/QmTmytwKogPqvoUrtnX2vHdcZA2stNirbNk7BBu3AAs4Rt/facebook.gif", link: "artist", }, { id: 2, artist: "annadreambrush", thumbnail: "https://ipfs.pixura.io/ipfs/QmdzWRYb8QpsASXuGKW3QgU8JWeU35iQoMCNGxEMjndBZB/profile-300.gif", link: "artist", }, { id: 3, artist: "giovannimotta", thumbnail: "https://ipfs.pixura.io/ipfs/QmVk6XdyASigysct5H5zdcxNQBTgP7jMLARiHJXDe2EdJD/jb.gif", link: "artist", }, { id: 4, artist: "Killercid", thumbnail: "https://ipfs.pixura.io/ipfs/QmP7nRMbPt6hNLm4PE5mwLjPmE2WZquRYso7e3AVRFyyFR/KillerAcidMouth.gif", link: "artist", }, { id: 5, artist: "opheliafu", thumbnail: "https://ipfs.pixura.io/ipfs/QmY8jYdqQHrJ2fGaDwwgpmKHEkGV6yt6HM3JnD6TxLEfih", link: "artist", }, { id: 6, artist: "frenetikvoid", thumbnail: "https://ipfs.pixura.io/ipfs/QmXJVH1ftXkhYafvkY1sp5iJPEMMV5ydwSgcn7rrnebDye/icon.jpg", link: "artist", }, { id: 7, artist: "federicoclapis", thumbnail: "https://ipfs.pixura.io/ipfs/QmfLyf2JYovKQRsBMHGE6Pt5tNMKjyUYoqMLZ9KGsu9VLQ/foro%20profilo%20media%20risoluzi.jpg", link: "artist", }, ]; const tracksGrid = [ { id: 1, title: "Meetbits", artist: "Apple Music African", thumbnail: "https://lh3.googleusercontent.com/d784iHHbqQFVH1XYD6HoT4u3y_Fsu_9FZUltWjnOzoYv7qqB5dLUqpGyHBd8Gq3h4mykK5Enj8pxqOUorgD2PfIWcVj9ugvu8l0=s64", link: "#", }, { id: 2, title: "Zed Run", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/tgpgbT3OwxX4REASLdyafzCWQ5EhOtgSiIlhI3am3aZ_mYPS0WbM9Z4F6hOhb0D-AKqhHlFg6BNBquchQy-_bwY=s64", link: "#", }, { id: 3, title: "crypto punk", artist: "Apple Music African", thumbnail: "https://lh3.googleusercontent.com/BdxvLseXcfl57BiuQcQYdJ64v-aI8din7WPk0Pgo3qQFhAUH-B6i-dCqqc_mCkRIzULmwzwecnohLhrcH8A9mpWIZqA7ygc52Sr81hE=s64", link: "#", }, { id: 4, title: "<NAME>", artist: "Apple Music African", thumbnail: "https://lh3.googleusercontent.com/p6uV0RJZwJb9hcEDOg2VUzw8pr5ZRd62y-VLe7nld5j6yGfJmsUeWugg1RBbEcC84khGArqMX3BwWp6vFa5FjpmUF5pIu6fliNf2=s64", link: "#", }, { id: 5, title: "Rarible", artist: "Apple Music African", thumbnail: "https://lh3.googleusercontent.com/FG0QJ00fN3c_FWuPeUr9-T__iQl63j9hn5d6svW8UqOmia5zp3lKHPkJuHcvhZ0f_Pd6P2COo9tt9zVUvdPxG_9BBw=s64", link: "#", }, { id: 6, title: "<NAME>", artist: "Apple Music African", thumbnail: "https://lh3.googleusercontent.com/Ju9CkWtV-1Okvf45wo8UctR-M9He2PjILP0oOvxE89AyiPPGtrR3gysu1Zgy0hjd2xKIgjJJtWIc0ybj4Vd7wv8t3pxDGHoJBzDB=s64", link: "#", }, { id: 7, title: "Sorare", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/gj47nmAR3valkmpVbwamiuTJfWEWSCyVeORdjM6DRWrZ1o8WaqBxFXmpBrzZnGoWaPwq1Y0jiXRrBLbnLcawAp92=s64", link: "#", }, { id: 8, title: "<NAME>", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/ZTBjAOy61poNh1htSHJ-BeokMpvbui7DdUUMIVk1OI1MtcpGN6sG_oHs38r3AF1JO1l-AxVQZ-aam_h43Dr0XZZC2jblvNYUmZLyTkw=s64", link: "#", }, { id: 9, title: "Decentraland", artist: "Apple Music gospel", thumbnail: newImg, link: "https://lh3.googleusercontent.com/5KIxEGmnAiL5psnMCSLPlfSxDxfRSk4sTQRSyhPdgnu70nGb2YsuVxTmO2iKEkOZOfq476Bl1hAu6aJIKjs1myY=s64", }, { id: 10, title: "Apymon", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/8OogKrYF_3kTL3w_8J_TwEWTn6E4OS_SP5EVdeAJnw7GycEJJy36uZYkLKoMnrX-ObWNYlMpEIu5fGoRMtJrkL8HRnVz4gY8jrD2Cw=s64", link: "#", }, { id: 11, title: "M<NAME>", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/KgKgvjxO8YUDbr747VRfmAEqhvjP8GzNIC23UMheTkzUQ1JmOK07FQ6BhlfBOtrKG_Jm7NoasA6PVch_0Ujf55mp=s64", link: "#", }, { id: 12, title: "Art Blocks Curated", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/ClKm5VUVeA_XuEvxx_jaDyCodqLqQcSNI6Cjk1S_b6YAMK6kLp8t4175jvmb9lQMiv9mWVFcbh4XksrhnHYqwoPD2tOxmVNK6Qn6=s64", link: "#", }, { id: 13, title: "Cryptovoxels", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/Jy6UrKMSi0e9w9jYtC1ON-4tOVXA1mXLk7XCLxvWEDuXeLFExJSYnw2DLAGtP3Ly98WJbrrFm6xEodcrpGnKB2tF=s64", link: "#", }, { id: 14, title: "Somnium space VR", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/mzUNo5vk95qQfpAbXir0_6oJmZlyqnq_ix3BIjmfeVGrFPoxeAqf-vYHMvh115bSdJGxRtgGTWKldOzdJQGtEqGW=s64", link: "#", }, { id: 15, title: "Ghxsts", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/uVziXd8Q64_zvofgrKFp5SmrcObngHoVWZMJQOHAZ3bdERsO4GaYvQcuGsz0ofr8zy8iajJdNQHCwFkSdBmkVy_osTPvoAuQFv489g=s64", link: "#", }, { id: 16, title: "The Sandbox", artist: "Apple Music gospel", thumbnail: "https://lh3.googleusercontent.com/SXH8tW1siikB80rwCRnjm1a5xM_MwTg9Xl9Db6mioIk9HIlDM09pVoSR7GKJgS6ulSUpgW9BDtMk_ePX_NKgO9A=s64", link: "#", }, ]; let specialList = [ { id: 1, title: "<NAME>", subHeading: "the honeymoon phase", img: fOne, link: "#", }, { id: 2, title: "Explore the rich", subHeading: "the honeymoon phase", img: fTwo, link: "#", }, { id: 3, title: "<NAME>", subHeading: "the honeymoon phase", img: fThree, link: "#", }, ]; const ButtonGroup = ({ next, previous, ...rest }) => { const { carouselState: { currentSlide }, } = rest; return ( <div className="carousel-button-group absolute w-full flex items-center"> <button className={ currentSlide === 0 ? "hidden" : "absolute text-white left-0 bg-gray-700 duration-150 bg-opacity-70 focus:outline-none hover:bg-red-600 rounded-full w-6 h-6 flex items-center justify-center" } onClick={() => previous()} > <svg className="h-5 w-5" viewBox="0 0 24 24"> <path fill="currentColor" d="M20,11V13H8L13.5,18.5L12.08,19.92L4.16,12L12.08,4.08L13.5,5.5L8,11H20Z" /> </svg> </button> <button className={ currentSlide === trackList.length - 5 ? "hidden" : "absolute text-white right-0 bg-gray-700 duration-150 bg-opacity-70 focus:outline-none hover:bg-red-600 rounded-full w-6 h-6 flex items-center justify-center" } onClick={() => next()} > <svg className="h-5 w-5" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> {currentSlide} </svg> </button> </div> ); }; const responsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: { max: 4000, min: 3000 }, items: 3, partialVisibilityGutter: 0, }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 5, partialVisibilityGutter: 0, }, tablet: { breakpoint: { max: 1024, min: 650 }, items: 2, partialVisibilityGutter: 0, }, mobile: { breakpoint: { max: 650, min: 0 }, items: 1, partialVisibilityGutter: 0, }, }; const heroResponsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: { max: 4000, min: 3000 }, items: 1, partialVisibilityGutter: 0, }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 1, partialVisibilityGutter: 0, }, tablet: { breakpoint: { max: 1024, min: 650 }, items: 1, partialVisibilityGutter: 0, }, mobile: { breakpoint: { max: 650, min: 0 }, items: 1, partialVisibilityGutter: 0, }, }; const heroes = [ { title: "NEMO ENIM IPSAM VOLUPTATEM QUIA VOLUPTAS", subHeading: "80/90s", price: "ETH 23", type: "XD/20-93", }, { title: "IPSAM VOLUPTATEM NEMO ENIM QUIA VOLUPTAS", subHeading: "80/90s", price: "ETH 19.99", type: "XD/20-93", }, ]; const features = featureList.map((card) => { return <FeatureCard key={card.id} card={card} />; }); const featuresB = featureList.map((card) => { return <FeatureCardB key={card.id} card={card} />; }); const tracks = trackList.map((card) => { return <MusicCard key={card.id} card={card} />; }); const featureCreation = trackList.map((card) => { return ( <div> <MusicCard key={card.id} card={card} />{" "} <hr className="my-4 border-gray-400 border-opacity-10 dark:border-sideBar" /> <MusicCard key={card.id} card={card} /> </div> ); }); const special = specialList.map((card) => { return <SpecialCard key={card.id} card={card} />; }); const radioTracks = artistList.map((card) => { return <RadioCard key={card.id} card={card} />; }); const getHeroes = heroes.map((hero) => { return <Hero key={hero.title} hero={hero} />; }); const gridTracks = <Track cards={tracksGrid} />; return ( <div className="max-w-7xl sm:mx-8 mx-auto text-gray-50 pb-24"> <div className="h-full"> <Carousel arrows={false} showDots={true} autoPlay={true} infinite={true} transitionDuration={500} partialVisible={true} responsive={heroResponsive} itemClass="px-2" className="mt-4 pt-7 pb-8" > {getHeroes} </Carousel> </div> <div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> </div> <div className="mt-12 grid lg:grid-cols-3 gap-6 items-end"> {featuresB} </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> Featured Creations </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <Carousel arrows={false} customButtonGroup={<ButtonGroup />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {featureCreation} </Carousel> </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <br></br> <div className="grid md:grid-cols-12 gap-8 text-bordyColor dark:text-gray-100"> <div className="xl:col-span-2 md:col-span-3 col-span-12"> <img src="https://ipfs.pixura.io/ipfs/QmTmytwKogPqvoUrtnX2vHdcZA2stNirbNk7BBu3AAs4Rt/facebook.gif" className="mx-auto" /> </div> <div className="xl:col-span-10 md:col-span-9 col-span-12 space-y-8 md:px-0 px-4"> <div className="grid md:grid-cols-12 gap-8"> <div className="md:col-span-4 col-span-12 text-center space-y-2"> <h3 className="text-lg capitalize font-semibold">SIGN UP</h3> <p className="text-sm"> Create an account , update your profile, add social links, profile image and bio. </p> </div> <div className="md:col-span-4 col-span-12 text-center space-y-2"> <h3 className="text-lg capitalize font-semibold"> ADD YOUR NFTs{" "} </h3> <p className="text-sm"> Upload your work (image, video, audio, or 3D art), add a title and description, add social links. </p> </div> <div className="md:col-span-4 col-span-12 text-center space-y-2"> <h3 className="text-lg capitalize font-semibold"> LIST THEM FOR SALE </h3> <p className="text-sm"> Choose between auctions and fixed-price listings, and set editions for your works, and we help you sell them! </p> </div> </div> <div className="text-center"> <button className="py-3 px-10 bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 ... rounded uppercase text-white text-sm font-medium"> enter marketplace </button> </div> </div> </div> </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> MBPR Agency </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <Carousel arrows={false} customButtonGroup={<ButtonGroup />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {featureCreation} </Carousel> </div> <div className="mt-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div className="mt-12"> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> Upcoming Hot Drops </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <div className="mt-6 grid lg:grid-cols-3 gap-4 items-end"> {special} </div> </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div className="mt-12 grid lg:grid-cols-3 gap-6 items-end"> {features} </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> featured artists </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <Carousel arrows={false} customButtonGroup={<ButtonGroup />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {radioTracks} </Carousel> </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> new week, new goals </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <Carousel arrows={false} customButtonGroup={<ButtonGroup />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel> </div> <div className="mt-6 mb-2 pt-2 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex relative top-4 justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> Collectibles/coming soon </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> {gridTracks} </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> new week, new goals </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <Carousel arrows={false} customButtonGroup={<ButtonGroup />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel> </div> <div className="mt-6 pt-4 mb-6 border-b border-gray-400 border-opacity-20" /> <div className="mb-2"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100 mb-4"> New Set </h2> <div className="flex flex-row-reverse relative bottom-10"> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <div className="flex"> <div className="w-full"> <img src={artis} className="w-96 h-80 rounded" alt="img" /> <div className="flex"> <p className="text-xl">Kissed by the sun</p> <span className="text-sm mt-2 ml-28">-2ETH/$3000</span> </div> <p className="text-lg">Dorgu</p> </div> <div className="w-full pt-20 pr-24 relative -left-20"> <p className="text-sm"> <p className="inline font-black text-lg"> {" "} The Deconstruction Of A Nation </p>{" "} - has been televised since Nigeria won it’s independence from the British in 1960. Our living rooms or parlors have become the arena citizens of our nascent nation have sat to watch the deconstruction of the dream our founding fathers had. We’ve seen civil war, coup’s , skirmishes and the dominance of our military. The deconstruction of a nation is mixed media reminding us how far we’ve come as a people. </p> </div> </div> </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <div> <div className="flex justify-between items-center"> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> new week, new goals </h2> <Link to="/view"> <a href="#" className="capitalize text-appRed flex items-center"> view all <svg className="w-5 h-5 ml-2" viewBox="0 0 24 24"> <path fill="currentColor" d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" /> </svg> </a> </Link> </div> <Carousel arrows={false} customButtonGroup={<ButtonGroup />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-8" > {tracks} </Carousel> </div> <div className="mt-6 mb-6 pt-4 border-b border-gray-400 border-opacity-20" /> <h2 className="text-xl capitalize font-medium text-bordyColor dark:text-gray-100"> Something something </h2> <div className="flex justify-between mt-16"> <div className="w-full"> <img src={artis} className="w-96 h-80 rounded" alt="img" /> <div className="flex"> <p className="text-xl">Kissed by the sun</p> <span className="text-sm mt-2 ml-28">-2ETH/$3000</span> </div> <p className="text-base">Dorgu</p> </div> <div className="w-full"> <img src={artis} className="w-96 h-80 rounded" alt="img" /> <div className="flex"> <p className="text-xl">Kissed by the sun</p> <span className="text-sm mt-2 ml-28">-2ETH/$3000</span> </div> <p className="text-base">Dorgu</p> </div> <div className="w-full"> <img src={artis} className="w-96 h-80 rounded" alt="img" /> <div className="flex"> <p className="text-xl">Kissed by the sun</p> <span className="text-sm mt-2 ml-28">-2ETH/$3000</span> </div> <p className="text-base">Dorgu</p> </div> </div> </div> ); } export default Content; <file_sep>/src/pages/Signup.js /* eslint-disable */ // import insta from "../assets/icons/insta.png"; // import twitter from "../assets/icons/twitter.png"; import React, { Component } from "react"; import ModalVideo from "react-modal-video"; import signup from "../assets/img/signup.jpg"; import "../assets/video.min.css"; import logo from "../assets/img/logo-white.svg"; import PropTypes from "prop-types"; import classnames from "classnames"; import { connect } from "react-redux"; import { withRouter, Link } from "react-router-dom"; import { registerUser } from "../actions/authActions"; import { Spinner } from "@chevtek/react-spinners"; import { withStyles } from "@material-ui/core/styles"; import compose from "recompose/compose"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import "../assets/video.min.css"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class Signup extends Component { constructor() { super(); this.state = { firstName: "", lastName: "", username: "", email: "", phone: "", location: "", password: "", confirmPassword: "", isOpen: false, errors: {}, }; this.onChange = this.onChange.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { if (this.props.auth.isAuthenticated) { this.props.history.push("/account"); } } componentWillReceiveProps(nextProps) { if (nextProps.auth.isAuthenticated) { this.props.history.push("/account"); } if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } handleKeyDown(e) { if (e.key === " ") { e.preventDefault(); } } onSubmit(e) { e.preventDefault(); const newUser = { firstName: this.state.firstName, lastName: this.state.lastName, username: this.state.username, email: this.state.email, phone: this.state.phone, location: this.state.location, password: <PASSWORD>, confirmPassword: <PASSWORD>, }; console.log("Reached here..."); this.props.registerUser(newUser); } render() { const { errors } = this.state; const { classes } = this.props; return ( <div className="relative h-full flex items-center justify-center"> <div className="max-w-7xl mx-auto py-16 lg:px-8 px-4"> <div className="grid lg:grid-cols-7 gap-8 text-bordyColor dark:text-gray-200 items-center"> <div className="lg:col-span-3 px-8 lg:order-first order-last"> <div> <Link to="/"> <img src={logo} width="225px" className="mb-10" /> </Link> <h2 className="sm:text-5xl text-3xl sm:leading-extraLoose font-bold"> Create Account </h2> </div> <form className="mt-12 space-y-4" onSubmit={this.onSubmit} novalidate="novalidate" > <div className="grid xl:grid-cols-2 lg:grid-cols-1 sm:grid-cols-2 gap-4"> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium">First Name</label> <input type="text" id="firstName" name="firstName" placeholder="Enter first name" onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.firstName, } )} required /> {errors.firstName && ( <div className="form-error">{errors.firstName}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium">Last Name</label> <input type="text" id="lastName" name="lastName" placeholder="Enter last name" value={this.state.lastName} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.lastName, } )} required /> {errors.lastName && ( <div className="form-error">{errors.lastName}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium">username</label> <input type="text" id="username" name="username" placeholder="Enter Username" value={this.state.username} onChange={this.onChange} onKeyDown={this.handleKeyDown} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.username, } )} required /> {errors.username && ( <div className="form-error">{errors.username}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium"> email address </label> <input type="email" id="email" name="email" placeholder="Enter Email Address" value={this.state.email} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.email, } )} required /> {errors.email && ( <div className="form-error">{errors.email}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium">phone</label> <input type="text" id="phone" name="phone" placeholder="Enter Phone" value={this.state.phone} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.phone, } )} required /> {errors.email && ( <div className="form-error">{errors.email}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium">location</label> <div className="select-wrapper country relative"> <select id="location" name="location" value={this.state.location} onChange={this.onChange} className="px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar w-full focus:outline-none" > <option value={0}>Select Location</option> <option value="Afghanistan">Afghanistan</option> <option value="Åland Islands">Åland Islands</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa">American Samoa</option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> <option value="Anguilla">Anguilla</option> <option value="Antarctica">Antarctica</option> <option value="Antigua and Barbuda"> Antigua and Barbuda </option> <option value="Argentina">Argentina</option> <option value="Armenia">Armenia</option> <option value="Aruba">Aruba</option> <option value="Australia">Australia</option> <option value="Austria">Austria</option> <option value="Azerbaijan">Azerbaijan</option> <option value="Bahamas">Bahamas</option> <option value="Bahrain">Bahrain</option> <option value="Bangladesh">Bangladesh</option> <option value="Barbados">Barbados</option> <option value="Belarus">Belarus</option> <option value="Belgium">Belgium</option> <option value="Belize">Belize</option> <option value="Benin">Benin</option> <option value="Bermuda">Bermuda</option> <option value="Bhutan">Bhutan</option> <option value="Bolivia">Bolivia</option> <option value="Bosnia and Herzegovina"> Bosnia and Herzegovina </option> <option value="Botswana">Botswana</option> <option value="Bouvet Island">Bouvet Island</option> <option value="Brazil">Brazil</option> <option value="British Indian Ocean Territory"> British Indian Ocean Territory </option> <option value="Brunei Darussalam"> Brunei Darussalam </option> <option value="Bulgaria">Bulgaria</option> <option value="Burkina Faso">Burkina Faso</option> <option value="Burundi">Burundi</option> <option value="Cambodia">Cambodia</option> <option value="Cameroon">Cameroon</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="Cayman Islands">Cayman Islands</option> <option value="Central African Republic"> Central African Republic </option> <option value="Chad">Chad</option> <option value="Chile">Chile</option> <option value="China">China</option> <option value="Christmas Island"> Christmas Island </option> <option value="Cocos (Keeling) Islands"> Cocos (Keeling) Islands </option> <option value="Colombia">Colombia</option> <option value="Comoros">Comoros</option> <option value="Congo">Congo</option> <option value="Congo, The Democratic Republic of The"> Congo, The Democratic Republic of The </option> <option value="Cook Islands">Cook Islands</option> <option value="Costa Rica">Costa Rica</option> <option value="Cote D'ivoire">Cote D'ivoire</option> <option value="Croatia">Croatia</option> <option value="Cuba">Cuba</option> <option value="Cyprus">Cyprus</option> <option value="Czech Republic">Czech Republic</option> <option value="Denmark">Denmark</option> <option value="Djibouti">Djibouti</option> <option value="Dominica">Dominica</option> <option value="Dominican Republic"> Dominican Republic </option> <option value="Ecuador">Ecuador</option> <option value="Egypt">Egypt</option> <option value="El Salvador">El Salvador</option> <option value="Equatorial Guinea"> Equatorial Guinea </option> <option value="Eritrea">Eritrea</option> <option value="Estonia">Estonia</option> <option value="Ethiopia">Ethiopia</option> <option value="Falkland Islands (Malvinas)"> Falkland Islands (Malvinas) </option> <option value="Faroe Islands">Faroe Islands</option> <option value="Fiji">Fiji</option> <option value="Finland">Finland</option> <option value="France">France</option> <option value="French Guiana">French Guiana</option> <option value="French Polynesia"> French Polynesia </option> <option value="French Southern Territories"> French Southern Territories </option> <option value="Gabon">Gabon</option> <option value="Gambia">Gambia</option> <option value="Georgia">Georgia</option> <option value="Germany">Germany</option> <option value="Ghana">Ghana</option> <option value="Gibraltar">Gibraltar</option> <option value="Greece">Greece</option> <option value="Greenland">Greenland</option> <option value="Grenada">Grenada</option> <option value="Guadeloupe">Guadeloupe</option> <option value="Guam">Guam</option> <option value="Guatemala">Guatemala</option> <option value="Guernsey">Guernsey</option> <option value="Guinea">Guinea</option> <option value="Guinea-bissau">Guinea-bissau</option> <option value="Guyana">Guyana</option> <option value="Haiti">Haiti</option> <option value="Heard Island and Mcdonald Islands"> Heard Island and Mcdonald Islands </option> <option value="Holy See (Vatican City State)"> Holy See (Vatican City State) </option> <option value="Honduras">Honduras</option> <option value="Hong Kong">Hong Kong</option> <option value="Hungary">Hungary</option> <option value="Iceland">Iceland</option> <option value="India">India</option> <option value="Indonesia">Indonesia</option> <option value="Iran, Islamic Republic of"> Iran, Islamic Republic of </option> <option value="Iraq">Iraq</option> <option value="Ireland">Ireland</option> <option value="Isle of Man">Isle of Man</option> <option value="Israel">Israel</option> <option value="Italy">Italy</option> <option value="Jamaica">Jamaica</option> <option value="Japan">Japan</option> <option value="Jersey">Jersey</option> <option value="Jordan">Jordan</option> <option value="Kazakhstan">Kazakhstan</option> <option value="Kenya">Kenya</option> <option value="Kiribati">Kiribati</option> <option value="Korea, Democratic People's Republic of"> Korea, Democratic People's Republic of </option> <option value="Korea, Republic of"> Korea, Republic of </option> <option value="Kuwait">Kuwait</option> <option value="Kyrgyzstan">Kyrgyzstan</option> <option value="Lao People's Democratic Republic"> Lao People's Democratic Republic </option> <option value="Latvia">Latvia</option> <option value="Lebanon">Lebanon</option> <option value="Lesotho">Lesotho</option> <option value="Liberia">Liberia</option> <option value="Libyan Arab Jamahiriya"> Libyan Arab Jamahiriya </option> <option value="Liechtenstein">Liechtenstein</option> <option value="Lithuania">Lithuania</option> <option value="Luxembourg">Luxembourg</option> <option value="Macao">Macao</option> <option value="Macedonia, The Former Yugoslav Republic of"> Macedonia, The Former Yugoslav Republic of </option> <option value="Madagascar">Madagascar</option> <option value="Malawi">Malawi</option> <option value="Malaysia">Malaysia</option> <option value="Maldives">Maldives</option> <option value="Mali">Mali</option> <option value="Malta">Malta</option> <option value="Marshall Islands"> Marshall Islands </option> <option value="Martinique">Martinique</option> <option value="Mauritania">Mauritania</option> <option value="Mauritius">Mauritius</option> <option value="Mayotte">Mayotte</option> <option value="Mexico">Mexico</option> <option value="Micronesia, Federated States of"> Micronesia, Federated States of </option> <option value="Moldova, Republic of"> Moldova, Republic of </option> <option value="Monaco">Monaco</option> <option value="Mongolia">Mongolia</option> <option value="Montenegro">Montenegro</option> <option value="Montserrat">Montserrat</option> <option value="Morocco">Morocco</option> <option value="Mozambique">Mozambique</option> <option value="Myanmar">Myanmar</option> <option value="Namibia">Namibia</option> <option value="Nauru">Nauru</option> <option value="Nepal">Nepal</option> <option value="Netherlands">Netherlands</option> <option value="Netherlands Antilles"> Netherlands Antilles </option> <option value="New Caledonia">New Caledonia</option> <option value="New Zealand">New Zealand</option> <option value="Nicaragua">Nicaragua</option> <option value="Niger">Niger</option> <option value="Nigeria">Nigeria</option> <option value="Niue">Niue</option> <option value="Norfolk Island">Norfolk Island</option> <option value="Northern Mariana Islands"> Northern Mariana Islands </option> <option value="Norway">Norway</option> <option value="Oman">Oman</option> <option value="Pakistan">Pakistan</option> <option value="Palau">Palau</option> <option value="Palestinian Territory, Occupied"> Palestinian Territory, Occupied </option> <option value="Panama">Panama</option> <option value="Papua New Guinea"> Papua New Guinea </option> <option value="Paraguay">Paraguay</option> <option value="Peru">Peru</option> <option value="Philippines">Philippines</option> <option value="Pitcairn">Pitcairn</option> <option value="Poland">Poland</option> <option value="Portugal">Portugal</option> <option value="Puerto Rico">Puerto Rico</option> <option value="Qatar">Qatar</option> <option value="Reunion">Reunion</option> <option value="Romania">Romania</option> <option value="Russian Federation"> Russian Federation </option> <option value="Rwanda">Rwanda</option> <option value="Saint Helena">Saint Helena</option> <option value="Saint Kitts and Nevis"> Saint Kitts and Nevis </option> <option value="Saint Lucia">Saint Lucia</option> <option value="Saint Pierre and Miquelon"> Saint Pierre and Miquelon </option> <option value="Saint Vincent and The Grenadines"> Saint Vincent and The Grenadines </option> <option value="Samoa">Samoa</option> <option value="San Marino">San Marino</option> <option value="Sao Tome and Principe"> Sao Tome and Principe </option> <option value="Saudi Arabia">Saudi Arabia</option> <option value="Senegal">Senegal</option> <option value="Serbia">Serbia</option> <option value="Seychelles">Seychelles</option> <option value="Sierra Leone">Sierra Leone</option> <option value="Singapore">Singapore</option> <option value="Slovakia">Slovakia</option> <option value="Slovenia">Slovenia</option> <option value="Solomon Islands">Solomon Islands</option> <option value="Somalia">Somalia</option> <option value="South Africa">South Africa</option> <option value="South Georgia and The South Sandwich Islands"> South Georgia and The South Sandwich Islands </option> <option value="Spain">Spain</option> <option value="Sri Lanka">Sri Lanka</option> <option value="Sudan">Sudan</option> <option value="Suriname">Suriname</option> <option value="Svalbard and Jan Mayen"> Svalbard and Jan Mayen </option> <option value="Swaziland">Swaziland</option> <option value="Sweden">Sweden</option> <option value="Switzerland">Switzerland</option> <option value="Syrian Arab Republic"> Syrian Arab Republic </option> <option value="Taiwan, Province of China"> Taiwan, Province of China </option> <option value="Tajikistan">Tajikistan</option> <option value="Tanzania, United Republic of"> Tanzania, United Republic of </option> <option value="Thailand">Thailand</option> <option value="Timor-leste">Timor-leste</option> <option value="Togo">Togo</option> <option value="Tokelau">Tokelau</option> <option value="Tonga">Tonga</option> <option value="Trinidad and Tobago"> Trinidad and Tobago </option> <option value="Tunisia">Tunisia</option> <option value="Turkey">Turkey</option> <option value="Turkmenistan">Turkmenistan</option> <option value="Turks and Caicos Islands"> Turks and Caicos Islands </option> <option value="Tuvalu">Tuvalu</option> <option value="Uganda">Uganda</option> <option value="Ukraine">Ukraine</option> <option value="United Arab Emirates"> United Arab Emirates </option> <option value="United Kingdom">United Kingdom</option> <option value="United States">United States</option> <option value="United States Minor Outlying Islands"> United States Minor Outlying Islands </option> <option value="Uruguay">Uruguay</option> <option value="Uzbekistan">Uzbekistan</option> <option value="Vanuatu">Vanuatu</option> <option value="Venezuela">Venezuela</option> <option value="Viet Nam">Viet Nam</option> <option value="Virgin Islands, British"> Virgin Islands, British </option> <option value="Virgin Islands, U.S."> Virgin Islands, U.S. </option> <option value="Wallis and Futuna"> Wallis and Futuna </option> <option value="Western Sahara">Western Sahara</option> <option value="Yemen">Yemen</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> {errors.location && ( <div className="form-error">{errors.location}</div> )} </div> </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium">Password</label> <input type="password" id="password" name="password" placeholder="Enter Password" value={this.state.password} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.password, } )} required /> {errors.password && ( <div className="form-error">{errors.password}</div> )} </div> <div className="form-control flex flex-col text-sm space-y-2 text-bordyColor dark:text-gray-400 w-full"> <label className="capitalize font-medium"> Confirm Password </label> <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Confirm Password" value={this.state.confirmPassword} onChange={this.onChange} className={classnames( "px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-sideBar", { "is-invalid": errors.confirmPassword, } )} required /> {errors.confirmPassword && ( <div className="form-error">{errors.confirmPassword}</div> )} </div> </div> <div className="flex flex-col justify-center items-center space-y-4"> <button className="px-4 py-3 bg-appRed text-sm text-gray-100 font-semibold rounded-sm w-full mt-8"> <Spinner name="registerLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Signing up... </Spinner> <Spinner name="registerNotLoading" show={true}> Sign up </Spinner> </button> {/* <p className="text-sm">or</p> <div className="flex space-x-4 w-full"> <button className="flex items-center justify-center px-8 py-3 bg-gray-100 capitalize text-sm text-gray-600 font-semibold rounded-sm w-full"> <img src={insta} className="w-5 h-5 mr-4" alt="google" /> instagram </button> <button className="flex items-center justify-center px-8 py-3 bg-gray-100 capitalize text-sm text-gray-600 font-semibold rounded-sm w-full"> <img src={twitter} className="w-5 h-5 mr-4" alt="twitter" /> twitter </button> </div> */} <div className="pt-8 text-sm text-center w-full space-y-4"> <p>Already have account?</p> <Link to="/login" className="flex items-center justify-center px-8 py-3 bg-gray-100 text-sm text-gray-600 font-semibold rounded-sm w-full" > Sign in </Link> </div> </div> </form> </div> <div className="lg:col-span-4"> <div className="relative w-full text-gray-100"> <img src={signup} className="" alt="signup" /> <div className="absolute w-full h-full bg-gradient-to-t from-black top-0 left-0 bg-opacity-60 flex px-8 pb-8 items-end justify-start"> <div className="max-w-sm"> <h3 className="text-3xl sm:text-5xl sm:leading-extraLoose font-semibold mb-2"> Night Sky </h3> <p className="mb-6"> The `night sky` depicts a time of reflection and how all our actions have consequences. </p> <React.Fragment> <ModalVideo channel="vimeo" autoplay isOpen={this.state.isOpen} videoId="355087595" onClose={() => this.setState({ isOpen: false })} /> <button className="px-12 py-3 bg-gray-100 rounded-full uppercase text-appRed font-medium focus:outline-none hover:bg-appRed hover:text-gray-100 duration-200" onClick={() => this.setState({ isOpen: true })} > View video </button> </React.Fragment> </div> </div> </div> </div> </div> </div> </div> ); } } Signup.propTypes = { registerUser: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, errors: state.errors, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { registerUser }) )(withRouter(Signup)); <file_sep>/src/components/Modal.js // import React from "react"; // import Modal from "react-modal"; // const customStyles = { // content: { // top: "50%", // left: "50%", // right: "auto", // bottom: "auto", // marginRight: "-50%", // transform: "translate(-50%, -50%)", // width: "335px", // borderRadius: "15px", // }, // }; // Modal.setAppElement("#root"); // export const Popup = ({ children }) => { // const [isOpen, setIsOpen] = React.useState(false); // // // const isOpen = () => { // // // setIsOpen(true); // // // }; // const onClose = () => { // setIsOpen(false); // }; // isOpen ? ( // <Modal // isOpen={isOpen} // onRequestClose={onClose} // style={customStyles} // className="top-2/4 right-auto bottom-auto left-2/4 -mr-2 absolute bg-white overflow-auto outline-none rounded-md px-7 md:px-10 transform translate-x-1/2 translate-y-1/2 md:w-4/5 overscroll-auto h-4/5" // overlayClassName="bg-elr-black bg-opacity-60 fixed inset-0" // > // <div // className="cursor-pointer text-right mt-2 text-elr-black font-bold rounded w-50" // onClick={onClose} // > // X // </div> // {children} // </Modal> // ) : null; // }; <file_sep>/src/reducers/assetReducer.js import { GET_ASSETS, GET_RECENT_ASSETS, GET_ALL_ASSETS, GET_ASSET, ASSET_LOADING, } from "../actions/types"; const initialState = { assets: [], recentAssets: [], allAssets: [], asset: {}, assetLoading: false, }; // eslint-disable-next-line export default function (state = initialState, action) { switch (action.type) { case ASSET_LOADING: return { ...state, assetLoading: true, }; case GET_ASSETS: return { ...state, assets: action.payload, assetLoading: false, }; case GET_RECENT_ASSETS: return { ...state, recentAssets: action.payload, assetLoading: false, }; case GET_ALL_ASSETS: return { ...state, allAssets: action.payload, assetLoading: false, }; case GET_ASSET: return { ...state, asset: action.payload, assetLoading: false, }; default: return state; } } <file_sep>/src/actions/profileActions.js import axios from "axios"; import { spinnerService } from "@chevtek/react-spinners"; import swal from "@sweetalert/with-react"; // import Noty from "noty"; // import "../../node_modules/noty/lib/noty.css"; // import "../../node_modules/noty/lib/themes/mint.css"; import { GET_PROFILE, GET_PROFILES, PROFILE_LOADING, CLEAR_CURRENT_PROFILE, GET_ERRORS, SET_CURRENT_USER, CLEAR_ERRORS, } from "./types"; // Get current profile export const getCurrentProfile = () => (dispatch) => { dispatch(setProfileLoading()); axios .get("/api/profile") .then((res) => dispatch({ type: GET_PROFILE, payload: res.data, }) ) .catch((err) => { console.log(err); dispatch({ type: GET_PROFILE, payload: {}, }); }); }; // Get profile by username export const getProfileByUsername = (username) => (dispatch) => { dispatch(setProfileLoading()); axios .get(`/api/profile/username/${username}`) .then((res) => dispatch({ type: GET_PROFILE, payload: res.data, }) ) .catch((err) => dispatch({ type: GET_PROFILE, payload: null, }) ); }; // Update Profile export const updateProfile = (profileData, history) => (dispatch) => { dispatch(clearErrors()); spinnerService.hide("updateProfileNotLoading"); spinnerService.show("updateProfileLoading"); axios .post("/api/profile", profileData) .then((res) => { spinnerService.hide("updateProfileLoading"); spinnerService.show("updateProfileNotLoading"); dispatch({ type: GET_PROFILE, payload: res.data, }); swal("Success!", "Profile Updated Successfully.", "success").then(() => { history.push("/account"); }); }) .catch((err) => { spinnerService.show("updateProfileNotLoading"); spinnerService.hide("updateProfileLoading"); window.scrollTo(0, 1); dispatch({ type: GET_ERRORS, payload: err.response.data, }); }); }; // Get all profiles export const getProfiles = () => (dispatch) => { dispatch(setProfileLoading()); axios .get("/api/profile/all") .then((res) => dispatch({ type: GET_PROFILES, payload: res.data, }) ) .catch((err) => dispatch({ type: GET_PROFILES, payload: null, }) ); }; // Delete account & profile export const deleteAccount = () => (dispatch) => { if (window.confirm("Are you sure? This can NOT be undone!")) { axios .delete("/api/profile") .then((res) => dispatch({ type: SET_CURRENT_USER, payload: {}, }) ) .catch((err) => dispatch({ type: GET_ERRORS, payload: err.response.data, }) ); } }; // Set Logged in User export const setCurrentUser = (decoded) => { return { type: SET_CURRENT_USER, payload: decoded, }; }; // Profile Loading export const setProfileLoading = () => { return { type: PROFILE_LOADING, }; }; // Clear profile export const clearCurrentProfile = () => { return { type: CLEAR_CURRENT_PROFILE, }; }; // Clear errors export const clearErrors = () => { return { type: CLEAR_ERRORS, }; }; <file_sep>/src/reducers/ethRateReducer.js import { GET_ETH_RATE, ETH_RATE_LOADING } from "../actions/types"; const initialState = { ethPrice: null, ethPriceLoading: false, }; export default function getETHRate(state = initialState, action) { switch (action.type) { case ETH_RATE_LOADING: return { ...state, ethPriceLoading: true, }; case GET_ETH_RATE: return { ...state, ethPrice: action.payload, ethPriceLoading: false, }; default: return state; } } <file_sep>/src/pages/Profile.js /* eslint-disable */ import React from "react"; import Carousel from "react-multi-carousel"; import Masonry, { ResponsiveMasonry } from "react-responsive-masonry"; import { Link } from "react-router-dom"; import artist from "../assets/img/artis.gif"; import Footer from "../components/Footer"; import NewSideBar from "../components/NewSideBar"; function Profile() { const minuteSeconds = 60; const hourSeconds = 3600; const daySeconds = 86400; const timerProps = { isPlaying: true, size: 120, strokeWidth: 6, }; const renderTime = (dimension, time) => { return ( <div className="time-wrapper"> <div className="time">{time}</div> <div>{dimension}</div> </div> ); }; const stratTime = Date.now() / 1000; // use UNIX timestamp in seconds const endTime = stratTime + 1043248; // use UNIX timestamp in seconds const remainingTime = endTime - stratTime; const days = Math.ceil(remainingTime / daySeconds); const daysDuration = days * daySeconds; const getTimeSeconds = (time) => (minuteSeconds - time) | 0; const getTimeMinutes = (time) => ((time % hourSeconds) / minuteSeconds) | 0; const getTimeHours = (time) => ((time % daySeconds) / hourSeconds) | 0; const getTimeDays = (time) => (time / daySeconds) | 0; const UrgeWithPleasureComponent = () => ( <CountdownCircleTimer isPlaying duration={10} colors={[ ["#004777", 0.33], ["#F7B801", 0.33], ["#A30000", 0.33], ]} > {({ remainingTime }) => remainingTime} </CountdownCircleTimer> ); const collection = [ { img: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", }, { img: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", }, { img: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", }, { img: "https://lh3.googleusercontent.com/m6rihxymByjWXFJWO3h4lIz2EJcWWxtlmRuH9VgpFbTRjBxltm7oyO7G0vfkeSZArdqsE-VI573oygdpURJtCtwqfAiJlMO-Fvfkjw=s0", }, { img: "https://lh3.googleusercontent.com/KBPFHbreehLr7iQYTAeAmAoQqM4GwlRJk9O9x9bLpBy1uVqtJEZTTEXkJ2-0bClw1zvFAmEDhXHctKAdW8tp2LwpMSMSROsUlyjS1A=s0", }, { img: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", }, ]; const creation = [ { img: "https://lh3.googleusercontent.com/CPe3saEkiRAMGiOuKIMtGXnent817rjIKGcwBRhSADk5zzFLsFxbHoWwc0qKqGqCFONS0E5SvT0ljbsZBiKLWolVFWP75PtcGCuh=s0", }, { img: "https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0", }, ]; const responsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: { max: 4000, min: 3000 }, items: 1, partialVisibilityGutter: 0, }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 1, partialVisibilityGutter: 0, }, tablet: { breakpoint: { max: 1024, min: 650 }, items: 1, partialVisibilityGutter: 0, }, mobile: { breakpoint: { max: 650, min: 0 }, items: 1, partialVisibilityGutter: 0, }, }; const getCollections = collection.map((img) => { return ( <div className="w-full px-2 py-2"> <img src={img.img} className="object-cover w-full"></img> </div> ); }); const getCreations = creation.map((img) => { return ( <div className="w-full h-track"> <img src={img.img} className="object-cover w-full h-full"></img> </div> ); }); const Navigation = ({ goToSlide, ...rest }) => { const { carouselState: { currentSlide }, } = rest; return ( <div className="carousel-button-group absolute top-0 right-0 left-0 text-center"> <button onClick={() => goToSlide(0)} className={ currentSlide === 0 ? "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none border-b border-gray-400" : "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none" } > {" "} creations{" "} </button> <button onClick={() => goToSlide(1)} className={ currentSlide === 1 ? "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none border-b border-gray-400" : "px-2 sm:px-8 duration-100 ease-in-out py-2 mx-2 text-lg uppercase focus:outline-none" } > {" "} series{" "} </button> </div> ); }; return ( <div> <div className="py-1 bg-black w-full h-10 fixed z-30 bg-opacity-90"> <NewSideBar /> </div> <div className="pb-24 pt-12"> <div className="max-w-7xl mx-auto text-bordyColor dark:text-gray-100 py-1 relative lg:px-16 px-4 mb-16"> <div className="grid grid-cols-12 gap-4 -mb-60"> <div className="col-span-12 sm:col-span-4 lg:col-span-5"> <div className="w-24 h-24"> <img src={artist} className="mx-auto rounded-full" /> </div> <h4 className="mt-4">@artistname</h4> <div className="flex space-x-6"> <p>Followers: 786</p> <p className="">Following: 6</p> </div> <div className="my-4"> <button className="text-appRed focus:outline-none"> twitter.com/@artistname </button> </div> <div className="mt-8 mb-12"> <a href="#" className="bg-gray-100 rounded-sm py-2 px-4 text-sm font-medium text-gray-600" > Sign up to follow </a> </div> <h2 className="text-xl font-semibold uppercase mt-4"> product name </h2> <div className="my-4"> <p> The `night sky` depicts a time of reflection and how all our actions have consequences. </p> <p className="text-gray-400 mt-4"> #2d #3d #animated #animation #cartoon #future #illustration #misang #mrmisang #psychedelic #scifi #SF #surreal </p> </div> <div className="flex"> <button className="py-2 px-10 font-black uppercase rounded bg-appRed text-white mt-8"> Bid now </button> <p className="mt-8 ml-8 py-2">- 2ETH/$3000</p> </div> </div> <div className="col-span-12 lg:col-span-7"> <img src="https://lh3.googleusercontent.com/9nTeFgvJAxS5I2es5KkxnjuP7dwbt0wWyR4V34LlaUPOQnBHK-omJbSw3lUeWvRhki7AJocyzYspSneOuXqqQdauxF_4-dyLwwz5=s0" className="h-3/4 w-3/4"/> </div> </div> <div className="pb-10 pt-40 border-b border-gray-400 border-opacity-20" /> <div className="grid grid-cols-12 mt-8"> <div className="col-span-12 relative"> <Carousel renderButtonGroupOutside={true} arrows={false} customButtonGroup={<Navigation />} partialVisible={true} responsive={responsive} itemClass="px-2" className="mt-16" > <div className="mt-8"> <ResponsiveMasonry columnsCountBreakPoints={{ 350: 1, 750: 2, 900: 3 }} > <Masonry gutter="20">{getCollections}</Masonry> </ResponsiveMasonry> {/* <div className="grid grid-cols-4 gap-4">{getCollections}</div> */} </div> <div className="mt-8"> <div className="grid grid-cols-4 gap-4">{getCreations}</div> </div> </Carousel> </div> </div> </div> <div className="box fixed bottom-0 left-0 w-full z-50"> <div className="items-center h-16 bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 ... py-4 px-4 sm:flex space-y-4 sm:space-y-0 text-gray-100"> <button className="mb-8">x</button> <div className="border-l h-14 border-white-600 border-opacity-90 mt-4 ml-16"/> <div className="space-y-1 ml-6"> <h2 className="text-base sm:text-xl font-semibold"> We are building a community of 1000+ Digital Artists </h2> </div> <div className="ml-auto"> <Link to="/sign-up" className="bg-gray-100 font-medium px-12 capitalize py-2 text-gray-600 flex focus:outline-none rounded" > Try it Now </Link> </div> </div> </div> <Footer /> </div> </div> ); } export default Profile; <file_sep>/src/pages/UpdateProfile.js /* eslint-disable */ import React, { Component } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { logoutUser } from "../actions/authActions"; import { getCurrentProfile, updateProfile } from "../actions/profileActions"; import classnames from "classnames"; import { compose } from "redux"; import { withStyles } from "@material-ui/core"; import { client } from "filestack-react"; import { Spinner } from "@chevtek/react-spinners"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import { Helmet } from "react-helmet"; import logo from "../assets/img/favicon.png"; import isEmpty from "../validation/is-empty"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class UpdateProfile extends Component { constructor(props) { super(props); this.state = { firstName: "", lastName: "", phone: "", location: "", ethAddress: "", youtubeURL: "", facebookURL: "", twitterURL: "", instagramURL: "", errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { window.scrollTo(0, 1); this.props.getCurrentProfile(); } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } if (nextProps.profile.profile) { const profile = nextProps.profile.profile; // If profile field doesn't exist, make empty string profile.firstName = !isEmpty(profile.firstName) ? profile.firstName : ""; profile.lastName = !isEmpty(profile.lastName) ? profile.lastName : ""; profile.phone = !isEmpty(profile.phone) ? profile.phone : ""; profile.location = !isEmpty(profile.location) ? profile.location : ""; profile.ethAddress = !isEmpty(profile.ethAddress) ? profile.ethAddress : ""; profile.bio = !isEmpty(profile.bio) ? profile.bio : ""; profile.social = !isEmpty(profile.social) ? profile.social : {}; profile.twitter = !isEmpty(profile.social.twitter) ? profile.social.twitter : ""; profile.facebook = !isEmpty(profile.social.facebook) ? profile.social.facebook : ""; profile.linkedin = !isEmpty(profile.social.linkedin) ? profile.social.linkedin : ""; profile.youtube = !isEmpty(profile.social.youtube) ? profile.social.youtube : ""; profile.instagram = !isEmpty(profile.social.instagram) ? profile.social.instagram : ""; // Set component field state this.setState({ firstName: profile.firstName, lastName: profile.lastName, ethAddress: profile.ethAddress, phone: profile.phone, location: profile.location, bio: profile.bio, twitter: profile.twitter, facebook: profile.facebook, linkedin: profile.linkedin, youtube: profile.youtube, instagram: profile.instagram, }); } } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } uploadImage(e) { e.preventDefault(); const apikey = "<KEY>"; const options = { accept: "image/*", maxFiles: 1, transformations: { crop: true, }, onFileUploadFinished: (res) => { this.setState({ image_url: res.url, }); }, }; const filestack = client.init(apikey, options); const picker = filestack.picker(options); picker.open(); } onSubmit(e) { e.preventDefault(); const profileData = { firstName: this.state.firstName, lastName: this.state.lastName, phone: this.state.phone, location: this.state.location, ethAddress: this.state.ethAddress, bio: this.state.bio, youtube_url: this.state.youtube_url, facebook_url: this.state.facebook_url, twitter_url: this.state.twitter_url, instagram_url: this.state.instagram_url, }; this.props.updateProfile(profileData, this.props.history); } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } render() { const { errors } = this.state; const { classes } = this.props; return ( <div> <Helmet> <meta charSet="utf-8" /> <title>WeAreMasters - Update Profile</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous" /> </Helmet> <div className="container py-4" style={{ minHeight: "100vh" }}> <div className="row no-gutter"> <div className="col-md-4 m-auto mt-4"> <Link to="/account"> <img width="100" src={logo} alt="WeAreMasters Logo" className="center-image mt-2 mb-4" /> </Link> </div> <div className="col-md-12"> <div className="col-md-6 m-auto"> <h2 className="text-center mb-4"> <strong>UPDATE PROFILE</strong> </h2> <form className="need-validation" onSubmit={this.onSubmit} noValidate > <div className="row"> <div className="col-md-6"> <div className="mb-4"> <label for="firstName" className="form-label"> <strong>First Name</strong> </label> <input type="text" id="firstName" name="firstName" value={this.state.firstName} onChange={this.onChange} className={classnames( "form-control form-control-lg", { "is-invalid": errors.firstName, } )} placeholder="Enter <NAME>" autofocus required /> {errors.firstName && ( <div className="invalid-feedback"> {errors.firstName} </div> )} </div> </div> <div className="col-md-6"> <div className="mb-4"> <label for="lastName" className="form-label"> <strong>Last Name</strong> </label> <input type="text" id="lastName" name="lastName" value={this.state.lastName} onChange={this.onChange} className={classnames( "form-control form-control-lg", { "is-invalid": errors.lastName, } )} placeholder="Enter <NAME>" autofocus required /> {errors.lastName && ( <div className="invalid-feedback"> {errors.lastName} </div> )} </div> </div> <div className="col-md-6"> <div className="mb-4"> <label for="firstName" className="form-label"> <strong>Location</strong> </label> <div class="input-group input-group-lg"> <select id="location" name="location" value={this.state.location} onChange={this.onChange} className="form-select" > <option value={0}>Select Location</option> <option value="Afghanistan">Afghanistan</option> <option value="Åland Islands">Åland Islands</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> <option value="American Samoa"> American Samoa </option> <option value="Andorra">Andorra</option> <option value="Angola">Angola</option> <option value="Anguilla">Anguilla</option> <option value="Antarctica">Antarctica</option> <option value="Antigua and Barbuda"> Antigua and Barbuda </option> <option value="Argentina">Argentina</option> <option value="Armenia">Armenia</option> <option value="Aruba">Aruba</option> <option value="Australia">Australia</option> <option value="Austria">Austria</option> <option value="Azerbaijan">Azerbaijan</option> <option value="Bahamas">Bahamas</option> <option value="Bahrain">Bahrain</option> <option value="Bangladesh">Bangladesh</option> <option value="Barbados">Barbados</option> <option value="Belarus">Belarus</option> <option value="Belgium">Belgium</option> <option value="Belize">Belize</option> <option value="Benin">Benin</option> <option value="Bermuda">Bermuda</option> <option value="Bhutan">Bhutan</option> <option value="Bolivia">Bolivia</option> <option value="Bosnia and Herzegovina"> Bosnia and Herzegovina </option> <option value="Botswana">Botswana</option> <option value="Bouvet Island">Bouvet Island</option> <option value="Brazil">Brazil</option> <option value="British Indian Ocean Territory"> British Indian Ocean Territory </option> <option value="Brunei Darussalam"> Brunei Darussalam </option> <option value="Bulgaria">Bulgaria</option> <option value="Burkina Faso">Burkina Faso</option> <option value="Burundi">Burundi</option> <option value="Cambodia">Cambodia</option> <option value="Cameroon">Cameroon</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="Cayman Islands"> Cayman Islands </option> <option value="Central African Republic"> Central African Republic </option> <option value="Chad">Chad</option> <option value="Chile">Chile</option> <option value="China">China</option> <option value="Christmas Island"> Christmas Island </option> <option value="Cocos (Keeling) Islands"> Cocos (Keeling) Islands </option> <option value="Colombia">Colombia</option> <option value="Comoros">Comoros</option> <option value="Congo">Congo</option> <option value="Congo, The Democratic Republic of The"> Congo, The Democratic Republic of The </option> <option value="Cook Islands">Cook Islands</option> <option value="Costa Rica">Costa Rica</option> <option value="Cote D'ivoire">Cote D'ivoire</option> <option value="Croatia">Croatia</option> <option value="Cuba">Cuba</option> <option value="Cyprus">Cyprus</option> <option value="Czech Republic"> Czech Republic </option> <option value="Denmark">Denmark</option> <option value="Djibouti">Djibouti</option> <option value="Dominica">Dominica</option> <option value="Dominican Republic"> Dominican Republic </option> <option value="Ecuador">Ecuador</option> <option value="Egypt">Egypt</option> <option value="El Salvador">El Salvador</option> <option value="Equatorial Guinea"> Equatorial Guinea </option> <option value="Eritrea">Eritrea</option> <option value="Estonia">Estonia</option> <option value="Ethiopia">Ethiopia</option> <option value="Falkland Islands (Malvinas)"> Falkland Islands (Malvinas) </option> <option value="Faroe Islands">Faroe Islands</option> <option value="Fiji">Fiji</option> <option value="Finland">Finland</option> <option value="France">France</option> <option value="French Guiana">French Guiana</option> <option value="French Polynesia"> French Polynesia </option> <option value="French Southern Territories"> French Southern Territories </option> <option value="Gabon">Gabon</option> <option value="Gambia">Gambia</option> <option value="Georgia">Georgia</option> <option value="Germany">Germany</option> <option value="Ghana">Ghana</option> <option value="Gibraltar">Gibraltar</option> <option value="Greece">Greece</option> <option value="Greenland">Greenland</option> <option value="Grenada">Grenada</option> <option value="Guadeloupe">Guadeloupe</option> <option value="Guam">Guam</option> <option value="Guatemala">Guatemala</option> <option value="Guernsey">Guernsey</option> <option value="Guinea">Guinea</option> <option value="Guinea-bissau">Guinea-bissau</option> <option value="Guyana">Guyana</option> <option value="Haiti">Haiti</option> <option value="Heard Island and Mcdonald Islands"> Heard Island and Mcdonald Islands </option> <option value="Holy See (Vatican City State)"> Holy See (Vatican City State) </option> <option value="Honduras">Honduras</option> <option value="Hong Kong">Hong Kong</option> <option value="Hungary">Hungary</option> <option value="Iceland">Iceland</option> <option value="India">India</option> <option value="Indonesia">Indonesia</option> <option value="Iran, Islamic Republic of"> Iran, Islamic Republic of </option> <option value="Iraq">Iraq</option> <option value="Ireland">Ireland</option> <option value="Isle of Man">Isle of Man</option> <option value="Israel">Israel</option> <option value="Italy">Italy</option> <option value="Jamaica">Jamaica</option> <option value="Japan">Japan</option> <option value="Jersey">Jersey</option> <option value="Jordan">Jordan</option> <option value="Kazakhstan">Kazakhstan</option> <option value="Kenya">Kenya</option> <option value="Kiribati">Kiribati</option> <option value="Korea, Democratic People's Republic of"> Korea, Democratic People's Republic of </option> <option value="Korea, Republic of"> Korea, Republic of </option> <option value="Kuwait">Kuwait</option> <option value="Kyrgyzstan">Kyrgyzstan</option> <option value="Lao People's Democratic Republic"> Lao People's Democratic Republic </option> <option value="Latvia">Latvia</option> <option value="Lebanon">Lebanon</option> <option value="Lesotho">Lesotho</option> <option value="Liberia">Liberia</option> <option value="Libyan Arab Jamahiriya"> Libyan Arab Jamahiriya </option> <option value="Liechtenstein">Liechtenstein</option> <option value="Lithuania">Lithuania</option> <option value="Luxembourg">Luxembourg</option> <option value="Macao">Macao</option> <option value="Macedonia, The Former Yugoslav Republic of"> Macedonia, The Former Yugoslav Republic of </option> <option value="Madagascar">Madagascar</option> <option value="Malawi">Malawi</option> <option value="Malaysia">Malaysia</option> <option value="Maldives">Maldives</option> <option value="Mali">Mali</option> <option value="Malta">Malta</option> <option value="Marshall Islands"> Marshall Islands </option> <option value="Martinique">Martinique</option> <option value="Mauritania">Mauritania</option> <option value="Mauritius">Mauritius</option> <option value="Mayotte">Mayotte</option> <option value="Mexico">Mexico</option> <option value="Micronesia, Federated States of"> Micronesia, Federated States of </option> <option value="Moldova, Republic of"> Moldova, Republic of </option> <option value="Monaco">Monaco</option> <option value="Mongolia">Mongolia</option> <option value="Montenegro">Montenegro</option> <option value="Montserrat">Montserrat</option> <option value="Morocco">Morocco</option> <option value="Mozambique">Mozambique</option> <option value="Myanmar">Myanmar</option> <option value="Namibia">Namibia</option> <option value="Nauru">Nauru</option> <option value="Nepal">Nepal</option> <option value="Netherlands">Netherlands</option> <option value="Netherlands Antilles"> Netherlands Antilles </option> <option value="New Caledonia">New Caledonia</option> <option value="New Zealand">New Zealand</option> <option value="Nicaragua">Nicaragua</option> <option value="Niger">Niger</option> <option value="Nigeria">Nigeria</option> <option value="Niue">Niue</option> <option value="Norfolk Island"> Norfolk Island </option> <option value="Northern Mariana Islands"> Northern Mariana Islands </option> <option value="Norway">Norway</option> <option value="Oman">Oman</option> <option value="Pakistan">Pakistan</option> <option value="Palau">Palau</option> <option value="Palestinian Territory, Occupied"> Palestinian Territory, Occupied </option> <option value="Panama">Panama</option> <option value="Papua New Guinea"> Papua New Guinea </option> <option value="Paraguay">Paraguay</option> <option value="Peru">Peru</option> <option value="Philippines">Philippines</option> <option value="Pitcairn">Pitcairn</option> <option value="Poland">Poland</option> <option value="Portugal">Portugal</option> <option value="Puerto Rico">Puerto Rico</option> <option value="Qatar">Qatar</option> <option value="Reunion">Reunion</option> <option value="Romania">Romania</option> <option value="Russian Federation"> Russian Federation </option> <option value="Rwanda">Rwanda</option> <option value="Saint Helena">Saint Helena</option> <option value="Saint Kitts and Nevis"> Saint Kitts and Nevis </option> <option value="Saint Lucia">Saint Lucia</option> <option value="Saint Pierre and Miquelon"> Saint Pierre and Miquelon </option> <option value="Saint Vincent and The Grenadines"> Saint Vincent and The Grenadines </option> <option value="Samoa">Samoa</option> <option value="San Marino">San Marino</option> <option value="Sao Tome and Principe"> Sao Tome and Principe </option> <option value="Saudi Arabia">Saudi Arabia</option> <option value="Senegal">Senegal</option> <option value="Serbia">Serbia</option> <option value="Seychelles">Seychelles</option> <option value="Sierra Leone">Sierra Leone</option> <option value="Singapore">Singapore</option> <option value="Slovakia">Slovakia</option> <option value="Slovenia">Slovenia</option> <option value="Solomon Islands"> Solomon Islands </option> <option value="Somalia">Somalia</option> <option value="South Africa">South Africa</option> <option value="South Georgia and The South Sandwich Islands"> South Georgia and The South Sandwich Islands </option> <option value="Spain">Spain</option> <option value="Sri Lanka">Sri Lanka</option> <option value="Sudan">Sudan</option> <option value="Suriname">Suriname</option> <option value="Svalbard and Jan Mayen"> Svalbard and Jan Mayen </option> <option value="Swaziland">Swaziland</option> <option value="Sweden">Sweden</option> <option value="Switzerland">Switzerland</option> <option value="Syrian Arab Republic"> Syrian Arab Republic </option> <option value="Taiwan, Province of China"> Taiwan, Province of China </option> <option value="Tajikistan">Tajikistan</option> <option value="Tanzania, United Republic of"> Tanzania, United Republic of </option> <option value="Thailand">Thailand</option> <option value="Timor-leste">Timor-leste</option> <option value="Togo">Togo</option> <option value="Tokelau">Tokelau</option> <option value="Tonga">Tonga</option> <option value="Trinidad and Tobago"> Trinidad and Tobago </option> <option value="Tunisia">Tunisia</option> <option value="Turkey">Turkey</option> <option value="Turkmenistan">Turkmenistan</option> <option value="Turks and Caicos Islands"> Turks and Caicos Islands </option> <option value="Tuvalu">Tuvalu</option> <option value="Uganda">Uganda</option> <option value="Ukraine">Ukraine</option> <option value="United Arab Emirates"> United Arab Emirates </option> <option value="United Kingdom"> United Kingdom </option> <option value="United States">United States</option> <option value="United States Minor Outlying Islands"> United States Minor Outlying Islands </option> <option value="Uruguay">Uruguay</option> <option value="Uzbekistan">Uzbekistan</option> <option value="Vanuatu">Vanuatu</option> <option value="Venezuela">Venezuela</option> <option value="Viet Nam">Viet Nam</option> <option value="Virgin Islands, British"> Virgin Islands, British </option> <option value="Virgin Islands, U.S."> Virgin Islands, U.S. </option> <option value="Wallis and Futuna"> Wallis and Futuna </option> <option value="Western Sahara"> Western Sahara </option> <option value="Yemen">Yemen</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> {errors.location && ( <div className="form-error">{errors.location}</div> )} </div> </div> </div> <div className="col-md-6"> <div className="mb-4"> <label for="lastName" className="form-label"> <strong>Phone</strong> </label> <input type="text" id="phone" name="phone" value={this.state.phone} onChange={this.onChange} className={classnames( "form-control form-control-lg", { "is-invalid": errors.phone, } )} placeholder="Enter phone number" autofocus required /> {errors.phone && ( <div className="invalid-feedback">{errors.phone}</div> )} </div> </div> </div> <div className="mb-4"> <label for="ethAddress" className="form-label"> <strong>ETH Payout Address</strong> </label> <div className="mb-4"> <input type="text" id="ethAddress" name="ethAddress" value={this.state.ethAddress} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.ethAddress, })} placeholder="Enter ETH payout address" autofocus required /> {errors.ethAddress && ( <div className="invalid-feedback"> {errors.ethAddress} </div> )} </div> {errors.ethAddress && ( <div className="invalid-feedback"> {errors.ethAddress} </div> )} </div> <div className="mb-4"> <label for="bio" className="form-label"> <strong>Profile Bio</strong> </label> <textarea rows="5" id="bio" name="bio" value={this.state.bio} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.bio, })} placeholder="Enter full bio for your profile" required ></textarea> {errors.bio && ( <div className="invalid-feedback">{errors.bio}</div> )} </div> <div className="mb-4"> <label for="youtubeURL" className="form-label"> <strong>YouTube URL for Digital Art</strong> </label> <input type="text" id="youtubeURL" name="youtubeURL" value={this.state.youtubeURL} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.youtubeURL, })} placeholder="e.g https://youtu.be/WEA9EB7Q5RY (optional)" autofocus required /> {errors.youtubeURL && ( <div className="invalid-feedback"> {errors.youtubeURL} </div> )} </div> <div className="mb-4"> <label for="facebookURL" className="form-label"> <strong>FaceBook URL for Digital Art</strong> </label> <input type="text" id="facebookURL" name="facebookURL" value={this.state.facebookURL} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.facebookURL, })} placeholder="e.g https://facebook.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.facebookURL && ( <div className="invalid-feedback"> {errors.facebookURL} </div> )} </div> <div className="mb-4"> <label for="twitterURL" className="form-label"> <strong>Twitter URL for Digital Art</strong> </label> <input type="text" id="twitterURL" name="twitterURL" value={this.state.twitterURL} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.twitterURL, })} placeholder="e.g https://twitter.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.twitterURL && ( <div className="invalid-feedback"> {errors.twitterURL} </div> )} </div> <div className="mb-4"> <label for="instagramURL" className="form-label"> <strong>Instagram URL for Digital Art</strong> </label> <input type="text" id="instagramURL" name="instagramURL" value={this.state.instagramURL} onChange={this.onChange} className={classnames("form-control form-control-lg", { "is-invalid": errors.instagramURL, })} placeholder="e.g https://instagram.com/WEA9EB7Q5RY (optional)" autofocus required /> {errors.instagramURL && ( <div className="invalid-feedback"> {errors.instagramURL} </div> )} </div> <div className="d-grid gap-2"> <button className="btn btn-lg btn-primary" type="submit"> <Spinner name="updateProfileLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Processing... </Spinner> <Spinner name="updateProfileNotLoading" show={true}> Proceed to Update Profile </Spinner> </button> </div> </form> <hr /> <div className="row"> <div className="col-md-6"> <div className="d-grid gap-2"> <Link to="/account" className="btn btn-dark my-2"> Back Home </Link> </div> </div> <div className="col-md-6"> <div className="d-grid gap-2"> <Link to="/market" className="btn btn-dark my-2"> Market Place </Link> </div> </div> </div> </div> </div> </div> </div> </div> ); } } UpdateProfile.propTypes = { getCurrentProfile: PropTypes.func.isRequired, updateProfile: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, profile: state.profile, errors: state.errors, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getCurrentProfile, updateProfile, logoutUser, }) )(UpdateProfile); <file_sep>/src/components/cards/Radio.js /* eslint-disable */ function Radio(props) { const { artist, thumbnail } = props.card; return ( <div className="cursor-pointer"> <div className="relative flex h-track lg:h-radio"> <img src={thumbnail} alt="feature" className="rounded-md w-full object-cover" /> <div className="absolute px-4 py-4 w-full h-full flex items-end text-sm text-white font-medium justify-between"></div> </div> <a href="/artist" className="flex flex-col mt-2 text-sm capitalize text-bordyColor dark:text-gray-100" > <p>{artist}</p> </a> </div> ); } export default Radio; <file_sep>/src/pages/Onhover.js import React from "react"; import category from "../assets/img/category.jpg"; const Onhover = () => { return ( <div> <div className="overlay h-28 m-32 border border-elr-green border-opacity-30 rounded-md"> {/* <img src={category} alt="burna" className="overlay h-28 m-32 border border-elr-green border-opacity-30 rounded-md" /> */} <div className="overlay-first-elem bg-elr-white-400 opacity-90 rounded-md text-center transform translate-x-0 translate-y-10"> yes please </div> <div className="overlay-second-elem flex ml-3 md:ml-5 mt-5 mr-1.5"> hey </div> </div> </div> ); }; export default Onhover; <file_sep>/src/pages/NewUploadArt.js import React, { Component } from "react"; import { connect } from "react-redux"; import PropTypes from "prop-types"; import { logoutUser } from "../actions/authActions"; import { getCurrentProfile } from "../actions/profileActions"; import classnames from "classnames"; import { client } from "filestack-react"; import { getETHRate } from "../actions/assetActions"; import { compose } from "redux"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import { Spinner } from "@chevtek/react-spinners"; import { withStyles } from "@material-ui/core"; import Footer from "../components/Footer"; import { uploadArt } from "../actions/assetActions"; import { Link } from "react-router-dom"; import NavigateBeforeIcon from "@material-ui/icons/NavigateBefore"; import exactMath from "exact-math"; import CurrencyFormat from "react-currency-format"; const Validator = require("validator"); const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class NewUploadArt extends Component { constructor(props) { super(props); this.state = { title: "", price: "", image_url: "", animation_url: "", youtube_url: "", facebook_url: "", twitter_url: "", instagram_url: "", description: "", edition: "", errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { window.scrollTo(0, 1); this.props.getCurrentProfile(); this.props.getETHRate(); } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } uploadImage(e) { e.preventDefault(); const apikey = "ADBFWdFLGQ8C3n9tImp8Ez"; const options = { accept: "image/*", maxFiles: 1, transformations: { crop: true, }, onFileUploadFinished: (res) => { this.setState({ image_url: res.url, }); }, }; const filestack = client.init(apikey, options); const picker = filestack.picker(options); picker.open(); } onSubmit(e) { e.preventDefault(); const uploadData = { title: this.state.title, price: this.state.price, image_url: this.state.image_url, animation_url: this.state.animation_url, youtube_url: this.state.youtube_url, facebook_url: this.state.facebook_url, twitter_url: this.state.twitter_url, instagram_url: this.state.instagram_url, description: this.state.description, }; this.props.uploadArt(uploadData, this.props.history); } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } render() { const { errors } = this.state; const { classes } = this.props; const { ethPrice, ethPriceLoading } = this.props.ethRate; const disableMathError = { invalidError: false }; let imageBox; if (!Validator.isEmpty(this.state.image_url)) { imageBox = ( <div className="col-md-6 m-auto"> <img src={this.state.image_url} alt="Digital Art Preview" className="image-preview" /> </div> ); } return ( <div className="bg-black"> <div> <Link to="/account"> <a className="py-2 bg-gray-700 w-full h-10 fixed z-50 bg-opacity-60" alt="#" href="#" > <div className="bg-gray-400 ml-3 bg-gray-600 w-6 h-6 rounded"> <NavigateBeforeIcon style={{ color: "#fff" }} /> </div> </a> </Link> <div> <p className="text-white font-black text-xl ml-12 pt-14"> Upload Item </p> </div> <form onSubmit={this.onSubmit} noValidate className="border border-gray-300 ml-12 mt-7 w-96 p-7 mb-16 rounded" > <div> <p className="text-white font-black text-base">Title Of Item</p> <input type="text" id="title" name="title" value={this.state.title} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-4 text-bordyColor dark:text-gray-100 bg-gray-white dark:bg-bordyColor border-gray-300 dark:border-bordyColor focus:outline-none focus:border focus:border-gray-500", { "is-invalid": errors.title, } )} placeholder="e.g Kaleidoscope Woman" autofocus required /> {errors.title && ( <div className="invalid-feedback">{errors.title}</div> )} </div> <div className="mb-4"> <p className="text-white font-black text-base"> {" "} Price of Item {ethPrice === null || ethPriceLoading ? null : ( <CurrencyFormat value={exactMath.mul(1, ethPrice.amount, disableMathError)} displayType={"text"} thousandSeparator={true} decimalSeperator="." decimalScale={2} fixedDecimalScale={true} renderText={(value) => <span>(1 ETH = &#36;{value})</span>} /> )} </p> <div> <span className="border rounded-l-lg text-xs border-gray-300 bg-gray-300 p-2"> ETH </span> <CurrencyFormat name="price" id="price" thousandSeparator={true} decimalSeperator="." decimalScale={2} fixedDecimalScale={true} value={this.state.price} className={classnames( "w-64 rounded p-3 pl-3 text-xs mt-2 mb-4 text-bordyColor dark:text-gray-100 bg-gray-white dark:bg-bordyColor border-gray-300 dark:border-bordyColor focus:outline-none focus:border focus:border-gray-500", { "is-invalid": errors.price, } )} onValueChange={(values) => { const { value } = values; this.setState({ price: value, }); }} placeholder="e.g 2.75" required /> </div> {errors.price && ( <div style={{ color: "#dc3545", fontSize: "12px", marginTop: "-15px", fontWeight: "400", }} > {errors.price} </div> )} </div> <div className="mb-4"> {!Validator.isEmpty(this.state.image_url) ? ( imageBox ) : ( <button className="p-3 w-full rounded text-xs text-center cursor-pointer text-bordyColor dark:text-gray-100 bg-blue-400 border-gray-300 dark:border-bordyColor" onClick={this.uploadImage.bind(this)} > Click to Upload </button> )} {errors.image_url && ( <div style={{ color: "#dc3545", fontSize: "12px", marginTop: "5px", fontWeight: "400", }} > {errors.image_url} </div> )} </div> <div className="mb-4"> <p className="text-white font-black text-base">Editions</p> <input type="number" value={this.state.animation_url} onChange={this.onChange} className={classnames( "w-full rounded text-xs p-3 mt-2 mb-4 text-bordyColor dark:text-gray-100 bg-gray-white dark:bg-bordyColor border-gray-300 dark:border-bordyColor focus:outline-none focus:border focus:border-gray-500", { "is-invalid": errors.animation_url, } )} placeholder="Item No e.g 1/10 (optional)" required /> {errors.animation_url && ( <div className="invalid-feedback">{errors.animation_url}</div> )} </div> <div className="mb-4"> <p className="text-white font-black text-base"> Description of Digital Art </p> <textarea rows="5" id="description" name="description" value={this.state.description} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-2 mt-2 mb-4 text-bordyColor dark:text-gray-100 bg-gray-white dark:bg-bordyColor border-gray-300 dark:border-bordyColor focus:outline-none focus:border focus:border-gray-500", { "is-invalid": errors.description, } )} placeholder="Enter full description for Digital Art" required ></textarea> {errors.description && ( <div className="invalid-feedback">{errors.description}</div> )} </div> <button className="ml-20 py-6 px-8"> <Link to="/login" onClick={this.onLogoutClick.bind(this)} className="uppercase py-2 px-6 text-sm font-medium rounded text-white bg-appRed" > <Spinner name="uploadLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Processing... </Spinner> <Spinner name="uploadNotLoading" show={true}> Submit </Spinner> </Link> </button> </form> </div> <div></div> <div className=""> <Footer /> </div> </div> ); } } NewUploadArt.propTypes = { getCurrentProfile: PropTypes.func.isRequired, uploadArt: PropTypes.func.isRequired, getETHRate: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, profile: state.profile, ethRate: state.ethRate, errors: state.errors, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getCurrentProfile, uploadArt, logoutUser, getETHRate, }) )(NewUploadArt); <file_sep>/src/App.js import React from "react"; import { Provider } from "react-redux"; import PrivateRoute from "./components/common/PrivateRoute"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import jwt_decode from "jwt-decode"; import Profile from "./pages/Profile"; import Home from "./pages/Home"; import Login from "./pages/Login"; import Signup from "./pages/Signup"; import Account from "./pages/Account"; import UploadArt from "./pages/UploadArt"; import UpdateProfile from "./pages/UpdateProfile"; import Assets from "./pages/Assets"; import Asset from "./pages/Asset"; import store from "./store"; import setAuthToken from "./utils/setAuthToken"; import { setCurrentUser, logoutUser } from "./actions/authActions"; import { clearCurrentProfile } from "./actions/profileActions"; import NewSideBar from "./components/NewSideBar"; import NewUploadArt from "./pages/NewUploadArt"; import ViewAll from "./pages/ViewAll"; import Onhover from "./pages/Onhover"; import NewUpdateProfile from "./pages/NewUpdateProfile"; import Collectible from "./pages/Collectible"; import NextDrop from "./pages/NextDrop"; // Check for token if (localStorage.jwtToken) { // Set auth token header auth setAuthToken(localStorage.jwtToken); // Decode token and get user info and exp const decoded = jwt_decode(localStorage.jwtToken); // Set user and isAuthenticated store.dispatch(setCurrentUser(decoded)); // Check for expired token const currentTime = Date.now() / 1000; if (decoded.exp < currentTime) { // Logout user store.dispatch(logoutUser()); // Clear current Profile store.dispatch(clearCurrentProfile()); // Redirect to login window.location.href = "/login"; } } function App() { return ( <Provider store={store}> <div className="bg-white dark:bg-bordyColor"> <Router> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/side" component={NewSideBar} /> <Route exact path="/up" component={NewUploadArt} /> <Route exact path="/upp" component={NewUpdateProfile} /> <Route exact path="/collectible" component={Collectible} /> <Route exact path="/next" component={NextDrop} /> <Route exact path="/view" component={ViewAll} /> <Route exact path="/hover" component={Onhover} /> <Route exact path="/login" component={Login} /> <Route exact path="/sign-up" component={Signup} /> <Route exact path="/profile" component={Profile} /> <PrivateRoute exact path="/account" component={Account} /> <PrivateRoute exact path="/upload-art" component={UploadArt} /> <PrivateRoute exact path="/assets" component={Assets} /> <PrivateRoute exact path="/asset/:id" component={Asset} /> <PrivateRoute exact path="/update-profile" component={UpdateProfile} /> </Switch> </Router> </div> </Provider> ); } export default App; <file_sep>/src/components/Track.js /* eslint-disable */ function Track(props) { return ( <div className="grid xl:grid-cols-4 lg:grid-cols-3 sm:grid-cols-2 gap-4 mt-8"> {props.cards.map((item) => ( <a href="#"> <div className="flex justify-between text-sm border-t border-gray-200 border-opacity-20 dark:border-sideBar py-4"> <div className="flex space-x-2"> <div className="w-10 h-10"> <img src={item.thumbnail} className="rounded-sm" alt="track" /> </div> <div> <h3 className="capitalize text-bordyColor dark:text-gray-100"> {item.title} </h3> <h3 className="lowercase text-gray-500">{item.artist}</h3> </div> </div> <button className="text-appRed flex content-features focus:outline-none"> <svg className="w-6 h-6" viewBox="0 0 24 24"> <path fill="currentColor" d="M16,12A2,2 0 0,1 18,10A2,2 0 0,1 20,12A2,2 0 0,1 18,14A2,2 0 0,1 16,12M10,12A2,2 0 0,1 12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12M4,12A2,2 0 0,1 6,10A2,2 0 0,1 8,12A2,2 0 0,1 6,14A2,2 0 0,1 4,12Z" /> </svg> </button> </div> </a> ))} </div> ); } export default Track; <file_sep>/src/pages/Assets.js /* eslint-disable */ import React, { Component } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { logoutUser } from "../actions/authActions"; import { getCurrentProfile } from "../actions/profileActions"; import { getAllAssets, getETHRate } from "../actions/assetActions"; import { compose } from "redux"; import exactMath from "exact-math"; import { withStyles } from "@material-ui/core"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import CurrencyFormat from "react-currency-format"; import Moment from "react-moment"; import TableCell from "@material-ui/core/TableCell"; import TableContainer from "@material-ui/core/TableContainer"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import Paper from "@material-ui/core/Paper"; import Backdrop from "@material-ui/core/Backdrop"; import CircularProgress from "@material-ui/core/CircularProgress"; import { Helmet } from "react-helmet"; import logo from "../assets/img/favicon.png"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, table: { minWidth: 650, }, }); class Assets extends Component { constructor(props) { super(props); } componentDidMount() { window.scrollTo(0, 1); this.props.getCurrentProfile(); this.props.getAllAssets(); this.props.getETHRate(); } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } render() { const { classes } = this.props; const { allAssets, assetLoading } = this.props.asset; const { ethPrice, ethPriceLoading } = this.props.ethRate; const disableMathError = { invalidError: false }; let assetsTable; if (allAssets === null || assetLoading) { assetsTable = assetsTable = <div />; } else { if (Object.keys(allAssets).length > 0) { assetsTable = ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Title</TableCell> <TableCell>Price</TableCell> <TableCell>Status</TableCell> <TableCell align="right">Date</TableCell> <TableCell align="right">Action</TableCell> </TableRow> </TableHead> <TableBody> {allAssets.map((asset) => ( <TableRow key={asset._id}> <TableCell component="th" scope="row"> {asset.name} </TableCell> <TableCell> {asset.price} ETH{" "} {ethPrice === null || ethPriceLoading ? null : ( <CurrencyFormat value={exactMath.mul( asset.price, ethPrice.amount, disableMathError )} displayType={"text"} thousandSeparator={true} decimalSeperator="." decimalScale={2} fixedDecimalScale={true} renderText={(value) => <span>(&#36; {value})</span>} /> )} </TableCell> <TableCell>{asset.status}</TableCell> <TableCell align="right"> <Moment format="Do MMM, YYYY">{asset.date}</Moment> </TableCell> <TableCell align="right"> <Link to={`/asset/${asset._id}`} className="btn btn-primary btn-sm" > APPROVE </Link> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); } else { assetsTable = ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Title</TableCell> <TableCell>Price</TableCell> <TableCell>Status</TableCell> <TableCell align="right">Date</TableCell> <TableCell align="right">Action</TableCell> </TableRow> </TableHead> <TableBody> <p className="p-3">All assets will show here...</p> </TableBody> </Table> </TableContainer> ); } } return ( <div> <Helmet> <meta charSet="utf-8" /> <title>WeAreMasters - Approve Digital Art</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous" /> </Helmet> <div className="container py-4" style={{ minHeight: "100vh" }}> <Backdrop className={classes.backdrop} open={!assetLoading ? false : true} > <CircularProgress color="inherit" /> </Backdrop> <div className="row no-gutter"> <div className="col-md-4 m-auto mt-4"> <Link to="/account"> <img width="100" src={logo} alt="WeAreMasters Logo" className="center-image" /> </Link> </div> <div className="col-md-12 pt-4"> <div className="row text-center"> <div className="col-md-4 mb-10 mt-10 px-10"> <div className="d-grid gap-2"> <Link to="/upload" className="btn btn-dark"> <strong style={{ fontWeight: 600 }}>UPLOAD ART</strong> </Link> </div> </div> <div className="col-md-4 mb-10 mt-10 px-10"> <div className="d-grid gap-2"> <Link to="/market" className="btn btn-dark"> <strong style={{ fontWeight: 600 }}>MARKET PLACE</strong> </Link> </div> </div> <div className="col-md-4 mb-10 mt-10 px-10"> <div className="d-grid gap-2"> <Link className="btn btn-dark" onClick={this.onLogoutClick.bind(this)} > <strong style={{ fontWeight: 600 }}>LOG OUT</strong> </Link> </div> </div> </div> <h2 className="text-center mb-4"> <strong style={{ wordSpacing: "5px" }}> DIGITAL ART UPLOADS </strong> </h2> </div> <div className="col-md-12"> <div className="row"> <div className="col-xl-12 col-sm-12 m-auto"> <div className="p-2">{assetsTable}</div> </div> </div> </div> </div> </div> </div> ); } } Assets.propTypes = { getCurrentProfile: PropTypes.func.isRequired, getAllAssets: PropTypes.func.isRequired, getETHRate: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, profile: state.profile, asset: state.asset, ethRate: state.ethRate, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getCurrentProfile, getAllAssets, logoutUser, getETHRate, }) )(Assets); <file_sep>/src/pages/NewUpdateProfile.js import React, { Component } from "react"; import PropTypes from "prop-types"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { logoutUser } from "../actions/authActions"; import { getCurrentProfile, updateProfile } from "../actions/profileActions"; import classnames from "classnames"; import { compose } from "redux"; import { withStyles } from "@material-ui/core"; import { client } from "filestack-react"; import * as AiIcons from "react-icons/ai"; import { Spinner } from "@chevtek/react-spinners"; import isEmpty from "../validation/is-empty"; import Backdrop from "@material-ui/core/Backdrop"; import * as IconName from "react-icons/io"; import CircularProgress from "@material-ui/core/CircularProgress"; import NavigateBeforeIcon from "@material-ui/icons/NavigateBefore"; import hero from "../assets/img/hero.png"; const styles = (theme) => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: "#fff", }, }); class NewUpdateProfile extends Component { constructor(props) { super(props); this.state = { firstName: "", lastName: "", userName: "", ethAddress: "", confirmEthAddress: "", twitterURL: "", errors: {}, }; this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } componentDidMount() { window.scrollTo(0, 1); this.props.getCurrentProfile(); } componentWillReceiveProps(nextProps) { if (nextProps.errors) { this.setState({ errors: nextProps.errors }); } if (nextProps.profile.profile) { const profile = nextProps.profile.profile; // If profile field doesn't exist, make empty string profile.firstName = !isEmpty(profile.firstName) ? profile.firstName : ""; profile.lastName = !isEmpty(profile.lastName) ? profile.lastName : ""; profile.userName = !isEmpty(profile.userName) ? profile.userName : ""; profile.ethAddress = !isEmpty(profile.ethAddress) ? profile.ethAddress : ""; profile.confirmEthAddress = !isEmpty(profile.confirmEthAddress) ? profile.confirmEthAddress : ""; profile.bio = !isEmpty(profile.bio) ? profile.bio : ""; profile.social = !isEmpty(profile.social) ? profile.social : {}; profile.twitter = !isEmpty(profile.social.twitter) ? profile.social.twitter : ""; profile.youtube = !isEmpty(profile.social.youtube) ? profile.social.youtube : ""; // Set component field state this.setState({ firstName: profile.firstName, lastName: profile.lastName, userName: profile.userName, ethAddress: profile.ethAddress, confirmEthAddress: profile.confirmEthAddress, bio: profile.bio, twitter: profile.twitter, youtube: profile.youtube, }); } } onChange(e) { this.setState({ [e.target.name]: e.target.value }); } uploadImage(e) { e.preventDefault(); const apikey = "<KEY>"; const options = { accept: "image/*", maxFiles: 1, transformations: { crop: true, }, onFileUploadFinished: (res) => { this.setState({ image_url: res.url, }); }, }; const filestack = client.init(apikey, options); const picker = filestack.picker(options); picker.open(); } onSubmit(e) { e.preventDefault(); const profileData = { firstName: this.state.firstName, lastName: this.state.lastName, userName: this.state.userName, ethAddress: this.state.ethAddress, confrimEthAddress: this.state.confirmEthAddress, bio: this.state.bio, youtube_url: this.state.youtube_url, twitter_url: this.state.twitter_url, }; this.props.updateProfile(profileData, this.props.history); } onLogoutClick(e) { e.preventDefault(); this.props.logoutUser(); } render() { const { errors } = this.state; const { classes } = this.props; return ( <div className="bg-black text-gray pb-1"> <div> <div className=""> <Link to="/account"> <a className="py-2 bg-gray-700 w-full h-10 fixed z-50 bg-opacity-60" alt="#" href="#" > <div className="bg-gray-400 ml-3 bg-gray-600 w-6 h-6 rounded"> <NavigateBeforeIcon style={{ color: "#fff" }} /> </div> </a> </Link> </div> <div> <p className="text-white font-black text-xl ml-20 pt-6" /> </div> <div className="flex justify-evenly"> <form onSubmit={this.onSubmit} noValidate className="border border-gray-300 mt-7 w-96 p-7 ml-10 bg-gray-300 mb-16 rounded need-validation" > <div className="h-24 w-24 rounded-full bg-gray-400 flex-end mb-7 pt-4 pl-6 flex justify-between"> <button className="focus:outline-none"> <AiIcons.AiOutlineUserAdd size="50px" color="skyblue" /> </button> <div className="ml-10 mt-2 "> <IconName.IoIosAddCircle color="skyblue" size="40px" onMouseOver={({ target }) => (target.style.color = "white")} onMouseOut={({ target }) => (target.style.color = "skyblue") } /> </div> </div> <div className="flex justify-between"> <div className="mb-1"> <div><NAME></div> <input type="text" id="firstName" name="firstName" value={this.state.firstName} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.firstName, } )} placeholder="Enter first name" autofocus required /> {errors.firstName && ( <div className="invalid-feedback">{errors.firstName}</div> )} </div> <div className="mb-1"> <div>Last Name</div> <input type="text" id="lastName" name="lastName" value={this.state.lastName} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.lastName, } )} placeholder="Enter last name" autofocus required /> {errors.lastName && ( <div className="invalid-feedback">{errors.lastName}</div> )} </div> </div> <div className="flex justify-between space-x-1"> <div className="mb-1"> <div>Username</div> <input type="text" id="userName" name="userName" value={this.state.userName} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.userName, } )} placeholder="Enter first Username" autofocus required /> {errors.firstName && ( <div className="invalid-feedback">{errors.userName}</div> )} </div> <div className="mb-1"> <div>Twitter Url</div> <input type="text" id="twitterUrl" name="twitterUrl" value={this.state.twitterUrl} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.twitterUrl, } )} placeholder="e.g https://twitterUrl.be/WEA9EB7Q5RY (optional)" autofocus required /> {errors.twitterUrl && ( <div className="invalid-feedback">{errors.ltwitterUrl}</div> )} </div> </div> <div className="mb-1"> <label for="ethAddress" className="form-label"> <strong>ETH Payout Address</strong> </label> <div className="mb-4"> <input type="text" id="ethAddress" name="ethAddress" value={this.state.ethAddress} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.ethAddress, } )} placeholder="Enter ETH payout address" autofocus required /> {errors.ethAddress && ( <div className="invalid-feedback">{errors.ethAddress}</div> )} </div> {errors.ethAddress && ( <div className="invalid-feedback">{errors.ethAddress}</div> )} </div> <div className="mb-1"> <label for="bio" className="form-label"> <strong>Profile Bio</strong> </label> <textarea rows="5" id="bio" name="bio" value={this.state.bio} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.bio, } )} placeholder="Enter full bio for your profile" required ></textarea> {errors.bio && ( <div className="invalid-feedback">{errors.bio}</div> )} </div> <div className="mb-1"> <label for="youtubeURL" className="form-label"> <strong>Website Url</strong> </label> <input type="text" id="youtubeURL" name="youtubeURL" value={this.state.youtubeURL} onChange={this.onChange} className={classnames( "w-full text-xs rounded p-3 mt-2 mb-1 text-black dark:text-black bg-gray-white dark:bg-gray-300 border border-black dark:border-black focus:border focus:border-black", { "is-invalid": errors.youtubeURL, } )} placeholder="e.g https://youtu.be/WEA9EB7Q5RY (optional)" autofocus required /> {errors.youtubeURL && ( <div className="invalid-feedback">{errors.youtubeURL}</div> )} </div> <button className="ml-16 py-6 px-8"> <Link to="/login" onClick={this.onLogoutClick.bind(this)} className="uppercase py-2 px-6 text-sm font-medium rounded text-white bg-blue-400" > <Spinner name="uploadLoading"> <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> Processing... </Spinner> <Spinner name="uploadNotLoading" show={true}> Update </Spinner> </Link> </button> </form> <div className="self-center ml-40"> <img src={hero} alt="hero" className="h-1/2 mt-10 rounded w-1/2" /> <h6 className="text-white font-black text-2xl ml-40 mt-2"> Hey Dodo </h6> <h6 className="text-white font-black text-xl ml-28 text-appRed"> Just Add Details Dodo </h6> </div> </div> </div> </div> ); } } NewUpdateProfile.propTypes = { getCurrentProfile: PropTypes.func.isRequired, updateProfile: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, logoutUser: PropTypes.func.isRequired, errors: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, profile: state.profile, errors: state.errors, }); export default compose( withStyles(styles, { withTheme: true }), connect(mapStateToProps, { getCurrentProfile, updateProfile, logoutUser, }) )(NewUpdateProfile); <file_sep>/src/components/NewSideBarData.js import React from "react"; import * as AiIcons from "react-icons/ai"; export const NewSideBarData = [ { title: "Market Place", path: "/", icon: <AiIcons.AiFillQqSquare color="pink"/>, cName: "nav-text", }, { title: "WAMLabs", path: "/", icon: <AiIcons.AiOutlineGitlab color="skyblue"/>, cName: "nav-text", }, ];<file_sep>/src/reducers/index.js import { combineReducers } from "redux"; import authReducer from "./authReducer"; import errorReducer from "./errorReducer"; import profileReducer from "./profileReducer"; import assetReducer from "./assetReducer"; import ethRateReducer from "./ethRateReducer"; export default combineReducers({ auth: authReducer, errors: errorReducer, profile: profileReducer, asset: assetReducer, ethRate: ethRateReducer, }); <file_sep>/src/components/Footer.js import { TiSocialInstagram } from "react-icons/ti"; import { TiSocialFacebook } from "react-icons/ti"; import { TiSocialTwitter } from "react-icons/ti"; import { IconContext } from "react-icons"; import newlogo from "../assets/img/newlogo.png"; /* eslint-disable */ function Footer() { return ( <footer className="bg-footer text-white px-20"> <IconContext.Provider value={{ size: "25px" }}> <div className="flex h-28"> <img src={newlogo} className="relative top-10" alt="logo" /> <div className="border-l h-44 border-gray-400 border-opacity-40 mt-4 ml-28" /> <div className="w-80 mx-6"> <p className="text-gray-400 text-sm mt-20"> Digital marketplace for crypto collectibles and non-fungible tokens (NFTs). Buy, sell, and discover exclusive digital assets. </p> </div> </div> <div className="-mt-8"> <div className="flex flex-row-reverse"> <TiSocialInstagram /> <TiSocialFacebook /> <TiSocialTwitter /> </div> <div className="mt-2 text-gray-400 text-sm flex flex-row-reverse"> <EMAIL> </div> </div> <div className="mt-16 pt-4 border-b border-gray-400 border-opacity-20" /> <div className="text-gray-400 mt-4 flex justify-between"> <p className="text-gray-400 text-sm mt-2"> Copyright © 2021 <a href="https://www.apple.com/uk/" target="_blank" rel="noopener"> WEAREMASTERS.IO </a> All Rights Reserved. </p> </div> </IconContext.Provider> </footer> ); } export default Footer;
c288c642d0bcf01ea5e87459754ad6b205b083a6
[ "JavaScript" ]
28
JavaScript
bigbrain25/wearemasters
5fbfc024ce691807a033df2f2c89c6fd64362133
ddf13ca2cf88fb23932829247b299013cd954462
refs/heads/main
<repo_name>Sougata024/Stone-Paper-Sizer-Game<file_sep>/README.py # Stone-Paper-Sizer-Game <file_sep>/Game/Stone Paper Game.py import random r=random.randint(1,4) a=r if(a==1): a='stone' elif(a==2): a='paper' else: a='sizer' i=input("Enter Your Choice Here:") print("Your Choice is:"+i) print("Computer Choice:"+a) if(a=='stone' and i=='stone'): print("Tie") elif(a=='stone' and i=='paper'): print("You Won !") elif(a=='stone' and i=='sizer'): print("Computer Won !") elif(a=='paper' and i=='stone'): print("Computer Won!") elif(a=='paper' and i=='paper'): print("Tie") elif(a=='paper' and i=='sizer'): print("You Won !") elif(a=='sizer' and i=='stone'): print("You Won!") elif(a=='sizer' and i=='paper'): print("Computer Won !") elif(a=='sizer' and i=='sizer'): print("Tie") else: print("Please Enter a Valid Input here :)............")
a26a3567c1f7b02f8e4b8441b34489c3fd128727
[ "Python" ]
2
Python
Sougata024/Stone-Paper-Sizer-Game
85f5fd5013519554fe567a1ea046b1ed16fadf45
ff70d5fbddaad760dc7c464191927fdcea79642e
refs/heads/master
<file_sep># nemo * nemo and nemo2 are identical applications running on different ports * both use spring session + redis so you must have redis running locally; they need nemo-account for authentication * $ redis-server /usr/local/etc/redis.conf * nemo-account is the authentication server using oauth2; see user credential in application.yml * nemo-resource is resource (REST end points) server; it needs nemo-account for authentication * see application.yml in each app for configuration settings including server port * In Eclipse, make sure you do Maven -> Update Project after getting the code * If you'd like to disable Redis, comment out @EnableRedisHttpSession in nemo or nemo2 projects, and remove redis maven dependency in projects's pom.xml. Two ideas explored in this Poc * Load balance between nemo and nemo2. Spring session + redis should allow you to shudown one application and update it withou user loosing session * OAuth2 provides single sign-on as well as API consumption using bearer token <file_sep>package com.nemo.resource; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @EnableResourceServer public class NemoResourceApplication { @RequestMapping("/api/version") public Map<String,Object> home() { Map<String,Object> model = new HashMap<String,Object>(); model.put("version", "v0.1"); model.put("time", new SimpleDateFormat().format(new Date())); model.put("message", "Hello, this data comes from resource server"); return model; } public static void main(String[] args) { SpringApplication.run(NemoResourceApplication.class, args); } } <file_sep>package com.nemo.accounts; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @EnableResourceServer // by default secures everything in an authorization server except the "/oauth/*" endpoints public class NemoAccountsApplication { @RequestMapping({"/user", "/me"}) public Principal user(Principal user) { return user; } @Configuration @Order(-20) protected static class LoginConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .formLogin() .loginPage("/login") .permitAll() .and() .requestMatchers() .antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access") .and() .authorizeRequests() .anyRequest() .authenticated(); // @formatter:on } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.parentAuthenticationManager(authenticationManager); } } @Configuration @EnableAuthorizationServer protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off clients.inMemory() .withClient("acme") .authorizedGrantTypes("authorization_code","refresh_token","password", "client_credentials") .scopes("nemo") .secret("acmesecret") .autoApprove("nemo") .and() .withClient("cmp") .authorizedGrantTypes("authorization_code","refresh_token","password") .scopes("cmp") .secret("cmpsecret") .autoApprove("cmp") // .redirectUris("http://platform.ias.dev.com:8080/cmp") .and() .withClient("client-with-registered-redirect") .authorizedGrantTypes("authorization_code") .authorities("ROLE_CLIENT") .scopes("read", "trust") .resourceIds("api_v1") .redirectUris("http://anywhere?key=value") .secret("secret123") .and() .withClient("my-client-with-secret") .authorizedGrantTypes("client_credentials", "password") .authorities("ROLE_CLIENT") .scopes("read") .resourceIds("api_v2") .secret("secret"); // @formatter:on } } public static void main(String[] args) { SpringApplication.run(NemoAccountsApplication.class, args); } }
a0989a8e9663228801ad76c85195e674792ec35c
[ "Markdown", "Java" ]
3
Markdown
bwang-ias/nemo
f52cfd34b761f00e6c734528223b155cc3fbbdc7
10c766478ee834ad94d9a8ecc3c9f4b64e14243a
refs/heads/main
<file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'VaccineCalendarCalculation.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(647, 590) self.calendarWidget_current = QtWidgets.QCalendarWidget(Dialog) self.calendarWidget_current.setGeometry(QtCore.QRect(110, 70, 431, 183)) self.calendarWidget_current.setObjectName("calendarWidget_current") self.calendarWidget_future = QtWidgets.QCalendarWidget(Dialog) self.calendarWidget_future.setGeometry(QtCore.QRect(110, 290, 421, 183)) self.calendarWidget_future.setObjectName("calendarWidget_future") self.label_CurrentCal = QtWidgets.QLabel(Dialog) self.label_CurrentCal.setGeometry(QtCore.QRect(280, 50, 101, 16)) font = QtGui.QFont() font.setFamily("Gill Sans MT") font.setPointSize(11) font.setBold(True) font.setWeight(75) self.label_CurrentCal.setFont(font) self.label_CurrentCal.setObjectName("label_CurrentCal") self.label_FutureCal = QtWidgets.QLabel(Dialog) self.label_FutureCal.setGeometry(QtCore.QRect(190, 260, 271, 21)) font = QtGui.QFont() font.setFamily("Gill Sans MT") font.setPointSize(11) font.setBold(True) font.setWeight(75) self.label_FutureCal.setFont(font) self.label_FutureCal.setObjectName("label_FutureCal") self.label_NumberOfDays = QtWidgets.QLabel(Dialog) self.label_NumberOfDays.setGeometry(QtCore.QRect(70, 530, 511, 21)) font = QtGui.QFont() font.setFamily("Gill Sans MT") font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label_NumberOfDays.setFont(font) self.label_NumberOfDays.setText("") self.label_NumberOfDays.setObjectName("label_NumberOfDays") self.pushButtonCalculate = QtWidgets.QPushButton(Dialog) self.pushButtonCalculate.setGeometry(QtCore.QRect(250, 490, 141, 23)) self.pushButtonCalculate.setObjectName("pushButtonCalculate") self.label_VaccineCalc = QtWidgets.QLabel(Dialog) self.label_VaccineCalc.setGeometry(QtCore.QRect(90, 10, 481, 31)) font = QtGui.QFont() font.setFamily("Engravers MT") font.setPointSize(12) font.setBold(True) font.setUnderline(True) font.setWeight(75) self.label_VaccineCalc.setFont(font) self.label_VaccineCalc.setTextFormat(QtCore.Qt.RichText) self.label_VaccineCalc.setObjectName("label_VaccineCalc") self.graphicsView = QtWidgets.QGraphicsView(Dialog) self.graphicsView.setGeometry(QtCore.QRect(25, 11, 601, 551)) self.graphicsView.setObjectName("graphicsView") self.graphicsView.raise_() self.calendarWidget_current.raise_() self.calendarWidget_future.raise_() self.label_CurrentCal.raise_() self.label_FutureCal.raise_() self.label_NumberOfDays.raise_() self.pushButtonCalculate.raise_() self.label_VaccineCalc.raise_() self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.label_CurrentCal.setText(_translate("Dialog", "Today\'s date is:")) self.label_FutureCal.setText(_translate("Dialog", "Date on which to receive vaccination :")) self.pushButtonCalculate.setText(_translate("Dialog", "Calculate")) self.label_VaccineCalc.setText(_translate("Dialog", "<html><head/><body><p align=\"center\"><span style=\" font-size:14pt; font-weight:600; color:#eb1506;\">VACCINATION date CALCULATION</span></p></body></html>"))
7c911545e5b2766721b959224a07591453e1d894
[ "Python" ]
1
Python
PreshConqueror/Vaccine-Calendar
d387f2c38bb5a021866e3be1cec6ddb6f6908ed7
0d11922b29e0f94e466a0af44513ac1a62e671b8
refs/heads/master
<repo_name>mall0c/TileEngine<file_sep>/include/gamelib/core/res/EntityConfigResource.hpp #ifndef GAMELIB_ENTITYCONFIGRESOURCE_HPP #define GAMELIB_ENTITYCONFIGRESOURCE_HPP #include "Resource.hpp" /* * Provides an alternative loader for JsonResource that automatically registers * it at EntityFactory. */ namespace gamelib { class ResourceManager; void registerEntityConfigLoader(ResourceManager& resmgr); BaseResourceHandle entityConfigLoader(const std::string& fname, ResourceManager* resmgr); } #endif <file_sep>/src/gamelib/core/res/EntityConfigResource.cpp #include "gamelib/core/res/EntityConfigResource.hpp" #include "gamelib/core/res/ResourceManager.hpp" #include "gamelib/core/ecs/EntityFactory.hpp" #include "gamelib/json/json-utils.hpp" #include "gamelib/core/res/JsonResource.hpp" namespace gamelib { void registerEntityConfigLoader(ResourceManager& resmgr) { for (auto& i : { "ent", "entity" }) resmgr.registerFileType(i, entityConfigLoader); } BaseResourceHandle entityConfigLoader(const std::string& fname, ResourceManager* resmgr) { auto res = jsonLoader(fname, resmgr).as<JsonResource>(); if (res->isMember("base")) { // loadOnce because it will be modified auto baseres = resmgr->loadOnce((*res)["base"].asString()).as<JsonResource>(); mergeJson(*res, &*baseres); res = baseres; } if (res->isMember("children")) { LOG_ERROR("Can't define children in entity configs -> removing"); res->removeMember("children"); } auto factory = getSubsystem<EntityFactory>(); if (factory) factory->add(*res); return res; } } <file_sep>/include/gamelib/core/input/InputSystem.hpp #ifndef GAMELIB_INPUT_SYSTEM_HPP #define GAMELIB_INPUT_SYSTEM_HPP #include <SFML/Graphics.hpp> #include "math/geometry/Vector.hpp" #include "gamelib/core/Subsystem.hpp" namespace gamelib { class InputSystem : public Subsystem<InputSystem> { public: ASSIGN_NAMETAG("InputSystem"); enum ButtonState { Pressed, Released, Down, None }; struct MouseData { math::Point2i desktop; math::Point2i win; math::Point2f world; int wheel; bool moved; }; public: InputSystem(); InputSystem(const sf::RenderWindow& win); auto setWindow(const sf::RenderWindow& win) -> void; auto beginFrame() -> void; auto process(const sf::Event& ev) -> void; auto markConsumed(bool keyboard, bool mouse) -> void; auto isKeyboardConsumed() const -> bool; auto isMouseConsumed() const -> bool; auto isKeyPressed(sf::Keyboard::Key key) const -> bool; auto isKeyReleased(sf::Keyboard::Key key) const -> bool; auto isKeyDown(sf::Keyboard::Key key) const -> bool; auto isMousePressed(sf::Mouse::Button btn) const -> bool; auto isMouseReleased(sf::Mouse::Button btn) const -> bool; auto isMouseDown(sf::Mouse::Button btn) const -> bool; auto isKey(sf::Keyboard::Key key, ButtonState state) const -> bool; auto isMouse(sf::Mouse::Button btn, ButtonState state) const -> bool; auto getKeyState(sf::Keyboard::Key key) const -> ButtonState; auto getMouseState(sf::Mouse::Button btn) const -> ButtonState; auto getMouse() const -> const MouseData&; private: auto _check(bool keyboard, bool mouse) const -> bool; private: struct StateStruct { bool keyboard; ButtonState state; union { sf::Mouse::Button btn; sf::Keyboard::Key key; }; }; private: MouseData _mouse; const sf::RenderWindow* _window; bool _consumedKeyboard; bool _consumedMouse; std::vector<StateStruct> _states; }; } #endif <file_sep>/src/gamelib/core/input/InputSystem.cpp #include "gamelib/core/input/InputSystem.hpp" #include "gamelib/utils/conversions.hpp" #include "imgui.h" namespace gamelib { InputSystem::InputSystem() : _window(nullptr) { } InputSystem::InputSystem(const sf::RenderWindow& win) : _window(&win) { } void InputSystem::setWindow(const sf::RenderWindow& win) { _window = &win; } void InputSystem::beginFrame() { _states.clear(); _mouse.wheel = 0; _mouse.moved = false; _mouse.world = convert(_window->mapPixelToCoords(sf::Mouse::getPosition(*_window))).asPoint(); _consumedMouse = _consumedKeyboard = false; } void InputSystem::process(const sf::Event& ev) { if (ev.type == sf::Event::KeyPressed || ev.type == sf::Event::KeyReleased || ev.type == sf::Event::MouseButtonPressed || ev.type == sf::Event::MouseButtonReleased) { _states.emplace_back(); auto& state = _states.back(); switch (ev.type) { case sf::Event::KeyPressed: state.keyboard = true; state.key = ev.key.code; state.state = Pressed; break; case sf::Event::KeyReleased: state.keyboard = true; state.key = ev.key.code; state.state = Released; break; case sf::Event::MouseButtonPressed: state.keyboard = false; state.btn = ev.mouseButton.button; state.state = Pressed; break; case sf::Event::MouseButtonReleased: state.keyboard = false; state.btn = ev.mouseButton.button; state.state = Released; break; default: break; // removes switch warning } } else { if (ev.type == sf::Event::MouseMoved) { auto m = sf::Mouse::getPosition(*_window); _mouse.desktop = convert(sf::Mouse::getPosition()).asPoint(); _mouse.win = convert(m).asPoint(); _mouse.moved = true; } else if (ev.type == sf::Event::MouseWheelMoved) _mouse.wheel = ev.mouseWheel.delta; } } void InputSystem::markConsumed(bool keyboard, bool mouse) { if (keyboard) _consumedKeyboard = true; if (mouse) _consumedMouse = true; } bool InputSystem::isKeyboardConsumed() const { return _consumedKeyboard || ImGui::GetIO().WantCaptureKeyboard; } bool InputSystem::isMouseConsumed() const { return _consumedMouse || ImGui::GetIO().WantCaptureMouse; } bool InputSystem::isKeyPressed(sf::Keyboard::Key key) const { return isKey(key, Pressed); } bool InputSystem::isKeyReleased(sf::Keyboard::Key key) const { return isKey(key, Released); } bool InputSystem::isKeyDown(sf::Keyboard::Key key) const { return isKey(key, Down); } bool InputSystem::isMousePressed(sf::Mouse::Button btn) const { return isMouse(btn, Pressed); } bool InputSystem::isMouseReleased(sf::Mouse::Button btn) const { return isMouse(btn, Released); } bool InputSystem::isMouseDown(sf::Mouse::Button btn) const { return isMouse(btn, Down); } bool InputSystem::isKey(sf::Keyboard::Key key, ButtonState state) const { return getKeyState(key) == state; } bool InputSystem::isMouse(sf::Mouse::Button btn, ButtonState state) const { return getMouseState(btn) == state; } InputSystem::ButtonState InputSystem::getKeyState(sf::Keyboard::Key key) const { if (!_check(true, false)) return None; for (auto& i : _states) if (i.keyboard && i.key == key) return i.state; return sf::Keyboard::isKeyPressed(key) ? Down : None; } InputSystem::ButtonState InputSystem::getMouseState(sf::Mouse::Button btn) const { if (!_check(false, true)) return None; for (auto& i : _states) if (!i.keyboard && i.btn == btn) return i.state; return sf::Mouse::isButtonPressed(btn) ? Down : None; } const InputSystem::MouseData& InputSystem::getMouse() const { return _mouse; } bool InputSystem::_check(bool keyboard, bool mouse) const { if ((keyboard && isKeyboardConsumed()) || (mouse && isMouseConsumed())) return false; return _window->hasFocus(); } }
a8c5ef17bf1ed3108d110e80fc7b33669858b58c
[ "C++" ]
4
C++
mall0c/TileEngine
174d9b0fe249e78f7ab599b43e061b1b6b2ddf8b
91c42be86b0827235f8ca5feb09cacdbf9a9c741
refs/heads/master
<repo_name>Exost/workflow<file_sep>/app/components/App.js import React, { Component } from 'react' import { connect } from 'react-redux' class App extends Component { handleClick() { const { dispatch } = this.props dispatch({ type: 'INCREMENT' }) } render() { const { counter } = this.props return ( <div> Counter is {counter} <button onClick={::this.handleClick}>Click</button> </div> ) } } export default connect( state => ({ counter: state.counter }) )(App)
83ec1403e5e28b9ec2951134f72a04b04f712e75
[ "JavaScript" ]
1
JavaScript
Exost/workflow
2728af001d5d86938f7b6813fa72c5d999811596
34c4a889c5ebd1792883691b1bf69816820910fe
refs/heads/master
<file_sep>#!/usr/bin/env python3 """ run.py ====== Script for executable module. Compute a hash value for the given DIMACS file. * Ignores comments 'c' and '%' lines * Order of clauses matters * Order of literals matters A more formal specification is provided at `cnfhash project homepage <http://lukas-prokop.at/proj/cnfhash/>`_. (C) <NAME>, 2016, Public Domain """ import gzip import os.path import argparse import datetime import multiprocessing from . import hashing def read_chunks(fd, chunk_size=None): """Read chunks from a file descriptor""" if chunk_size is None: import resource chunk_size = resource.getpagesize() while True: data = fd.read(chunk_size) if not data: break yield data def run(arg): args, dimacsfile = arg if dimacsfile.endswith('.gz'): opener = gzip.open else: opener = open with opener(dimacsfile, 'rb') as fd: ignore_lines = b'c' for prefix in (args.ignore or []): ignore_lines += prefix.encode('ascii') try: gen = read_chunks(fd) hashvalue = hashing.hash_dimacs(gen, ignore_lines=ignore_lines) except hashing.DimacsSyntaxError as e: raise hashing.DimacsSyntaxError("Error while processing {}".format(dimacsfile)) filename = os.path.basename(dimacsfile) print('{:<45} {}'.format(hashvalue, dimacsfile if args.fullpath else filename)) def main(): parser = argparse.ArgumentParser(description='CNF hashing') parser.add_argument('dimacsfiles', metavar='dimacsfiles', nargs='+', help='filepath of DIMACS file') parser.add_argument('--ignore', action='append', help='a prefix for lines that shall be ignored (like "c")') parser.add_argument('-f', '--fullpath', action='store_true', help='the hash value will be followed by the filepath, not filename') args = parser.parse_args() print('cnf-hash-py 2.1.2 {} {}'.format(datetime.datetime.utcnow().isoformat(), os.getcwd())) with multiprocessing.Pool(multiprocessing.cpu_count()) as pool: pool.map(run, zip([args] * len(args.dimacsfiles), args.dimacsfiles)) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python3 """ cnfhash.hashing --------------- Integer hashing library for cnfhash. (C) <NAME>, 2015, Public Domain """ import os import string import hashlib import functools LITERAL_DELIM = b' ' CLAUSE_DELIM = b'0\n' ENCODING = 'ascii' def hash_cnf(ints: [int], check_header=True): """Hash a given CNF defined as sequence of integers. `ints` is a sequence of integers: (1) the first 2 integers are expected to be nbvars and nbclauses (2) the following integers are considered literals where 0 terminates a clause Hence, the following file:: p cnf 3 2 1 -3 0 -1 2 0 will be hashed correctly by calling:: hash_cnf([3, 2, 1, -3, 0, -1, 2, 0]) If `check_header` is False, all checks related to nbvars and nbclauses will be skipped. """ sha1 = hashlib.sha1() clause_ended = False nbclauses = None clauses = 0 for i, lit in enumerate(ints): if i == 0: nbvars = lit clause_ended = False if nbvars <= 0: tmpl = "nbvars must be non-negative, is {}".format(lit) raise ValueError(tmpl) elif i == 1: nbclauses = lit clause_ended = False if nbclauses <= 0: tmpl = "nbclauses must be non-negative, is {}".format(lit) raise ValueError(tmpl) elif lit == 0: if clause_ended: continue # multiple zeros truncated to a single one clauses += 1 sha1.update(CLAUSE_DELIM) clause_ended = True else: clause_ended = False if check_header and not (-nbvars <= lit <= nbvars): tmpl = "Variable {} outside range ({})--({})".format(lit, -nbvars, nbvars) raise ValueError(tmpl) sha1.update(str(lit).encode(ENCODING)) sha1.update(LITERAL_DELIM) if not clause_ended: sha1.update(CLAUSE_DELIM) clauses += 1 if nbclauses is None: errmsg = "Premature end, CNF must at least contain header values" raise ValueError(errmsg) if not clause_ended: raise ValueError("CNF must be terminated by zero") if check_header and nbclauses != clauses: tmpl = "Invalid number of clauses, expected {}, got {} clauses" raise ValueError(tmpl.format(nbclauses, clauses)) return 'cnf2$' + sha1.hexdigest() def hash_decorator(f): """Decorator wrapping `hash_cnf`""" @functools.wraps(f) def inner(*args, **kwargs): return hash_cnf(f(*args, **kwargs)) return inner class DimacsSyntaxError(Exception): """An exception representing a syntax error in DIMACS""" pass @hash_decorator def hash_dimacs(dimacs_bytes, ignore_lines=b'c%'): """Given a DIMACS file as sequence of bytes, return the corresponding cnfhash. `dimacs_bytes` A sequence of byte specifying content in DIMACS format. `ignore_lines` A sequence of characters. If a line starts with this character, the line is ignored. Example:: ignore_lines=b'c' will ignore all lines like:: c this is a comment """ # '%' is included because ... there are strange CNF files out there skip_line = False got_newline = False got_line_whitespace = False start, end = 0, 0 mode = 0 lineno = 1 intcache = "" WS = set(string.whitespace.encode(ENCODING)) LINE_WS = set(string.whitespace.replace('\n', '').encode(ENCODING)) DIGIT = set(string.digits.encode(ENCODING)) HYPHEN = ord('-') NEWLINE = ord('\n') KEYWORD = b'pcnf' def unexp_byte(given, expected): errmsg = "Unexpected byte {} found at line {}, expected {}" return DimacsSyntaxError(errmsg.format(bytes([given]), lineno, expected)) # I know this is a rdiciulously long state machine. # However, a consume-parser design was terribly slow while True: try: block = next(dimacs_bytes) except StopIteration: break for i in range(len(block)): if block[i] == NEWLINE: lineno += 1 if skip_line: if block[i] == NEWLINE: skip_line = False got_newline = True continue if block[i] in LINE_WS: got_line_whitespace = True elif block[i] == NEWLINE: got_newline = True else: char = block[i] if mode == 0: if char == ord(b'p'): mode = 1 elif char in set(ignore_lines): skip_line = True else: raise unexp_byte(char, "keyword 'p'") elif mode == 1: if not got_line_whitespace: raise unexp_byte(char, "whitespace") elif char == ord(b'c'): mode = 2 else: raise unexp_byte(char, "keyword 'cnf'") elif mode == 2: if not got_line_whitespace and char == ord(b'n'): mode = 3 else: raise unexp_byte(char, "keyword 'cnf'") elif mode == 3: if not got_line_whitespace and char == ord(b'f'): mode = 4 else: raise unexp_byte(char, "keyword 'cnf'") elif mode == 4: if got_line_whitespace and char in DIGIT: intcache += chr(char) mode = 5 else: raise unexp_byte(char, "non-negative integer") elif mode == 5: if not got_line_whitespace and char in DIGIT: intcache += chr(char) elif got_line_whitespace and char in DIGIT: yield int(intcache) intcache = chr(char) mode = 6 else: raise unexp_byte(char, "non-negative integer") elif mode == 6: if got_line_whitespace or got_newline: yield int(intcache) if char in DIGIT or char == HYPHEN: intcache = chr(char) else: intcache = '' if got_newline and char in set(ignore_lines): skip_line = True mode = 7 elif not got_line_whitespace and char in DIGIT: intcache += chr(char) else: raise unexp_byte(char, "non-negative integer") elif mode == 7: if (got_line_whitespace or got_newline) and intcache: yield int(intcache) intcache = '' if got_newline and char in set(ignore_lines): skip_line = True elif char in DIGIT or char == HYPHEN: intcache += chr(char) else: raise unexp_byte(char, "digit or hyphen") got_line_whitespace = False got_newline = False if intcache: yield int(intcache) <file_sep>from .run import main main() <file_sep>#!/usr/bin/env python3 """ cnf-hash -------- A library to hash CNF/DIMACS files. (C) <NAME>, 2016, Public Domain """ from . import hashing hash_cnf = hashing.hash_cnf hash_dimacs = hashing.hash_dimacs __author__ = '<NAME>' __version_info__ = ('1', '0', '0') __version__ = '.'.join(__version_info__) __license__ = 'Public Domain' __docformat__ = 'reStructuredText en' <file_sep>#!/usr/bin/env python3 """ cnfhash.test ------------ Testsuite for the python3 implementation of CNF hashing. Provide the folder to the testsuite either as environment variable TESTSUITE, as second command line parameter or 'testsuite' is taken. 'testsuite' is a folder with CNF files with their hash value in their name like `cnf-hash-test <https://github.com/prokls/cnf-hash-tests>`_. (C) <NAME>, 2016, Public Domain """ import sys import os.path import unittest import cnfhash class CnfHashingTestsuite(unittest.TestCase): def test_testsuite(self): testsuite = sys.argv[1] if len(sys.argv) > 1 else 'testsuite' testsuite = dict(os.environ).get('TESTSUITE', testsuite) for filename in os.listdir(testsuite): if not filename.endswith('.cnf'): continue if os.path.isdir(os.path.join(testsuite, filename)): continue filepath = os.path.join(testsuite, filename) hashvalue = filename.split('_')[0] with open(filepath, 'rb') as fd: try: comp_hashvalue = cnfhash.hash_dimacs(fd) assert comp_hashvalue[0:5] == 'cnf2$' except Exception as e: print('Failure while processing testcase {}'.format(filepath), file=sys.stderr) raise e self.assertEqual(hashvalue, comp_hashvalue[5:], filename[len(hashvalue) + 1:]) if __name__ == '__main__': unittest.main() <file_sep>cnf-hash-py =========== :author: <NAME> :date: August 2015, May 2016 :version: 2.1.2 :license: CC-0 A python3 implementation to hash DIMACS CNF files. See `the technical report <http://lukas-prokop.at/proj/megosat/downloads/cnf-hash.pdf>`_ for more details. This implementation was pushed to `Python Package Index PyPI <https://pypi.python.org/pypi/cnfhash>`_. How to use ---------- To install use pip3:: pip3 install cnfhash Then you can use the following API in python3:: import cnfhash # reading blockwise from a DIMACS file def read_blockwise(filepath): with open(filepath) as fd: while True: buf = fd.read(4096) if len(buf) == 0: break yield buf reader = read_blockwise('test.cnf') print(cnfhash.hash_dimacs(reader)) # or use integers directly print(cnfhash.hash_cnf([3, 2, 1, -3, 0, -1, 2, 0])) Testing the software -------------------- Download `the testsuite <http://github.com/prokls/cnf-hash-tests1/>`_. Provide the folder location as environment variable:: export TESTSUITE="/home/prokls/Downloads/cnf-hash/tests1/" Then run all files in the ``tests`` directory:: python3 tests/test_testsuite.py The testsuite has been run successfully, if the exit code has always been 0. DIMACS file assumptions ----------------------- A DIMACS file is valid iff 1. Any line starting with "c" or consisting only of whitespace is considered as *comment line* and content is not interpreted until the next newline character occurs. 2. The remaining file is a sequence of whitespace separated values. 1. The first value is required to be "p" 2. The second value is required to be "cnf" 3. The third value is required to be a non-negative integer and called *nbvars*. 4. The fourth value is required to be a non-negative integer and called *nbclauses*. 5. The remaining non-zero integers are called *lits*. 6. The remaining zero integers are called *clause terminators*. 3. A DIMACS file must be terminated by a clause terminator. 4. Every lit must satisfy ``-nbvars ≤ lit ≤ nbvars``. 5. The number of clause terminators must equate nbclauses. ============== ========================================= **term** **ASCII mapping** -------------- ----------------------------------------- "c" U+0063 "p" U+0070 "cnf" U+0063 U+006E U+0066 U+0020 sign U+002D nonzero digit U+0031 – U+0039 digits U+0030 – U+0039 whitespace U+0020, U+000D, U+000A, U+0009 zero U+0030 ============== ========================================= Formal specification -------------------- A valid DIMACS file is read in and a SHA1 instance is fed with bytes: 1. The first four values are dropped. 2. Lits are treated as integers without leading zeros. Integers are submitted as base 10 ASCII digits with an optional leading sign to the SHA1 instance. 3. Clause terminators are submitted as zero character followed by a newline character to the SHA1 instance. Performance and memory ---------------------- The DIMACS parser uses OS' page size as default block size. A few constant values and the python runtime is also stored in memory. So for a python program, this implementation is very memory-friendly. The technical report shows that 45 DIMACS files summing up to 1 GB memory can be read in 2989 seconds. In terms of performance, the equivalent `Go implementation <http://github.com/prokls/cnf-hash-go/>`_ is recommended. Example ------- :: % cat test.cnf p cnf 5 6 1 2 3 0 2 3 -4 0 1 -2 0 -1 2 0 1 3 5 0 1 -4 -5 0 % cnf-hash-py test.cnf cnf-hash-py 2.1.2 2016-05-29T12:27:13.991260 /root cnf2$776d81a0c805104e265667917b22ffefe9f39433 test.cnf % Cheers!
c5ca130f80796037c64f144c77ed6356f34f1147
[ "Python", "reStructuredText" ]
6
Python
prokls/cnf-hash-py
37e1b1392845acc00faff4451b64dbb40af99e1e
52c64ac549f8f94d36fe0aabe6bc7ff34a35f9c6
refs/heads/main
<repo_name>gongsir0630/easypicker2-client<file_sep>/src/utils/regExp.ts // 手机号 export const rMobilePhone = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|16[0-9]|17[0-9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/ // 账号 export const rAccount = /^(\d|[a-zA-Z]){4,8}$/ // 密码 支持字母/数字/下划线(6-16) export const rPassword = /^\w{6,16}$/ // 验证码 export const rVerCode = /^\d{4}$/ <file_sep>/src/apis/modules/file.ts import ajax from '../ajax' function getUploadToken() { return ajax.get<any, BaseResponse>('file/token') } function addFile(options:DbFile) { return ajax.post<any, BaseResponse>('file/info', options) } function getFileList() { return ajax.get<any, BaseResponse>('file/list') } function getTemplateUrl(template:string, key:string) { return ajax.get<any, BaseResponse>('file/template', { params: { template, key, }, }) } function getOneFileUrl(id:number) { return ajax.get<any, BaseResponse>('file/one', { params: { id, }, }) } function deleteOneFile(id:number) { return ajax.delete<any, BaseResponse>('file/one', { params: { id, }, }) } function batchDownload(ids:number[]) { return ajax.post<any, BaseResponse>('file/batch/down', { ids, }) } function batchDel(ids:number[]) { return ajax.delete<any, BaseResponse>('file/batch/del', { params: { ids, }, }) } function checkCompressStatus(id:string) { return ajax.post<any, BaseResponse>('file/compress/status', { id, }) } function getCompressDownUrl(key:string) { return ajax.post<any, BaseResponse>('file/compress/down', { key, }) } function getCompressFileUrl(id:string):Promise<string> { const check = (_r:any) => { checkCompressStatus(id).then((r) => { const { code, key } = r.data if (code === 0) { getCompressDownUrl(key).then((v) => { const { url } = v.data _r(url) }) } else { setTimeout(() => { check(_r) }, 1000) } }) } return new Promise((resolve, reject) => { check(resolve) }) } interface WithdrawFileOptions{ taskKey:string taskName:string filename:string hash:string peopleName:string info:string } function withdrawFile(options:WithdrawFileOptions) { return ajax.delete('file/withdraw', { params: options, }) } export default { getUploadToken, addFile, getFileList, getTemplateUrl, withdrawFile, getOneFileUrl, deleteOneFile, batchDownload, batchDel, checkCompressStatus, getCompressFileUrl, getCompressDownUrl, } <file_sep>/src/utils/networkUtil.ts import { base64 } from './stringUtil' /* eslint-disable no-restricted-syntax */ type SuccessCallback = (data:any) => void export function jsonp(url: string, jsonpCallback: string, success:SuccessCallback) { const $script = document.createElement('script') $script.src = `${url}&callback=${jsonpCallback}` $script.async = true $script.type = 'text/javascript'; (<any>window)[jsonpCallback] = function callback(data:any) { if (success) { success(data) } } document.body.appendChild($script) } interface UploadFileOptions{ success?:any, error?:any, process?:any method?:string, } export function uploadFile(file:File, url:string, options?:UploadFileOptions) { const form = new FormData() // ajax对象 const xhr = new XMLHttpRequest() // 添加文件到表单中 form.append('file', file) // 设置请求方式 路径 是否异步 xhr.open(options?.method || 'post', url, true) // 设置请求头参数的方式,如果没有可忽略此行代码 xhr.setRequestHeader('token', localStorage.getItem('token') as string) if (options?.success) { // 上传完成 xhr.onload = (e) => { const target = e?.currentTarget as any if (target.response) { options.success(JSON.parse(target.response)) return } options.success() } } if (options?.error) { // 上传出错 xhr.onerror = options.error } if (options?.process) { // 上传中 xhr.onprogress = (e) => { const { total, loaded, lengthComputable } = e if (lengthComputable) { options.process((loaded / total).toFixed(2)) } } } // 发送请求 xhr.send(form) } /** * 导出表格数据为xls * @param headers 头部 * @param body 身体部分数据 */ export function tableToExcel(headers:string[], body:any[], filename = 'res.xls') { // 列标题 let str = `<tr>${headers.map((v) => `<th>${v}</th>`).join('')}</tr>` // 循环遍历,每行加入tr标签,每个单元格加td标签 for (const row of body) { str += '<tr>' for (const cell of row) { // 增加\t为了不让表格显示科学计数法或者其他格式 str += `<td>${`${cell}\t`}</td>` } str += '</tr>' } // Worksheet名 const worksheet = 'sheet1' const uri = 'data:application/vnd.ms-excel;base64,' // 下载的表格模板数据 const template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" \n' + ' xmlns:x="urn:schemas-microsoft-com:office:excel" \n' + ' xmlns="http://www.w3.org/TR/REC-html40">\n' + ' <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>\n' + ` <x:Name>${worksheet}</x:Name>\n` + ' <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>\n' + ' </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->\n' + ` </head><body><table>${str}</table></body></html>\n` // 下载模板 const tempA = document.createElement('a') tempA.href = uri + base64(template) tempA.download = filename document.body.appendChild(tempA) tempA.click() document.body.removeChild(tempA) } /** * 七牛云上传 */ export function qiniuUpload(token:string, file:File, key:string, options?:UploadFileOptions) { const observable = qiniu.upload(file, key, token) const { success, error, process } = options || {} const subscription = observable.subscribe({ next(res) { const { total: { percent } } = res if (process) { process(percent.toFixed(2), res, subscription) } }, error(err) { if (error) { error(err, subscription) } }, complete(res) { if (success) { success(res, subscription) } }, }) // subscription.close() // 取消上传 } export function downLoadByUrl(url: string, filename = `${Date.now()}`) { const a = document.createElement('a') a.href = url a.target = '_blank' a.download = filename a.click() } <file_sep>/src/apis/modules/public.ts import ajax from '../ajax' /** * 获取验证码 * @param mobile 手机号 */ function getCode(phone: string) { return ajax.get<any, BaseResponse>( 'public/code', { params: { phone, }, }, ) } function reportPv(path:string) { return ajax.post<any, BaseResponse>( 'public/report/pv', { path, }, ) } export default { getCode, reportPv, } <file_sep>/src/pages/dashboard/tasks/public.ts import { TaskApi } from '@/apis' import { ElMessage } from 'element-plus' export const updateTaskInfo = (key:string, options: any) => { if (key) { TaskApi .updateTaskMoreInfo(key, options) .then(() => { ElMessage.success('设置成功') }) .catch(() => { ElMessage.error('设置失败') }) } } <file_sep>/build/compress.sh # /bin/bash compressDir="./dist" # 需要压缩目录 compressFile="ep2.tar.gz" # 压缩后的文件名 echo "开始-----归档解压" tar -zvcf ${compressFile} ${compressDir}<file_sep>/src/router/routes/index.ts import { RouteRecordRaw } from 'vue-router' import Home from '@/pages/home/index.vue' const NotFind = () => import('@/pages/404/index.vue') const Login = () => import('@/pages/login/index.vue') const Reset = () => import('@/pages/reset/index.vue') const Register = () => import('@/pages/register/index.vue') const About = () => import('@/pages/about/index.vue') const Author = () => import('@/pages/callme/index.vue') const Feedback = () => import('@/pages/feedback/index.vue') const Dashboard = () => import('@/pages/dashboard/index.vue') const Files = () => import('@/pages/dashboard/files/index.vue') const Tasks = () => import('@/pages/dashboard/tasks/index.vue') // const Manage = () => import('@/pages/dashboard/manage/index.vue') // const Overview = () => import('@/pages/dashboard/manage/overview/index.vue') // const User = () => import('@/pages/dashboard/manage/user/index.vue') const Task = () => import('@/pages/task/index.vue') const requireLogin = { requireLogin: false, } const routes: RouteRecordRaw[] = [ // 404 { path: '/:pathMatch(.*)*', name: '404', component: NotFind }, { path: '/', name: 'home', component: Home }, { path: '/login', name: 'login', component: Login }, { path: '/register', name: 'register', component: Register }, { path: '/reset', name: 'reset', component: Reset }, { path: '/about', name: 'about', component: About }, { path: '/author', name: 'author', component: Author }, { path: '/feedback', name: 'feedback', component: Feedback }, { path: '/task/:key', name: 'task', component: Task }, { path: '/dashboard', name: 'dashboard', component: Dashboard, redirect: { name: 'tasks', }, children: [ { name: 'files', path: 'files', component: Files, meta: requireLogin, }, { name: 'tasks', path: 'tasks', component: Tasks, meta: requireLogin, }, // { // name: 'manage', // path: 'manage', // component: Manage, // meta: requireLogin, // redirect: { // name: 'overview', // }, // children: [ // { // name: 'overview', // path: 'overview', // component: Overview, // meta: requireLogin, // }, // { // name: 'user', // path: 'user', // component: User, // meta: requireLogin, // }, // ], // }, ], }, ] export default routes <file_sep>/src/apis/modules/people.ts import ajax from '../ajax' function importPeople(key: string, filename:string, type:string) { return ajax.post<any, BaseResponse>( `/people/${key}`, { filename, type, }, ) } function getPeople(key:string) { return ajax.get<any, BaseResponse>(`/people/${key}`) } function deletePeople(key:string, id:number) { return ajax.delete<any, BaseResponse>(`/people/${key}`, { params: { id, }, }) } function updatePeopleStatus(key:string, filename:string, name:string, hash:string) { return ajax.put<any, BaseResponse>(`/people/${key}`, { filename, name, hash, }) } function checkPeopleIsExist(key:string, name:string) { return ajax.get<any, BaseResponse>(`/people/check/${key}`, { params: { name, }, }) } export default { importPeople, getPeople, deletePeople, updatePeopleStatus, checkPeopleIsExist, } <file_sep>/src/@types/model.d.ts interface TaskInfo{ template?:string rewrite?:number format?:number info?:string share?:string ddl?:string people?:number } declare namespace qiniu { interface Subscription { unsubscribe(): void } interface SubscriptionConfig { next(res: any): void, error(err:any): void, complete(res:any): void } interface Observable { subscribe(cf: SubscriptionConfig): Subscription } type upload = (file: File, key: string, token: string) => Observable const upload: upload } interface DbFile { taskKey?: string taskName?: string categoryKey?: string name?: string info?: string hash?: string size?: number people?: string } <file_sep>/src/store/modules/category.ts import { CategoryApi } from '@/apis' import { Module } from 'vuex' interface State { categoryList: any [] } const store: Module<State, unknown> = { namespaced: true, state() { return { categoryList: [], } }, mutations: { updateCategory(state, payload) { state.categoryList = payload }, }, actions: { getCategory(context) { CategoryApi.getList().then((res) => { context.commit('updateCategory', res.data.categories) }) }, createCategory(context, name) { return CategoryApi.createNew(name).then((res) => { context.dispatch('getCategory') return res }) }, deleteCategory(context, k) { return CategoryApi.deleteOne(k).then((res) => { const idx = context.state.categoryList.findIndex((v) => v.k === k) if (idx >= 0) { context.state.categoryList.splice(idx, 1) } return res }) }, }, } export default store <file_sep>/src/apis/modules/category.ts import ajax from '../ajax' function getList() { return ajax.get<any, BaseResponse>( 'category', ) } function createNew(name:string) { return ajax.post<any, BaseResponse>( 'category/create', { name, }, ) } function deleteOne(key:string) { return ajax.delete<any, BaseResponse>(`category/${key}`) } export default { getList, createNew, deleteOne, } <file_sep>/src/utils/stringUtil.ts import { ElMessage } from 'element-plus' import SparkMD5 from 'spark-md5' import { jsonp } from './networkUtil' /** * 将结果写入的剪贴板 * @param {String} text */ export function copyRes(text:string) { const input = document.createElement('input') document.body.appendChild(input) input.setAttribute('value', text) input.select() if (document.execCommand('copy')) { document.execCommand('copy') } document.body.removeChild(input) ElMessage.success('结果已成功复制到剪贴板') } /** * 生成短地址 * @param url */ export function getShortUrl(text:string):Promise<string> { return new Promise((resolve, reject) => { jsonp(`https://api.suowo.cn/api.htm?format=jsonp&url=${encodeURIComponent(text)}&key=<KEY>&expireDate=2030-03-31&domain=0`, 'shortLink', (res) => { const { url, err } = res if (err) { reject(err) } resolve(url) }) }) } export function base64(s:string) { return window.btoa(unescape(encodeURIComponent(s))) } export function formatDate(d:Date, fmt = 'yyyy-MM-dd hh:mm:ss') { const o:any = { 'M+': d.getMonth() + 1, // 月份 'd+': d.getDate(), // 日 'h+': d.getHours(), // 小时 'm+': d.getMinutes(), // 分 's+': d.getSeconds(), // 秒 'q+': Math.floor((d.getMonth() + 3) / 3), // 季度 S: d.getMilliseconds(), // 毫秒 } if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (`${d.getFullYear()}`).substr(4 - RegExp.$1.length)) } // eslint-disable-next-line no-restricted-syntax for (const k in o) { if (new RegExp(`(${k})`).test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length))) } return fmt } export function getFileSuffix(str:string) { return str.slice(str.lastIndexOf('.')) } export function getFileMd5Hash(file:File) { return new Promise((resolve, reject) => { const blobSlice = File.prototype.slice const chunkSize = 2097152 // Read in chunks of 2MB const chunks = Math.ceil(file.size / chunkSize) let currentChunk = 0 const spark = new SparkMD5.ArrayBuffer() const fileReader = new FileReader() function loadNext() { const start = currentChunk * chunkSize const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize fileReader.readAsArrayBuffer(blobSlice.call(file, start, end)) } fileReader.onload = function (e) { // console.log('read chunk nr', currentChunk + 1, 'of', chunks) spark.append(e?.target?.result) // Append array buffer currentChunk += 1 if (currentChunk < chunks) { loadNext() } else { // console.log('finished loading') const hashResult = spark.end() // console.info('computed hash', hashResult) // Compute hash resolve(hashResult) } } fileReader.onerror = function () { reject(new Error('oops, something went wrong.')) } loadNext() }) } export function formatSize(size:number, pointLength?:number, units?:string[]) { let unit units = units || ['B', 'K', 'M', 'G', 'TB'] // eslint-disable-next-line no-cond-assign while ((unit = units.shift()) && size > 1024) { size /= 1024 } return (unit === 'B' ? size : size.toFixed(pointLength === undefined ? 2 : pointLength)) + unit } <file_sep>/src/apis/ajax.ts import router from '@/router' import axios from 'axios' import { ElMessage } from 'element-plus' const instance = axios.create({ baseURL: '/api/', }) /** * 请求拦截 */ instance.interceptors.request.use((config) => { const { method, params } = config // 附带鉴权的token const headers: any = { token: localStorage.getItem('token'), } // 不缓存get请求 if (method === 'get') { headers['Cache-Control'] = 'no-cache' } // delete请求参数放入body中 if (method === 'delete') { headers['Content-type'] = 'application/json;' Object.assign(config, { data: params, params: {}, }) } return ({ ...config, headers, }) }) // 跳转首页防抖 let redirectHome = true /** * 响应拦截 */ instance.interceptors.response.use((v) => { if (v.status === 200) { if (v.data.code === 0) { return v.data } if (v.data?.code === 3004) { localStorage.removeItem('token') if (redirectHome) { redirectHome = false ElMessage.error('登录过期,跳转首页') router.replace({ name: 'home', }) setTimeout(() => { redirectHome = true }, 1000) } } if (v?.data?.code === 500) { ElMessage.error(v?.data?.msg) } return Promise.reject(v.data) } ElMessage.error(v.statusText) return Promise.reject(v) }) export default instance <file_sep>/src/store/modules/task.ts import { TaskApi } from '@/apis' import { Module } from 'vuex' interface State { taskList: any [] } const store: Module<State, unknown> = { namespaced: true, state() { return { taskList: [], } }, mutations: { updateTask(state, payload) { state.taskList = payload }, }, actions: { getTask(context) { TaskApi.getList().then((res) => { context.commit('updateTask', res.data.tasks) }) }, createTask(context, payload) { const { name, category } = payload return TaskApi.create(name, category).then((res) => { context.dispatch('getTask') return res }) }, deleteTask(context, k) { return TaskApi.deleteOne(k).then((res) => { const idx = context.state.taskList.findIndex((v) => v.key === k) if (idx >= 0) { context.state.taskList.splice(idx, 1) } return res }) }, updateTask(context, payload) { const { key, name, category } = payload return TaskApi.updateBaseInfo(key, name, category).then((res) => { context.dispatch('getTask') return res }) }, }, } export default store <file_sep>/src/store/modules/user.ts import { Module } from 'vuex' interface State { token: string, isSuperAdmin: boolean } const store: Module<State, unknown> = { namespaced: true, state() { return { token: localStorage.getItem('token') as string, isSuperAdmin: false, } }, // 只能同步 mutations: { setToken(state, payload) { state.token = payload if (payload) { localStorage.setItem('token', payload) } else { localStorage.removeItem('token') } }, setSuperAdmin(state, payload) { state.isSuperAdmin = payload }, }, } export default store <file_sep>/README.md # <h1 align="center">EasyPicker2.0:轻取</h1> <p align="center">为提高在线文件收取效率而生</p> <p align="center"> <a href="https://ep.sugarat.top"> <img src="https://img.shields.io/badge/status-updating-success.svg" alt="Status"> </a> </p> ## 项目简介 在原有[EasyPicker1.0](https://ep.sugarat.top)的功能基础上,使用新技术进行功能的拓展 ## 项目背景 校园学习或者工作场景中会出现以下几个场景: * 每次碰到上机课的时候,都会遇到收取实验报告。 * 需要收取每个人填写的各种电子表格。 * 需要通过QQ/微信等等收集各种截图 * 类似场景还有不少就不列举了。。。 通常的方式是,通过QQ/微信/邮箱等收取,弊端显而易见,太过于麻烦且不方便整理统计。还占用电脑/手机内存。为了解决这个问题,此项目应运而生。 ## [开发计划-进度](plan.md) ## 本地运行 <details> 1. clone仓库到本地 ```sh git clone https://github.com/ATQQ/easypicker2-client.git ``` 2. 安装依赖 ```sh yarn ``` 3. 本地启动 ```sh yarn dev ``` 4. 其它指令 | 名称 | 作用 | | :--------: | :--------------- | | dev | 本地启动服务 | | build | 生产环境打包 | | build:test | 测试环境打包 | | serve | 预览本地构建产物 | | lint | 代码格式化 | </details> ## 线上地址 1. 正式环境:https://ep2.sugarat.top 2. 测试环境:https://ep2.test.sugarat.top 注:两环境数据不互通,新功能会先在测试环境进行实验 ## 技术栈 1. 前端:Vue3,Typescript,Vite - [模板仓库](https://github.com/ATQQ/vite-vue3-template) 2. 服务端:Typescript,Node.js - [模板仓库](https://github.com/ATQQ/node-server) ## 相关仓库 ### [EasyPicker1.0](https://ep.sugarat.top/) 1. ~~服务端(Java-已弃用):https://github.com/ATQQ/EasyPicker~~ 2. 客户端(web) :https://github.com/ATQQ/EasyPicker-webpack 3. 服务端(Node.js):https://github.com/ATQQ/easypicker-server ### [EasyPicker2.0](https://ep2.sugarat.top) 1. 客户端(Web):https://github.com/ATQQ/easypicker2-client 2. 服务端(Node.js):https://github.com/ATQQ/easypicker2-server ## 相关文档 * 使用手册 * 更新日志 * 数据库相关 * 接口文档 ## 其他链接 问卷反馈:https://www.wenjuan.com/s/UZBZJvA040/ <!-- ## 扫码反馈 ![图片](https://img.cdn.sugarat.top/mdImg/MTU5Njg5NTE3MTk1Nw==596895171957) --> ## 欢迎体验分享,反馈Bug ![TIM图片20191015225526-20191015](https://img.cdn.sugarat.top/TIM图片20191015225526-20191015.gif)<file_sep>/plan.md # 开发计划-进度 按页面划分功能 ## 门户页 ok * 导航 * 登录 * 注册 * 反馈 * 关于 * 使用文档 * Github * 联系QQ * 博客 * 产品简介 ## 文件管理 ok * 提交记录展示 * 筛选 * 分类 * 分任务 * 关键词 * 分页 * 自定义页面大小 * 下载 * 单个 * 批量 * 指定任务 * 删除 * 单个 * 批量 ## 任务管理 ok * 分类 * 创建 * 删除 * 筛选任务 * 任务 * 创建 * 删除 * 任务属性修改 * 修改名称/分类 * 设置DDL * 生成链接 * 限制提交人员 * 查看提交情况 * 导出提交情况 * 设置模板文件 * 自动重命名 * 必填信息 ## 文件上传 ok * 提交文件 * 单个 * 多个 * 填写必要信息 * 下载模板 * 撤回提交的文件 * 查看截止日期 ## 登录 ok * 导航 * 忘记密码(修改/重置密码) * 注册 * 登录方式 * 手机号-密码 * 账号-密码 * 手机号-验证码 * 登录成功 * 数据看板页 * 文件管理 * 任务管理 ## 注册 ok * 方式 * 账号+密码 * 账号+密码+手机号 ## 忘记密码 ok * 修改方式 * 手机号+验证码+新密码 ## 数据看板 * 产品运行信息查看 * 所有操作日志,提交记录 ## 用户管理 * 基本信息维护 * 状态信息修改 * 行为日志查看 ## 反馈页 * 上报问题 ## 反馈查看页面 * 更进问题与处理进度 ...未完待续<file_sep>/src/apis/modules/task.ts import ajax from '../ajax' function getList() { return ajax.get<any, BaseResponse>('task') } function create(name:string, category:string) { return ajax.post<any, BaseResponse>('task/create', { name, category, }) } function deleteOne(key:string) { return ajax.delete<any, BaseResponse>(`task/${key}`) } function updateBaseInfo(key:string, name:string, category:string) { return ajax.put<any, BaseResponse>(`task/${key}`, { name, category, }) } function getTaskInfo(key:string) { return ajax.get<any, BaseResponse>(`task/${key}`) } function getTaskMoreInfo(key:string) { return ajax.get<any, BaseResponse>(`task_info/${key}`) } function updateTaskMoreInfo(key:string, options:any) { return ajax.put<any, BaseResponse>(`task_info/${key}`, options) } export default { getList, create, deleteOne, updateBaseInfo, getTaskInfo, getTaskMoreInfo, updateTaskMoreInfo, } <file_sep>/src/apis/modules/user.ts import ajax from '../ajax' function register(account:string, pwd:string, bindPhone = false, options?:any) { return ajax.post<any, BaseResponse>('user/register', { account, pwd, bindPhone, ...options, }) } function login(account:string, pwd:string) { return ajax.post<any, BaseResponse>('user/login', { account, pwd, }) } function codeLogin(phone:string, code:string) { return ajax.post<any, BaseResponse>('user/login/code', { phone, code, }) } function resetPwd(phone:string, code:string, pwd:string) { return ajax.put<any, BaseResponse>('user/password', { phone, code, pwd, }) } function checkPower() { return ajax.get<any, BaseResponse>('user/power/super') } export default { register, login, codeLogin, resetPwd, checkPower, } <file_sep>/src/apis/modules/super/overview.ts import ajax from '../../ajax' const baseUrl = '/super/overview' function getCount() { return ajax.get<any, BaseResponse>(`${baseUrl}/count`) } function getAllLogMsg() { return ajax.get<any, BaseResponse>(`${baseUrl}/log`) } export default { getCount, getAllLogMsg, } <file_sep>/src/utils/elementUI.ts import { App } from '@vue/runtime-core' // import { // ElButton, ElInput, ElPopover, ElTag, // ElSelect, ElOption, ElCard, ElEmpty, // ElForm, ElFormItem, ElDialog, ElImage, // ElTabs, ElTabPane, ElDatePicker, ElTimePicker, ElTimeSelect, // } from 'element-plus' // import 'element-plus/packages/theme-chalk/src/icon.scss' // import lang from 'element-plus/lib/locale/lang/zh-cn' // import 'dayjs/locale/zh-cn' // import locale from 'element-plus/lib/locale' // // 设置语言 // locale.use(lang) // const components = [ // ElSelect, // ElOption, // ElCard, // ElEmpty, ElImage, // ElTabs, ElTabPane, // ElDatePicker, // ElTimePicker, // ElTimeSelect, // ElDatePicker, // ElForm, ElFormItem, ElDialog, // ElButton, ElInput, ElPopover, ElTag] import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' import 'dayjs/locale/zh-cn' import locale from 'element-plus/lib/locale/lang/zh-cn' export default function mountElementUI(app: App<Element>) { app.use(ElementPlus, { locale }) // components.forEach((c) => { // app.component(c.name, c) // }) } <file_sep>/src/apis/index.ts import p from './modules/public' import user from './modules/user' import category from './modules/category' import task from './modules/task' import people from './modules/people' import file from './modules/file' import superOverview from './modules/super/overview' export const PublicApi = p export const UserApi = user export const CategoryApi = category export const TaskApi = task export const PeopleApi = people export const FileApi = file export const SuperOverviewApi = superOverview <file_sep>/build/deploy.sh # /bin/bash compressFile="ep2.tar.gz" # 压缩后的文件名 user="root" # 远程登录用户 origin="sugarat.top" # 远程登录origin targetDir="/www/wwwroot/ep2.sugarat.top" # 目标目录 echo "开始-----部署" ssh -p22 ${user}@${origin} "tar -zvxf ${compressFile} -C ${targetDir}" echo "清理-----临时的文件" rm -rf $compressFile<file_sep>/src/store/index.ts import { createStore } from 'vuex' import user from './modules/user' import category from './modules/category' import task from './modules/task' // Create a new store instance. const store = createStore({ modules: { user, category, task, }, }) export default store <file_sep>/src/main.ts import { createApp } from 'vue' import mountElementUI from './utils/elementUI' import router from './router' import store from './store' import App from './App.vue' import Axios from './apis/ajax' document.title = import.meta.env.VITE_APP_TITLE as string const app = createApp(App) app.provide('$http', Axios) app.use(router) app.use(store) // 引入需要的ElementUI Component mountElementUI(app) app.mount('#app')
09214f7e4317d1a1ba3399cda43257ec056725ad
[ "Markdown", "TypeScript", "Shell" ]
25
TypeScript
gongsir0630/easypicker2-client
ea963acac3e49dc283a2e697212df72434158f0a
2f7a17136b40d9172b68d0b73790d3d8c26dc314
refs/heads/master
<file_sep>const express=require('express'); const path=require('path'); const mysql=require('mysql'); const ejs=require('ejs'); const bodyParser=require('body-parser'); //DataBase Connection const connection=mysql.createConnection({ host:'localhost', user:'root', password:'', database:'node-crud' }); connection.connect(function(error){ if(!!error){ console.log(error); }else{ console.log('Database Connected!'); } }); const app=express(); app.set('views', path.join(__dirname,'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); //Routes app.get('/', (req,res)=>{ let sql="SELECT * FROM students"; let query=connection.query(sql, (err,rows)=>{ if(err) throw err; res.render('index',{ students:rows }); }); }) //Add Students app.post('/save', (req,res)=>{ let sql="INSERT INTO `students`(`name`, `age`, `fatherName`, `motherName`, `address`) VALUES ('"+req.body.name+"','"+req.body.age+"','"+req.body.fatherName+"','"+req.body.motherName+"','"+req.body.address+"')"; let query=connection.query(sql,(err,results)=>{ if(err) throw err; res.redirect('/'); }); }); //Edit Students app.get('/edit/:studentId', (req,res)=>{ const studentId=req.params.studentId; let sql=`SELECT * FROM students WHERE id=${studentId}`; let query=connection.query(sql,(err,result)=>{ if(err) throw err; res.render('edit',{ students:result[0] }); }); }); //update students app.post('/update' , (req , res)=>{ const studentId=req.body.id; let sql ="update students SET name='"+req.body.name+"', age='"+req.body.age+"', fatherName='"+req.body.fatherName+"', motherName='"+req.body.motherName+"', address='"+req.body.address+"' where id="+studentId; let query=connection.query(sql,(err,results)=>{ if(err) throw err; res.redirect('/'); }); }); //Delete students app.get('/delete/:studentId', (req, res)=>{ const studentId=req.params.studentId; let sql=`DELETE from students where id=${studentId}`; let query=connection.query(sql,(err,results)=>{ if(err) throw err; res.redirect('/'); }) }) app.listen(3000,()=>{ console.log("Server is Running at Port 3000!"); })
ee707d5533e4532493b37cb32e536e210646e159
[ "JavaScript" ]
1
JavaScript
revocoder0/Student_Node
848ec6118525bc030abe93d4edd4a2103a576139
1e850254ee3309d70fb9ece4a8fd31a1c383ef1d
refs/heads/master
<repo_name>Pl4typusRex/ou-interface<file_sep>/Lovable.java /** * Provides an interface for three methods, stroke(), canStroke() and feed(). * * @author Pl4typusRex * @version 2019-01-20 */ public interface Lovable { /** * Performs an action in response to 'stroke'. */ public void stroke(); /** * Performs an action in response to 'canStroke'. */ public boolean canStroke(); /** * Performs an action in response to 'feed'. */ public void feed(); } <file_sep>/README.md # ou-interface Part of Open University work for the Object Oriented Java module. Simple interface and subclass example.
3c4915d92d921cf52aaae9cbf3f753419efd12c8
[ "Markdown", "Java" ]
2
Java
Pl4typusRex/ou-interface
436fea1569a2fba29bd13d57152ea86af79b5548
b71a92843b41a83de2185011e51c5299c6deb2a0
refs/heads/master
<file_sep> # Validating request payload and body [![npm version](https://badge.fury.io/js/goabela-schema-validator.svg)](https://badge.fury.io/js/goabela-schema-validator) This module can validate the request's payload and body by using a schema JSON file. ## Installation Install it by using the `npm install` command in the node shell: ```sh $ npm install goabela-schema-validator ``` \ Import the module in your `.js` file: ```js var schemaValidator = require("goabela-schema-validator") ``` ## Features ### Validate _Method: `schemaValidator.validate()`._ The `validate` method will do the validation. It will return a promise so you can call `then` and `catch` on the method. Required arguements are the body/payload as an object and the schema object. First you have to create a schema object. A good solution could be that creating a schema file such as `schema.json`. After that in the NodeJS file (e.g. under the Express controller), you can call the `validate` method with the schema and the body object. The prototype of the method: ```js schemaValidator.validate(body, schema) .then(() => { // The body is OK }) .catch(err => { // The body is invalid }) ``` The `err` variable will contain an object with all the errors that the body has. You can check the possible errors at the [errors section](#errors). _For a full example please check the [example section](#example)._ ## Schema structure ### Properties The available properties are the followings: - `type`: The type of the element. Valid values are `string`, `number` and `array`. Default is `string`. - `required`: Wether the given element is required or not. Can be `true` or `false`. Default is `false`. - `children`: The sub-elements. - `enum`: The list of the possible values collected into an array. - ~`length`~: The length settings of the element. Can have a `min` and a `max` value. - ~`range`~: When the `type` is `number`, you can specify a range by adding `min` and `max`. - ~`pattern`~: A regex script that you want to run on the given value. ### Prototype ```js { "username": { "type": "string", "required": true } } ``` ## Errors By calling the `catch` on the `validate` function, you can get the errors. ```js .catch(err => { console.log(err) // Output: { "internalIssue": "schemaNotSet" } }) ``` ### Internal errors _Error key: `internalIssue`._ The internal issues can be the followings: - `schemaNotSet`: The schema has not been set properly. - `bodyNotSet`: The body has not been set properly. - `bodyNotEmpty`: The schema is empty which means no body should have been received, but it is not empty. ### Missing keys _Error key: `missingKeys`._ If there are any keys which are required but the body has no such key, then this error will be returned. It will be an array which contains the missing keys with all its parents, for instance `born.date.year`. ### Invalid keys _Error key: `invalidKeys`._ If there are any keys in the body which are not in the schema, then this error will be returned. It will be an array which contains the invalid keys with all its parents, for instance `born.date.foo`. ### Invalid types _Error key: `invalidTypes`._ This error object will be returned once there are any type errors. For instance, in the schema if you set type of `year` to be `number`, and the body's key has different type, then this error will be returned. ### Out of enum _Error key: `outOfEnum`._ If you set an enum on a property, the validator will force the body's value to be one of the enum's value. ## Example The `schema.json` file: ```json { "userId": { "type": "string", "required": true }, "userRole": { "type": "string", "enum": ["owner", "writer"] } } ``` \ The `app.js` file: ```js // Other part of the app.js var schemaValidator = require("goabela-schema-validator") var bodySchema = require("./schema.json") app.post("/user", (req, res) => { schemaValidator.validate(req.body, bodySchema) .then(() => { // Do something }) .catch(err => { res.json({ "message": "The request body is not correct.", "errors": err }) }) }) ``` ## TO-DOs - ~Migrating the script from my app into a single node package.~ :heavy_check_mark: - ~Deploying unit-testing.~ :heavy_check_mark: - Creating all the features stated above. - Migrating the validator core loops into iterators. ## Tests Test files are located in the `test` directory. Use the `test` `npm` script to run the tests: ```sh $ npm run test ``` ## License [MIT](LICENSE) <file_sep>var assert = require("chai").assert var expect = require("chai").expect var schemaValidator = require("../index.js") /** * Defining the schema and the body. * * Resetting before each test. * Later this will be modified for testing. */ let schema = null let body = null beforeEach(done => { schema = { username: { type: "string" }, name: { children: { last: { type: "string" }, first: { type: "string", required: true }, nick: { type: "string" } } }, born: { children: { place: { type: "string" }, date: { children: { year: { type: "number" }, month: { type: "string", enum: ["Jan", "Feb", "Marc"] }, day: { type: "number", required: true } } } } }, skills: { type: "array" } } body = { username: "johndoe", name: { last: "Doe", first: "John", nick: "Johnny" }, born: { place: "Colorado, Denver", date: { year: 1985, month: "Jan", day: 15 } }, skills: [ "SEO", "HTML", "CSS" ] } done() }) // Internal issue tests describe("Internal tests", () => { // Testing with empty body it("Should throw EmptyBody error", () => { return schemaValidator.validate(null, schema) .then(() => { assert.fail(0, 1, "Validate should have thrown Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("internalIssue") expect(err.internalIssue).to.equal("bodyNotSet") }) }) // Testing with empty schema it("Should throw EmptySchema error", () => { return schemaValidator.validate(body, null) .then(() => { assert.fail(0, 1, "Validate should have thrown Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("internalIssue") expect(err.internalIssue).to.equal("schemaNotSet") }) }) }) // Basic tests describe("Basic tests", () => { // Testing for success validation it("Should be OK", () => { return schemaValidator.validate(body, schema) .then(() => { assert }) .catch(err => { assert.fail(0, 1, "Validate thrown Error") }) }) // Testing for `invalidKeys` error it("Should throw InvalidKey Error", () => { // Adding an foreign key body.testingForInvalidKey1 = 123 body.testingForInvalidKey2 = { subKey2: null } body.testingForInvalidKey3 = { subKey3: { subSubKey3: 123 } } body.testingForInvalidKey4 = { subKey4: { subSubKey4: { subSubSubKey4: 123 } } } return schemaValidator.validate(body, schema) .then(() => { assert.fail(0, 1, "Should have thrown an Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("invalidKeys") expect(err.invalidKeys).to.be.an.instanceof(Array) expect(err.invalidKeys).to.have.lengthOf(4) expect(err.invalidKeys[0]).to.equal("testingForInvalidKey1") expect(err.invalidKeys[1]).to.equal("testingForInvalidKey2") expect(err.invalidKeys[2]).to.equal("testingForInvalidKey3") expect(err.invalidKeys[3]).to.equal("testingForInvalidKey4") }) }) // Testing for `missingKey` error it("Should throw MissingKey Error", () => { // Adding extra keys to the schema schema.requiredTest1 = { type: "string", required: true } schema.requiredTest2 = { type: "string", required: false } schema.requiredTest3 = { children: { subItem3: { type: "string", required: true } } } schema.requiredTest4 = { children: { subItem4: { children: { subSubItem4: { type: "string", required: true } } } } } return schemaValidator.validate(body, schema) .then(() => { assert.fail(0, 1, "Should have thrown an Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("missingKeys") expect(err.missingKeys).to.be.an.instanceof(Array) expect(err.missingKeys).to.have.lengthOf(3) expect(err.missingKeys[0]).to.equal("requiredTest1") expect(err.missingKeys[1]).to.equal("requiredTest3.subItem3") expect(err.missingKeys[2]).to.equal("requiredTest4.subItem4.subSubItem4") }) }) }) // Type tests describe("Type tests", () => { it("Should expect `string` instead of `number` and `array`", () => { // Setting up invalid types body.testWithNumber = { subItem: { subSubItem: 47576458 } } schema.testWithNumber = { children: { subItem: { children: { subSubItem: { type: "string" } } } } } body.testWithArray = { subItem: [ "one", "two", "three" ] } schema.testWithArray = { children: { subItem: { type: "string" } } } return schemaValidator.validate(body, schema) .then(() => { assert.fail(0, 1, "Should have thrown an Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("invalidTypes") expect(err.invalidTypes).to.be.an.instanceof(Array) expect(err.invalidTypes).to.have.lengthOf(2) expect(err.invalidTypes[0].key).to.equal("testWithNumber.subItem.subSubItem") expect(err.invalidTypes[0].expected).to.equal("string") expect(err.invalidTypes[0].received).to.equal("number") expect(err.invalidTypes[1].key).to.equal("testWithArray.subItem") expect(err.invalidTypes[1].expected).to.equal("string") expect(err.invalidTypes[1].received).to.equal("array") }) }) it("Should expect `number` instead of `string` and `array`", () => { // Setting up invalid types body.testWithString = { subItem: { subSubItem: "two" } } schema.testWithString = { children: { subItem: { children: { subSubItem: { type: "number" } } } } } body.testWithArray = { subItem: [ "one", "two", "three" ] } schema.testWithArray = { children: { subItem: { type: "number" } } } return schemaValidator.validate(body, schema) .then(() => { assert.fail(0, 1, "Should have thrown an Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("invalidTypes") expect(err.invalidTypes).to.be.an.instanceof(Array) expect(err.invalidTypes).to.have.lengthOf(2) expect(err.invalidTypes[0].key).to.equal("testWithString.subItem.subSubItem") expect(err.invalidTypes[0].expected).to.equal("number") expect(err.invalidTypes[0].received).to.equal("string") expect(err.invalidTypes[1].key).to.equal("testWithArray.subItem") expect(err.invalidTypes[1].expected).to.equal("number") expect(err.invalidTypes[1].received).to.equal("array") }) }) it("Should expect `array` instead of `string` and `number`", () => { // Setting up invalid types body.testWithString = { subItem: { subSubItem: "two" } } schema.testWithString = { children: { subItem: { children: { subSubItem: { type: "array" } } } } } body.testWithNumber = { subItem: 123 } schema.testWithNumber = { children: { subItem: { type: "array" } } } return schemaValidator.validate(body, schema) .then(() => { assert.fail(0, 1, "Should have thrown an Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("invalidTypes") expect(err.invalidTypes).to.be.an.instanceof(Array) expect(err.invalidTypes).to.have.lengthOf(2) expect(err.invalidTypes[0].key).to.equal("testWithString.subItem.subSubItem") expect(err.invalidTypes[0].expected).to.equal("array") expect(err.invalidTypes[0].received).to.equal("string") expect(err.invalidTypes[1].key).to.equal("testWithNumber.subItem") expect(err.invalidTypes[1].expected).to.equal("array") expect(err.invalidTypes[1].received).to.equal("number") }) }) }) describe("Property tests", () => { it("Should be out of enum", () => { // Setting up a out-of-enum body property body.born.date.month = "Apr" return schemaValidator.validate(body, schema) .then(() => { assert.fail(0, 1, "Should have thrown an Error") }) .catch(err => { expect(err).to.be.an.instanceof(Object) expect(Object.keys(err).length).to.equal(1) expect(err).to.have.property("outOfEnum") expect(err.outOfEnum).to.be.an.instanceof(Array) expect(err.outOfEnum).to.have.lengthOf(1) expect(err.outOfEnum[0].key).to.equal("born.date.month") expect(err.outOfEnum[0].received).to.equal("Apr") expect(err.outOfEnum[0]).to.have.property("enum") expect(err.outOfEnum[0].enum).to.be.an.instanceof(Array) }) }) })
0fde2bcdf2b0b624c9bf84ca982a84e6a029a1e5
[ "Markdown", "JavaScript" ]
2
Markdown
belaarany/schema-validator
7dbbb85871945f8a2e6a3287fc28746a3efe4fc6
0ef5b21c35c61e72c74bb464dc141c021f93bcb6
refs/heads/main
<file_sep>using System.Threading.Tasks; using Cake.Common; using Cake.Common.IO; using Cake.Common.Tools.DotNetCore; using Cake.Common.Tools.DotNetCore.Build; using Cake.Common.Tools.DotNetCore.Test; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .UseWorkingDirectory("..") .Run(args); } } public class BuildContext : FrostingContext { public string MsBuildConfiguration { get; set; } public BuildContext(ICakeContext context) : base(context) { MsBuildConfiguration = context.Argument("configuration", "Release"); }} [TaskName("Clean")] public sealed class CleanTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.CleanDirectory($"./src/Example/bin/{context.MsBuildConfiguration}"); } } [TaskName("Build")] [IsDependentOn(typeof(CleanTask))] public sealed class BuildTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.DotNetCoreBuild("./src/Example.sln", new DotNetCoreBuildSettings { Configuration = context.MsBuildConfiguration, }); } } [TaskName("Test")] [IsDependentOn(typeof(BuildTask))] public sealed class TestTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.DotNetCoreTest("./src/Example.sln", new DotNetCoreTestSettings { Configuration = context.MsBuildConfiguration, NoBuild = true, }); } } [TaskName("Default")] [IsDependentOn(typeof(TestTask))] public sealed class Default : FrostingTask { }
ec3038712e4bb15ac713febb6a25976134002894
[ "C#" ]
1
C#
pascalberger/cake-frosting-example
0ac29abdcb74efb7fa4069d4d3b8f456294fb6ec
be5e129768b09b34036fc75fa0127576ffd11ac0
refs/heads/master
<file_sep><section class="content-header"> <h1> Disposisi </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Disposisi</a> </li> <li class="active">Inbox</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Inbox Disposisi Surat</h3> </div> <!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table id="table_data" class="table table-striped table-hover"> <thead> <tr> <th>No</th> <th>Nomor Agenda</th> <th>Perihal</th> <th>Isi Ringkas</th> <th>Dari</th> <th>Instruksi</th> <th>Aksi</th> </tr> </thead> <tbody> <?php $no = 1; $query = $mysqli->query("SELECT sm.*,ssm.*,ds.* FROM tbl_disposisi_surat ds LEFT JOIN tbl_status_sm ssm ON ds.no_surat = ssm.no_surat LEFT JOIN tbl_surat_masuk sm on ssm.no_surat=sm.no_surat where ds.diteruskan_kpd LIKE '%$jabatan%' and ds.proses='belum ditindak lanjuti'"); while($data = $query->fetch_array()){ ?> <tr> <td> <?php echo ($no) ?> </td> <td> <?php echo ($data["nomor_agenda"]) ?> </td> <td> <?php echo ($data["perihal"]) ?> </td> <td> <?php echo ($data["isi_ringkas"]) ?> </td> <td> <?php echo ($data["asal_surat"]) ?> </td> <td> <?php echo ($data["instruksi"]) ?> </td> <td> <a href='<?php echo "?page=detail_disposisi&no_surat=$data[no_surat]"; ?>' class="btn btn-success btn-sm">Detail</a> <a href='<?php echo "?page=tindak_lanjut_disposisi&no_surat=$data[no_surat]"; ?>' class="btn btn-primary btn-sm ">Proses</a> </td> </tr> <?php $no++; } ?> </tbody> </table> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><?php //Establishing Connection with Server by passing server_name, user_id and password as a parameter $host= ''; $username= ''; $database= ''; $password= ''; $mysqli = new mysqli($host, $username, $password, $database); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" .$mysqli->connect_errno .")" .$mysqli->connect_error; } ?><file_sep><section class="content-header"> <h1> Disposisi </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Disposisi</a> </li> <li class="active">Rekap Disposisi Surat</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Rekap Disposisi Surat</h3> </div> <!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table id="table_data" class="table table-striped table-hover"> <thead> <tr> <th>No</th> <th>Nomor Agenda</th> <th>Perihal</th> <th>Tgl Penyelesaian</th> <th>Instruksi</th> <th>Diteruskan Kepada</th> <th>Tindak Lanjut</th> <?php if ($level_user=="kpl") { ?> <th>Aksi</th> <?php }?> </tr> </thead> <tbody> <?php $no = 1; $query = $mysqli->query("SELECT sm.*,ssm.*,ds.* FROM tbl_disposisi_surat ds LEFT JOIN tbl_status_sm ssm ON ds.no_surat = ssm.no_surat LEFT JOIN tbl_surat_masuk sm on ssm.no_surat=sm.no_surat ORDER BY tanggal_penyelesaian"); while($data = $query->fetch_array()){ ?> <tr> <td> <?php echo ($no)?> </td> <td> <?php echo ($data["nomor_agenda"]) ?> </td> <td> <?php echo ($data["perihal"]) ?> </td> <td> <?php echo ($data["tanggal_penyelesaian"]) ?> </td> <td> <?php echo ($data["instruksi"]) ?> </td> <td> <?php echo ($data["diteruskan_kpd"]) ?> </td> <?php if ($data["proses"]=="belum ditindak lanjuti"){ $warna = "bg-red text-center"; } else { $warna = "bg-green text-center"; } ?> <td> <div class="<?php echo $warna;?>"> <?php echo ($data["proses"]) ?> </div> </td> <?php if ($level_user=="kpl") { ?> <td> <a href='<?php echo "?page=edit_disposisi&no_surat=$data[no_surat]"; ?>' class="btn btn-success btn-sm btn-block">edit</a> <!-- <a href="" class="btn btn-danger btn-sm">delete</a> --> </td> <?php }?> </tr> <?php $no++; } ?> </tbody> </table> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><?php $message='hide'; if ($_POST) { foreach($_POST AS $key => $value) { $_POST[$key] = $mysqli->real_escape_string($value); } $sql = "INSERT INTO `tbl_pengguna` ( `nip` , `password` , `nama_user` , `jabatan` , `level_user` ) VALUES( '{$_POST['nip']}' , '{$_POST['password']}' , '{$_POST['nama_user']}' , '{$_POST['jabatan']}' , '{$_POST['level_user']}' ) "; $mysqli->query($sql) or die($mysqli->error); $message='show'; } ?> <section class="content-header"> <h1> User </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">User</a> </li> <li class="active">Input User</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <h3 class="box-title">Input User</h3> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action=""> <div class="box-body"> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">NIP</label> <div class="col-sm-6"> <input type="text" class="form-control" id="inputPassword3" placeholder="NIP" name="nip" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Nama</label> <div class="col-sm-6"> <input type="text" class="form-control" id="inputPassword3" placeholder="Nama" name="nama_user" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-6"> <input type="text" class="form-control" id="inputPassword3" placeholder="<PASSWORD>" name="password" required> </div> </div> <div class="form-group"> <label for="<PASSWORD>" class="col-sm-2 control-label">Jabatan</label> <div class="col-sm-6"> <select class="form-control" data-live-search="true" id="slct2" data-size="5" name="jabatan" required> <option value="Waka SDM">Waka SDM</option> <option value="Waka Sarana">Waka Sarana</option> <option value="Waka Kesiswaan">Waka Kesiswaan</option> <option value="Waka HUBIN">Waka HUBIN</option> <option value="Waka Kurikulum">Waka Kurikulum</option> <option value="WMM">WMM</option> <option value="Persuratan">Persuratan</option> <option value="Kepala Sekolah">Kepala Sekolah</option> </select> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Level</label> <div class="col-sm-6"> <select class="form-control" data-live-search="true" id="slct3" data-size="5" name="level_user" required> <option value="wka">Wakil Kepala Sekolah</option> <option value="wka">Kepala Sekolah</option> <option value="wka">Persuratan</option> </select> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" class="btn btn-primary" value="Submit"> </div> </div> </div> </form> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><!-- jQuery 3 --> <script src="../assets/bower_components/jquery/dist/jquery.min.js"></script> <!-- jQuery UI 1.11.4 --> <script src="../assets/bower_components/jquery-ui/jquery-ui.min.js"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <!-- Bootstrap 3.3.7 --> <script src="../assets/bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- Select2 --> <script src="../assets/bower_components/select2/dist/js/select2.full.min.js"></script> <!-- daterangepicker --> <script src="../assets/bower_components/bootstrap-daterangepicker/daterangepicker.js"></script> <!-- datepicker --> <script src="../assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script> <!-- Bootstrap WYSIHTML5 --> <script src="../assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script> <!-- DataTables --> <script src="../assets/bower_components/datatables.net/js/jquery.dataTables.min.js"></script> <script src="../assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <!-- AdminLTE App --> <script src="../assets/dist/js/adminlte.min.js"></script> <!-- AdminLTE dashboard demo (This is only for demo purposes) --> <!-- <script src="../assets/dist/js/pages/dashboard.js"></script> --> <!-- AdminLTE for demo purposes --> <!-- <script src="../assets/dist/js/demo.js"></script> --> <script> $('.textarea').wysihtml5(); $('#table_data').DataTable(); $('.select2').select2(); $('#datepicker, #datepicker2').datepicker({ autoclose: true }); window.setTimeout(function () { $(".alert-message").fadeTo(500, 0).slideUp(500, function () { $(this).remove(); }); }, 2000); $('.kode-sm').change(function(){ var kode = $(this).val(); var currentTime = new Date(); var month = currentTime.getMonth() + 1; var year = currentTime.getFullYear(); var roman_month = romanize(month); var nomor_surat = $('.no-surat').text(); $('.nomor_agenda').val(nomor_surat+'/'+kode+'-SMKN.14/'+roman_month+'/'+year); }) function romanize (num) { if (!+num) return false; var digits = String(+num).split(""), key = ["","<KEY>", "","X","XX","XXX","XL","L","<KEY>", "","I","II","III","IV","V","VI","VII","VIII","IX"], roman = "", i = 3; while (i--) roman = (key[+digits.pop() + (i * 10)] || "") + roman; return Array(+digits.join("") + 1).join("M") + roman; } </script> </body> </html><file_sep><?php session_start(); $nip = $_SESSION['nip']; $nama_user = $_SESSION['nama_user']; $jabatan = $_SESSION['jabatan']; $level_user = $_SESSION['level_user']; $hari= date('Y-m-d'); include "../db.php"; include "header.php"; $res=$mysqli->query("SELECT count(status) as status FROM `tbl_status_sm` WHERE status ='undisposed'"); $row = $res->fetch_assoc(); $inboxsurat=$row['status']; $res1=$mysqli->query("SELECT count(status) as status FROM `tbl_status_sm` s LEFT JOIN tbl_disposisi_surat ds on ds.no_surat=s.no_surat WHERE diteruskan_kpd LIKE '%$jabatan%' and ds.proses='belum ditindak lanjuti' "); $row1 = $res1->fetch_assoc(); $inboxdisposisi=$row1['status']; switch ($level_user) { case 'pst': $res=$mysqli->query("SELECT count(no_surat) as status FROM `tbl_surat_masuk` "); $row = $res->fetch_assoc(); $inboxsurat=$row['status']; break; case 'kpl': $res=$mysqli->query("SELECT count(status) as status FROM `tbl_status_sm` WHERE status ='undisposed'"); $row = $res->fetch_assoc(); $inboxsurat=$row['status']; break; case 'wka': $res=$mysqli->query("SELECT count(status) as status FROM `tbl_status_sm` s LEFT JOIN tbl_disposisi_surat ds on ds.no_surat=s.no_surat WHERE diteruskan_kpd LIKE '%$jabatan%' and ds.proses='belum ditindak lanjuti' "); $row = $res->fetch_assoc(); $inboxsurat=$row['status']; default: # code... break; } ?> <body class="hold-transition skin-yellow sidebar-mini"> <div class="wrapper"> <header class="main-header"> <!-- Logo --> <a href="./" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><img src="../assets/img/logo.png" width='40px' height='40px'></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"> <img src="../assets/img/logo.png" width='40px' height='40px'> <b>SMKN</b>14 </span> </a> <!-- Header Navbar: style can be found in header.less --> <nav class="navbar navbar-static-top"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <img src="../assets/dist/img/avatar.png" class="user-image" alt="User Image"> <span class="hidden-xs"><?=$nama_user?></span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header"> <img src="../assets/dist/img/avatar.png" class="img-circle" alt="User Image"> <p> <?php echo "$nama_user - $jabatan"; ?> </p> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="text-center"> <a href="../logout.php" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <?php include "navbar.php" ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <?php if (!empty($_GET['page'])) { switch ($_GET['page']) { case 'surat': include "../menu/surat_masuk.php"; break; case 'input_surat': include "../menu/input_surat_masuk.php"; break; case 'edit_surat': include "../menu/edit_surat_masuk.php"; break; case 'rekap_surat': include "../menu/rekap_surat_masuk.php"; break; case 'disposisi': include "../menu/disposisi.php"; break; case 'input_disposisi': include "../menu/input_disposisi.php"; break; case 'edit_disposisi': include "../menu/edit_disposisi.php"; break; case 'rekap_disposisi': include "../menu/rekap_disposisi.php"; break; case 'detail_disposisi': include "../menu/detail_disposisi.php"; break; case 'tindak_lanjut_disposisi': include "../menu/tindak_lanjut_disposisi.php"; break; case 'user': include "../menu/user.php"; break; case 'input_user': include "../menu/input_user.php"; break; case 'edit_user': include "../menu/edit_user.php"; break; default: include "../menu/dashboard.php"; break; } }else { include "../menu/dashboard.php"; } ?> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <!-- <div class="pull-right hidden-xs"> <b>Version</b> 2.4.0 </div> <strong>Copyright &copy; 2014-2016 <a href="https://adminlte.io">Almsaeed Studio</a>.</strong> All rights reserved. --> </footer> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <?php include "footer.php" ?><file_sep><?php if($level_user!='wka'){ header("location: index.php"); } $message = 'hide'; $hari= date('Y-m-d'); $id=$_REQUEST['no_surat']; $edit = "SELECT sm. * , ssm. * , ds. * FROM tbl_disposisi_surat ds LEFT JOIN tbl_status_sm ssm ON ds.no_surat = ssm.no_surat LEFT JOIN tbl_surat_masuk sm ON ssm.no_surat = sm.no_surat WHERE ds.no_surat = '$id' "; $hasil = $mysqli->query($edit); $data = $hasil->fetch_array(); if ($_POST) { foreach($_POST AS $key => $value) { $_POST[$key] = $mysqli->real_escape_string($value); } $sql = "UPDATE `tbl_disposisi_surat` SET `tanggal_penyelesaian` = '{$_POST['tanggal_penyelesaian']}' , `proses` = '{$_POST['proses']}' WHERE `no_surat` = '$id' "; ; $mysqli->query($sql) or die($mysqli->error); $message = 'show'; } ?> <section class="content-header"> <h1> Disposisi </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Disposisi</a> </li> <li class="active">Tindak Lanjut Disposisi Surat</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4> <i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <h3 class="box-title">Tindak Lanjut Disposisi Surat</h3> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action=""> <div class="box-body"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Tgl Penyelesaian </label> <div class="col-sm-4"> <input type="text" class="form-control" id="datepicker" placeholder="Tanggal Penyelesaian" name="tanggal_penyelesaian" required data-date-format="yyyy-mm-dd" required value="<?php echo ($hari) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tindakan</label> <div class="col-sm-7"> <textarea class="form-control textarea" id="proses" placeholder="Tindakan" name="proses" required></textarea> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary pull-right">Submit</button> <a href="dash.php" class="btn btn-success">Inbox Surat</a> </div> </div> </div> </div> </form> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><?php $rekap_disposisi = 'show'; $input_surat = 'hide'; $input_user = 'hide'; $rekap_surat = 'hide'; $inbox_surat = 'hide'; $inbox_disposisi = 'hide'; $rekap_user = 'hide'; $status_surat = 'hide'; $status_user = 'hide'; $status_disposisi = 'hide'; switch ($level_user) { case 'pst': $status_surat = 'show'; $input_surat = 'show'; $rekap_surat = 'show'; $status_disposisi = 'show'; break; case 'kpl': $status_surat = 'show'; $inbox_surat = 'show'; $status_disposisi = 'show'; break; case 'wka': $status_disposisi = 'show'; $inbox_disposisi = 'show'; break; case 'akr': $status_user = 'show'; $input_user = 'show'; $rekap_user = 'show'; $status_surat = 'show'; $input_surat = 'show'; $rekap_surat = 'show'; $inbox_surat = 'show'; $status_disposisi = 'show'; $inbox_disposisi = 'show'; break; default: break; } ?> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="../assets/dist/img/avatar.png" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p><?=$nama_user?></p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <!-- sidebar menu: : style can be found in sidebar.less --> <ul class="sidebar-menu" data-widget="tree"> <li class="header">MAIN NAVIGATION</li> <li class="active"> <a href="index.php"> <i class="fa fa-dashboard"></i> <span> Dashboard</span> </a> </li> <li class="treeview"> <a href="#" class='<?=$status_surat?>'> <i class="fa fa-envelope"></i> <span>Surat Masuk</span> <span class="pull-right-container"> <small class="label pull-right bg-green"><?=$inboxsurat?></small> </span> </a> <ul class="treeview-menu"> <li class='<?=$inbox_surat?>'> <a href="index.php?page=surat"> <i class="fa fa-circle-o"></i> Inbox <span class="pull-right-container"> <small class="label pull-right bg-green"><?=$inboxsurat?></small> </span> </a> </li> <li class='<?=$input_surat?>'><a href="index.php?page=input_surat"><i class="fa fa-circle-o"></i> Input Surat Masuk</a></li> <li class='<?=$rekap_surat?>'><a href="index.php?page=rekap_surat"><i class="fa fa-circle-o"></i> Rekap Surat Masuk <small class="label pull-right bg-green"><?=$inboxsurat?></small></a></li> </ul> </li> <li class="treeview"> <a href="#" class='<?=$status_disposisi?>'> <i class="fa fa-envelope"></i> <span>Disposisi</span> <span class="pull-right-container"> <small class="label pull-right bg-green"></small> </span> </a> <ul class="treeview-menu"> <li class="<?=$inbox_disposisi?>"> <a href="index.php?page=disposisi"> <i class="fa fa-circle-o"></i> Inbox <span class="pull-right-container"> <small class="label pull-right bg-green"><?=$inboxsurat?></small> </span> </a> </li> <!-- <li><a href="index.php?page=input_disposisi"><i class="fa fa-circle-o"></i> Input Disposisi</a></li> --> <li class="<?=$rekap_disposisi?>"><a href="index.php?page=rekap_disposisi"><i class="fa fa-circle-o"></i> Rekap Disposisi Surat</a></li> </ul> </li> <li class="treeview"> <a href="#" class='<?=$status_user?>'> <i class="fa fa-envelope"></i> <span>User</span> </a> <ul class="treeview-menu"> <li class="<?=$rekap_user?>"> <a href="index.php?page=user"> <i class="fa fa-circle-o"></i> List User </a> </li> <li class="<?=$input_user?>"><a href="index.php?page=input_user"><i class="fa fa-circle-o"></i> Input User</a></li> </ul> </li> </ul> </section> <!-- /.sidebar --> </aside><file_sep># disposisi-surat incoming mail management on school ## Installation - change filename from `db.example.php` to `db.php` add your configuration - import `example.sql` to your database - install bower component with `bower install`<file_sep><?php $surat = 'hide'; $disposisi = 'hide'; $user = 'hide'; $col = 'col-lg-4 col-xs-6'; $link_surat = ''; $link_disposisi = ''; switch ($level_user) { case 'pst': $surat = 'show'; $disposisi = 'show'; $link_surat = '?page=rekap_surat'; $link_disposisi ='?page=rekap_disposisi'; break; case 'wka': $disposisi = 'show'; $link_surat = '?page=surat'; $link_disposisi ='?page=disposisi'; break; case 'kpl': $surat = 'show'; $disposisi = 'show'; $link_surat = '?page=surat'; $link_disposisi ='?page=rekap_disposisi'; break; default: # code... break; } ?> <section class="content-header"> <h1> Dashboard <small>Control panel</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Dashboard</li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Small boxes (Stat box) --> <div class="row"> <div class="<?=$col?> <?=$surat?>"> <!-- small box --> <div class="small-box bg-aqua"> <div class="inner"> <h3><?=$inboxsurat?></h3> <p>Surat Masuk</p> </div> <div class="icon"> <i class="ion ion-bag"></i> </div> <a href="<?=$link_surat?>" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a> </div> </div> <!-- ./col --> <div class="col-lg-4 col-xs-6 <?=$disposisi?>"> <!-- small box --> <div class="small-box bg-green"> <div class="inner"> <h3><?=$inboxdisposisi?></sup></h3> <p>Disposisi</p> </div> <div class="icon"> <i class="ion ion-stats-bars"></i> </div> <a href="<?=$link_disposisi?>" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a> </div> </div> <!-- ./col --> <div class="col-lg-4 col-xs-6 <?=$user?>"> <!-- small box --> <div class="small-box bg-yellow"> <div class="inner"> <?php $res = $mysqli->query("SELECT * FROM tbl_pengguna"); $user = $res->num_rows; ?> <h3><?=$user?></h3> <p>User </p> </div> <div class="icon"> <i class="ion ion-person-add"></i> </div> <a href="#" class="small-box-footer">More info <i class="fa fa-arrow-circle-right"></i></a> </div> </div> <!-- ./col --> </div> <!-- /.row --> <!-- Main row --> </section> <!-- /.content --> <file_sep><?php $message='hide'; if ($_REQUEST['edit'] ?? false) { $id=$_REQUEST['edit']; $edit = "select * from tbl_pengguna where nip='$id'"; $hasil = $mysqli->query($edit); $row = $hasil->fetch_array(); if ($_POST) { foreach($_POST AS $key => $value) { $_POST[$key] = $mysqli->real_escape_string($value); } $sql = "UPDATE `tbl_pengguna` SET `nama_user` = '{$_POST['nama_user']}' , `password` = '{$_POST['password']}' , `jabatan` = '{$_POST['jabatan']}' , `level_user` = '{$_POST['level_user']}' WHERE `nip` = '$id' "; $mysqli->query($sql) or die($mysqli->error); $message = 'show'; } } if ($_REQUEST['del'] ?? false ) { $id=$_REQUEST['del']; $mysqli->query("DELETE FROM `tbl_pengguna` WHERE `nip` = '$id' "); echo "<meta http-equiv='refresh' content='0; url=./'>"; } ?> <section class="content-header"> <h1> User </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">User</a> </li> <li class="active">Input User</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <h3 class="box-title">Input User</h3> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action=""> <div class="box-body"> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">NIP</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="NIP" name="nip" readonly value="<?= stripslashes($row['nip']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Nama</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Nama" name="nama_user" required value="<?= stripslashes($row['nama_user']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="*********" name="password" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Jabatan</label> <div class="col-sm-4"> <select class="form-control" data-live-search="true" id="slct2" data-size="5" name="jabatan" required> <option value="Waka SDM">Waka SDM</option> <option value="Waka Sarana">Waka Sarana</option> <option value="Waka Kesiswaan">Waka Kesiswaan</option> <option value="Waka HUBIN">Waka HUBIN</option> <option value="Waka Kurikulum">Waka Kurikulum</option> <option value="WMM">WMM</option> <option value="Persuratan">Persuratan</option> <option value="Kepala Sekolah">Kepala Sekolah</option> </select> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Level</label> <div class="col-sm-4"> <select class="form-control" data-live-search="true" id="slct3" data-size="5" name="level_user" required> <option value="wka">Wakil Kepala Sekolah</option> <option value="kpl">Kepala Sekolah</option> <option value="pst">Persuratan</option> </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type='hidden' value='1' name="edituser" /> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" class="btn btn-success pull-right" value="Edit"> <a href="./" class="btn btn-primary "> Dashboard </a> </div> </div> </div> </form> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><?php session_start();//starting session include("db.php"); $error=''; //variable to store error message if ($_POST) { if (empty($_POST['username']) || empty($_POST['password'])) { $error = "Username atau Password salah"; echo "<meta http-equiv='refresh' content='0; url=./'>"; } else { $username=$_POST['username']; $password=$_POST['<PASSWORD>']; $res = $mysqli->query("SELECT * from tbl_pengguna where password='$<PASSWORD>' AND nip='$username' "); $data = $res->fetch_array(); $rows = $res->num_rows; if ($rows == 1) { /** * session set */ $_SESSION['nip']=$data['nip']; $_SESSION['nama_user']=$data['nama_user']; $_SESSION['jabatan']=$data['jabatan']; $_SESSION['level_user']=$data['level_user']; echo "<meta http-equiv='refresh' content='0; url=layout/index.php'>"; } else { $error = "User Atau Password Salah"; echo "<meta http-equiv='refresh' content='0; url=./'>"; } } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.5.4.1deb2ubuntu2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: 01 Nov 2017 pada 20.51 -- Versi Server: 5.7.20-0ubuntu0.16.04.1 -- PHP Version: 7.1.11-1+ubuntu16.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `dispose` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `tbl_disposisi_surat` -- CREATE TABLE `tbl_disposisi_surat` ( `no_surat` varchar(100) NOT NULL, `tanggal_penyelesaian` date DEFAULT NULL, `tanggal_penerimaan` date DEFAULT NULL, `instruksi` text NOT NULL, `diteruskan_kpd` varchar(100) NOT NULL, `proses` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tbl_disposisi_surat` -- INSERT INTO `tbl_disposisi_surat` (`no_surat`, `tanggal_penyelesaian`, `tanggal_penerimaan`, `instruksi`, `diteruskan_kpd`, `proses`) VALUES ('1', '2017-11-01', NULL, 'palajari, adakan pertemuan tanggal 3 november 2017 pukul 09.00', 'Waka Kurikulum-Waka Kesiswaan-Waka Sarana', 'buatkan surat tugas untuk guru multimedia dan 10 siswa untuk mengikuti workshop tersebut.'), ('3', NULL, NULL, 'tindak lanjuti', 'Waka SDM', 'belum ditindak lanjuti'); -- -------------------------------------------------------- -- -- Struktur dari tabel `tbl_pengguna` -- CREATE TABLE `tbl_pengguna` ( `nip` varchar(20) NOT NULL, `password` varchar(50) NOT NULL, `nama_user` varchar(30) NOT NULL, `jabatan` varchar(20) NOT NULL, `level_user` varchar(3) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tbl_pengguna` -- INSERT INTO `tbl_pengguna` (`nip`, `password`, `nama_user`, `jabatan`, `level_user`) VALUES ('000', '123', 'Super Admin', 'admin', 'akr'), ('001', '123', 'B<NAME>adi, M.Sn', 'Kepala Sekolah', 'kpl'), ('002', '123', 'Yulian T.S. Karyat, Drs.', 'Waka Kurikulum', 'wka'), ('003', '123', '<NAME>, Drs. M.Ds.', 'Waka HUBIN', 'wka'), ('004', '123', 'Drs. <NAME>, S.Pd', 'Waka Kesiswaan', 'wka'), ('005', '123', 'Nana Sutejo, Drs.', 'Waka Sarana', 'wka'), ('006', '123', '<NAME>, Drs., M.Ds.', 'WMM', 'wka'), ('007', '123', 'Drs. D<NAME>', 'Waka SDM', 'wka'), ('008', '123', '<NAME> S., Dra.', 'Persuratan', 'pst'); -- -------------------------------------------------------- -- -- Struktur dari tabel `tbl_status_sm` -- CREATE TABLE `tbl_status_sm` ( `no_surat` int(5) NOT NULL, `tujuan` varchar(100) NOT NULL, `status` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tbl_status_sm` -- INSERT INTO `tbl_status_sm` (`no_surat`, `tujuan`, `status`) VALUES (1, 'Kepala Sekolah', 'disposed'), (2, 'Kepala Sekolah', 'undisposed'), (3, 'Kepala Sekolah', 'disposed'); -- -------------------------------------------------------- -- -- Struktur dari tabel `tbl_surat_masuk` -- CREATE TABLE `tbl_surat_masuk` ( `no_surat` int(5) NOT NULL, `kode_sm` varchar(20) NOT NULL, `nomor_agenda` varchar(100) NOT NULL, `perihal` text NOT NULL, `isi_ringkas` text NOT NULL, `asal_surat` varchar(100) NOT NULL, `tgl_sm` date NOT NULL, `lampiran` int(5) NOT NULL, `tgl_diteruskan` date NOT NULL, `nama_file` varchar(50) NOT NULL, `golongan_surat` varchar(20) NOT NULL, `pengolah` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tbl_surat_masuk` -- INSERT INTO `tbl_surat_masuk` (`no_surat`, `kode_sm`, `nomor_agenda`, `perihal`, `isi_ringkas`, `asal_surat`, `tgl_sm`, `lampiran`, `tgl_diteruskan`, `nama_file`, `golongan_surat`, `pengolah`) VALUES (1, '421.7', '1/421.7-SMKN.14/XI/2017', 'Penawaran Program Workshop', 'Pelaksanaan workshop desain grafis yang difasilitasi oleh pintar grafis, dilaksanakan tanpa biaya pungutan apapun (gratis). Sekolah hanya bertanggung jawab untuk menyiapkan waktu, tempat dan peserta workshop.', 'Pintar Grafis', '2017-11-01', 1, '2017-11-01', '1509527725_pintar grafis.jpg', 'Biasa', '<NAME> S., Dra.'), (2, '425', '2/425-SMKN.14/XI/2017', 'Penawaran Jasa Service Komputer dan Printer', 'Penawaran kerjasama maintenance komputer, printer dan pemasangan jaringan komputer', 'MSC Tarutung', '2017-11-01', 3, '2017-11-01', '1509530651_penawaran service.jpg', 'Penting', '<NAME> S., Dra.'), (3, '800', '3/800-SMKN.14/XI/2017', 'Pengunduran Diri', 'Pengajuan pengunduran diri Supardi S.Pd per tanggal 15 November 2017.', 'Supardi S.Pd', '2017-11-01', 0, '2017-11-01', '1509531280_pengunduran diri.jpg', 'Penting', '<NAME> S., Dra.'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_disposisi_surat` -- ALTER TABLE `tbl_disposisi_surat` ADD PRIMARY KEY (`no_surat`); -- -- Indexes for table `tbl_pengguna` -- ALTER TABLE `tbl_pengguna` ADD PRIMARY KEY (`nip`); -- -- Indexes for table `tbl_status_sm` -- ALTER TABLE `tbl_status_sm` ADD PRIMARY KEY (`no_surat`); -- -- Indexes for table `tbl_surat_masuk` -- ALTER TABLE `tbl_surat_masuk` ADD PRIMARY KEY (`no_surat`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_surat_masuk` -- ALTER TABLE `tbl_surat_masuk` MODIFY `no_surat` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;<file_sep><?php $id=$_REQUEST['no_surat']; $edit = "select * from tbl_surat_masuk where no_surat='$id'"; $hasil = $mysqli->query($edit); $data = $hasil->fetch_array(); $message = 'hide'; if(empty($level_user)){ header("location: index.php"); } $id=$_REQUEST['no_surat']; if ($level_user=="kpl") { $edit = " SELECT sm.*,ssm.* FROM tbl_surat_masuk sm LEFT JOIN tbl_status_sm ssm on ssm.no_surat=sm.no_surat where sm.no_surat = '$id' "; } if ($level_user=="wka") { $edit = "SELECT sm.*,ssm.*,ds.* FROM tbl_disposisi_surat ds LEFT JOIN tbl_status_sm ssm ON ds.no_surat = ssm.no_surat LEFT JOIN tbl_surat_masuk sm on ssm.no_surat=sm.no_surat where ds.no_surat = '$id' "; } $hasil = $mysqli->query($edit); $row = $hasil->fetch_array(); ?> <section class="content-header"> <h1> Surat Masuk </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Surat Masuk</a> </li> <li class="active">Input Surat Masuk</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4> <i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <h3 class="box-title">Input Surat Masuk</h3> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action=""> <div class="box-body"> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Kode Surat</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Kode Surat" name="kode_sm" required value="<?= stripslashes($row['kode_sm']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Golongan Surat</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="G<NAME>at" name="golongan_surat" required value="<?= stripslashes($row['golongan_surat']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Nomor Agenda</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Nom<NAME>" name="nomor_agenda" required value="<?= stripslashes($row['nomor_agenda']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Perihal</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Perihal" name="perihal" required value="<?= stripslashes($row['perihal']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Isi Ringkas</label> <div class="col-sm-7"> <textarea class="form-control " id="inputPassword3" placeholder="<NAME>" name="isi_ringkas" required rows="5" readonly><?= stripslashes($row['isi_ringkas']) ?> </textarea> </div> </div> <?php if ($level_user=="wka"): ?> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Instruksi</label> <div class="col-sm-7"> <textarea class="form-control textarea" id="inputPassword3" placeholder="Instruksi" name="instruksi" required rows="5" readonly><?= stripslashes($row['instruksi']) ?> </textarea> </div> </div> <?php endif ?> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Asal Surat</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="<NAME>" name="asal_surat" required value="<?= stripslashes($row['asal_surat']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tanggal Diterima</label> <div class="col-sm-4"> <input type="text" class="form-control" placeholder="Tanggal" autocomplete="off" name="tgl_sm" data-date-format="yyyy-mm-dd" required value="<?= stripslashes($row['tgl_sm']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Jumlah Lampiran</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Lampiran" name="lampiran" value="<?= stripslashes($row['lampiran']) ?>" readonly> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tanggal Diteruskan</label> <div class="col-sm-4"> <input type="text" id="datepicker" class="form-control" placeholder="Tanggal Diteruskan" autocomplete="off" name="tgl_diteruskan" data-date-format="yyyy-mm-dd" required value="<?= stripslashes($row['tgl_diteruskan']) ?>" readonly> </div> </div> <div class="form-group"> <label for="input<PASSWORD>3" class="col-sm-2 control-label">File Permohonan</label> <div class="col-sm-4"> <a href="<?php echo "../file-sm/$row[nama_file] ";?>" class="btn btn-warning example1demo">File Surat</a> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <a href="?page=surat" class="btn btn-success ">Inbox Surat</a> <?php if ($level_user =="kpl") { ?> <a href= '<?php echo "?page=input_disposisit&no_surat=$row[no_surat]"; ?>' class="btn btn-primary pull-right"> Disposisi </a> <?php } ?> <?php if ($level_user =="wka") { ?> <a href= '<?php echo "?page=tindak_lanjut_disposisi&no_surat=$row[no_surat]"; ?>' class="btn btn-primary pull-right"> Tindak Lanjut </a> <?php } ?> </div> </div> </div> </div> </form> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><?php $id=$_REQUEST['no_surat']; $edit = "select * from tbl_surat_masuk where no_surat='$id'"; $hasil = $mysqli->query($edit); $data = $hasil->fetch_array(); $message = 'hide'; if ($_POST) { $wak=$_POST['diteruskan_kpd']; $imp=implode("-", $wak); foreach($_POST AS $key => $value) { $_POST[$key] =$value; } $sql = "INSERT INTO `tbl_disposisi_surat` ( `no_surat` , `instruksi` , `diteruskan_kpd`, `proses`) VALUES( '{$_POST['no_surat']}', '{$_POST['instruksi']}', '$imp', 'belum ditindak lanjuti')"; $sql1 = " UPDATE `tbl_status_sm` SET `status`='disposed' where `no_surat`='$id' "; $mysqli->query($sql) or die($mysqli->error); $mysqli->query($sql1) or die($mysqli->error); $message = 'show'; } ?> <section class="content-header"> <h1> Disposisi </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Disposisi</a> </li> <li class="active">Input Disposisi</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4> <i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <h3 class="box-title">Input Disposisi</h3> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action=""> <div class="box-body"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">No Agenda Surat </label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputEmail3" placeholder="No Surat" value=<?php echo ($data[ "nomor_agenda"]) ?> readonly name="no_agenda"> <input type="hidden" class="form-control" id="inputEmail3" placeholder="No Surat" value=<?php echo ($data[ "no_surat"]) ?> readonly name="no_surat"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Instruksi</label> <div class="col-sm-7"> <textarea class="form-control textarea" id="instruksi" placeholder="Instruksi" name="instruksi" required></textarea> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Diteruskan Kepada</label> <div class="col-sm-4"> <select class="form-control select2" data-live-search="true" data-size="5" multiple name="diteruskan_kpd[]"> <?php $query = $mysqli->query("SELECT * FROM tbl_pengguna WHERE level_user='wka'"); while($data=$query->fetch_array()): ?> <option value="<?=$data['jabatan']?>"><?=$data['jabatan']?></option> <?php endwhile;?> </select> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary pull-right">Submit</button> <a href="dash.php" class="btn btn-success">Inbox Surat</a> </div> </div> </div> </div> </form> </div> <!-- /.box --> </div> </section><file_sep><?php $kode_surats = array ( "0|Pilih Kode Surat", "800|kepegawaian", "900|keuangan", "420|PENDIDIKAN", "421|Sekolah", "421.1|Pra Sekolah", "421.2|Sekolah Dasar", "421.3|Sekolah Menengah", "421.4|Sekolah Tinggi", "421.5|Sekolah Kejuruan", "421.6|Kegiatan Sekolah, Dies Natalis Lustrum", "421.7|Kegiatan Pelajar", "421.71|Reuni Darmawisata", "421.72|Pelajar Teladan", "421.73|Resimen Mahasiswa", "421.8|Sekolah Pendidikan Luar Biasa", "421.9|Pendidikan Luar Sekolah / Pemberantasan Buta Huruf", "422|Administrasi Sekolah", "422.1|Persyaratan Masuk Sekolah, Testing, Ujian, Pendaftaran, Mapras, Perpeloncoan", "422.2|Tahun Pelajaran", "422.3|Hari Libur", "422.4|Uang Sekolah, Klasifikasi Disini SPP", "422.5|Beasiswa", "423|Metode Belajar", "423.1|Kuliah", "423.2|Ceramah, Simposium", "423.3|Diskusi", "423.4|Kuliah Lapangan, Widyawisata, KKN, Studi Tur", "423.5|Kurikulum", "423.6|Karya Tulis", "423.7|Ujian", "424|Tenaga Pengajar, Guru, Dosen, Dekan, Rektor", "425|Sarana Pendidikan", "425.1|Gedung", "425.11|Gedung Sekolah", "425.12|Kampus", "425.13|Pusat Kegiatan Mahasiswa", "425.2|Buku", "425.3|Perlengkapan Sekolah "); $message = 'hide'; if ($_POST) { $lokasi_file=$_FILES['nama_file']['tmp_name']; $nama_file=$_FILES['nama_file']['name']; $tipe = explode(".",$nama_file); $nn=time(); $nama_baru = $nn."_".$tipe[0].".".$tipe[1]; move_uploaded_file($lokasi_file,"../file-sm/$nama_baru"); foreach($_POST AS $key => $value) { $_POST[$key] = $mysqli->real_escape_string($value); } $sql = "INSERT INTO `tbl_surat_masuk` ( `kode_sm` , `nomor_agenda` , `perihal` , `isi_ringkas` , `asal_surat` , `tgl_sm` , `lampiran` , `tgl_diteruskan` , `nama_file` , `golongan_surat` , `pengolah` ) VALUES( '{$_POST['kode_sm']}' , '{$_POST['nomor_agenda']}' , '{$_POST['perihal']}' , '{$_POST['isi_ringkas']}' , '{$_POST['asal_surat']}' , '{$_POST['tgl_sm']}' , '{$_POST['lampiran']}' , '{$_POST['tgl_diteruskan']}', '$nama_baru', '{$_POST['golongan_surat']}' , '{$_POST['pengolah']}' ) "; $sql1 = "INSERT INTO `tbl_status_sm` ( `no_surat`, `tujuan`, `status`) VALUES ( LAST_INSERT_ID(), 'Kepala Sekolah', 'undisposed')"; $mysqli->query($sql) or die($mysqli->error); $mysqli->query($sql1) or die($mysqli->error); $message = "show"; } ?> <section class="content-header"> <h1> Surat Masuk </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Surat Masuk</a> </li> <li class="active">Input Surat Masuk</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4><i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <?php $query = $mysqli->query("SELECT * FROM tbl_surat_masuk"); $nomor_surat = $query->num_rows+1; ?> <h3 class="box-title">Input Surat Masuk</h3> <div class="no-surat hide"><?php echo $nomor_surat ?></div> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action="" enctype="multipart/form-data"> <div class="box-body"> <div class="form-group"> <label for="<PASSWORD>" class="col-sm-2 control-label">Kode Surat</label> <div class="col-sm-4"> <select name="kode_sm" data-size="5" class="form-control select2 kode-sm" data-live-search="true"> <?php foreach ($kode_surats as $kode_surat) : ?> <?php $kode_surat = explode('|',$kode_surat) ?> <option value="<?=$kode_surat[0]?>"><?=$kode_surat[0].' - '.$kode_surat[1] ?></option> <?php endforeach; ?> </select> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Golongan Surat</label> <div class="col-sm-4"> <select class="form-control" data-live-search="true" id="slct" data-size="5" name="golongan_surat" required> <option value="Biasa">Biasa</option> <option value="Penting">Penting</option> <option value="Rahasia">Rahasia</option> <option value="Sangat Rahasia">Sangat Rahasia</option> </select> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Nomor Agenda</label> <div class="col-sm-4"> <input type="text" class="form-control nomor_agenda" id="inputPassword3" placeholder="<NAME>" name="nomor_agenda" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Perihal</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Perihal" name="perihal" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Isi Ringkas</label> <div class="col-sm-7"> <textarea class="form-control textarea" id="inputPassword3" placeholder="<NAME>" name="isi_ringkas" required></textarea> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Asal Surat</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="As<NAME>" name="asal_surat" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tanggal Diterima</label> <div class="col-sm-4"> <input type="text" class="form-control" id="datepicker" placeholder="Tanggal" autocomplete="off" name="tgl_sm" data-date-format="yyyy-mm-dd" required value="<?php echo ($hari) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Jumlah Lampiran</label> <div class="col-sm-4 "> <input type="text" class="form-control" id="inputPassword3" placeholder="Jumlah Lembar" name="lampiran"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tanggal Diteruskan</label> <div class="col-sm-4"> <input type="text" class="form-control" id="datepicker2" placeholder="Tanggal Diteruskan" autocomplete="off" name="tgl_diteruskan" data-date-format="yyyy-mm-dd" required> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">File Surat Masuk</label> <div class="col-sm-4"> <input type="file" class="form-control" placeholder="File Surat Masuk" name="nama_file"> </div> </div> <div class="form-group"> <label for="input<PASSWORD>" class="col-sm-2 control-label">Pengolah</label> <div class="col-sm-4"> <input type="text" class="form-control" placeholder="Pengolah" value="<?php echo ($nama_user) ?>" readonly name="pengolah"> </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" class="btn btn-primary" value="Submit"> <input type='hidden' value='1' name="inputsurat" /> </div> </div> </div> </form> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section><file_sep><section class="content-header"> <h1> Surat Masuk </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Surat Masuk</a> </li> <li class="active">Rekap Surat Masuk</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Rekap Surat Masuk</h3> </div> <!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table id="table_data" class="table table-striped table-hover"> <thead> <tr> <th>No</th> <th>Nomor Agenda</th> <th>Perihal</th> <th>Isi Ringkas</th> <th>Asal Surat</th> <th>Status</th> <th>Aksi</th> </tr> </thead> <tbody> <?php $no = 1; $query = $mysqli->query("SELECT * FROM tbl_surat_masuk sm LEFT JOIN tbl_status_sm ssm ON sm.`no_surat` = ssm.`no_surat` ORDER BY sm.no_surat DESC"); while($data = $query->fetch_array()){ ?> <tr> <td> <?php echo ($no) ?> </td> <td> <?php echo ($data["nomor_agenda"]) ?> </td> <td> <?php echo ($data["perihal"]) ?> </td> <td> <?php echo ($data["isi_ringkas"]) ?> </td> <td> <?php echo ($data["asal_surat"]) ?> </td> <?php if ($data["status"]=="disposed"){ $warna = "bg-primary"; } else { $warna = "bg-danger"; } ?> <td> <p class="<?php echo ($warna) ?> text-center"> <?php echo ($data["status"]) ?> </p> </td> <td> <a href= '<?php echo "?page=edit_surat&no_surat=$data[no_surat]"; ?>' class="btn btn-success btn-sm btn-block">edit</a> </td> </tr> <?php $no++; } ?> </tbody> </table> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <file_sep><?php $message = 'hide'; $id=$_REQUEST['no_surat']; $edit = "select * from tbl_surat_masuk where no_surat='$id'"; $hasil = $mysqli->query($edit); $row = $hasil->fetch_array(); if ($_POST) { foreach($_POST AS $key => $value) { $_POST[$key] = $mysqli->real_escape_string($value); } $sql = "UPDATE `tbl_surat_masuk` SET `kode_sm` = '{$_POST['kode_sm']}' , `nomor_agenda` = '{$_POST['nomor_agenda']}' , `perihal` = '{$_POST['perihal']}' , `isi_ringkas` = '{$_POST['isi_ringkas']}' , `asal_surat` = '{$_POST['asal_surat']}' , `tgl_sm` = '{$_POST['tgl_sm']}' , `lampiran` = '{$_POST['lampiran']}' , `tgl_diteruskan` = '{$_POST['tgl_diteruskan']}' , `golongan_surat` = '{$_POST['golongan_surat']}' WHERE `no_surat` = $id "; $mysqli->query($sql) or die($mysqli->error); $message = 'show'; } ?> <section class="content-header"> <h1> Surat Masuk </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Surat Masuk</a> </li> <li class="active">Input Surat Masuk</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <div class="alert alert-success alert-dismissible alert-message <?=$message?>"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h4> <i class="icon fa fa-check"></i> Sukses!</h4> Data berhasil disimpan </div> <h3 class="box-title">Input Surat Masuk</h3> </div> <!-- /.box-header --> <form class="form-horizontal" role="form" method="POST" action=""> <div class="box-body"> <input type='hidden' name='no_surat' value='<?= $id ?>' /> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Kode Surat</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Kode Surat" name="kode_sm" required value="<?= stripslashes($row['kode_sm']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Golongan Surat</label> <div class="col-sm-4"> <select class="form-control" data-live-search="true" id="slct" data-size="5" name="golongan_surat" required> <option value="Biasa">Biasa</option> <option value="Penting">Penting</option> <option value="Rahasia">Rahasia</option> <option value="Sangat Rahasia">Sangat Rahasia</option> </select> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Nomor Agenda</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Nomor Agenda" name="nomor_agenda" required value="<?= stripslashes($row['nomor_agenda']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Perihal</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Perihal" name="perihal" required value="<?= stripslashes($row['perihal']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Isi Ringkas</label> <div class="col-sm-7"> <textarea class="form-control textarea" id="inputPassword3" placeholder="<NAME>" name="isi_ringkas" required rows="5"><?= stripslashes($row['isi_ringkas']) ?></textarea> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Asal Surat</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="<NAME>" name="asal_surat" required value="<?= stripslashes($row['asal_surat']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tanggal Diterima</label> <div class="col-sm-4"> <input type="text" class="form-control" id="datepicker" placeholder="Tanggal" autocomplete="off" name="tgl_sm" data-date-format="yyyy-mm-dd" required value="<?= stripslashes($row['tgl_sm']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Jumlah Lampiran</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Lampiran" name="lampiran" value="<?= stripslashes($row['lampiran']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Tanggal Diteruskan</label> <div class="col-sm-4"> <input type="text" class="form-control" id="datepicker2" placeholder="Tanggal Diteruskan" autocomplete="off" name="tgl_diteruskan" data-date-format="yyyy-mm-dd" required value="<?= stripslashes($row['tgl_diteruskan']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">File Permohonan</label> <div class="col-sm-4"> <input type="file" class="form-control" id="inputPassword3" placeholder="Password" value="<?= stripslashes($row['perihal']) ?>"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Pegolah</label> <div class="col-sm-4"> <input type="text" class="form-control" id="inputPassword3" placeholder="Pengolah" value="<?= stripslashes($row['pengolah']) ?>" readonly name="pengolah" > </div> </div> </div> <!-- /.box-body --> <div class="box-footer"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary pull-right">Submit</button> <a href="dash.php" class="btn btn-success">Inbox Surat</a> </div> </div> </div> </div> </form> </div> <!-- /.box --> </div> </section><file_sep><section class="content-header"> <h1> Surat Masuk </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-dashboard"></i> Home</a> </li> <li> <a href="#">Surat Masuk</a> </li> <li class="active">Inbox</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">Inbox Surat Masuk</h3> </div> <!-- /.box-header --> <div class="box-body"> <div class="table-responsive"> <table id="table_data" class="table table-striped table-hover"> <thead> <tr> <th>No</th> <th>Nomor Agenda</th> <th>Perihal</th> <th>Isi Ringkas</th> <th>Asal Surat</th> <th>Golongan Surat</th> <th>Aksi</th> </tr> </thead> <tbody> <?php $no = 1; $query = $mysqli->query("SELECT * FROM tbl_surat_masuk LEFT JOIN tbl_status_sm ON tbl_surat_masuk.`no_surat` = tbl_status_sm.`no_surat`where tbl_status_sm.`status` = 'undisposed' ORDER BY tbl_surat_masuk.`tgl_sm` DESC "); while($data = $query->fetch_array()){ ?> <tr> <td width="2%"> <?php echo ($no) ?> </td> <td> <?php echo ($data["nomor_agenda"]) ?> </td> <td> <?php echo ($data["perihal"]) ?> </td> <td> <?php echo ($data["isi_ringkas"]) ?> </td> <td> <?php echo ($data["asal_surat"]) ?> </td> <?php if ($data["golongan_surat"]=="Biasa"){ $warna = "bg-primary"; } else if ($data["golongan_surat"]=="Penting") { $warna = "bg-success"; } else if ($data["golongan_surat"]=="Rahasia") { $warna = "bg-warning"; } else { $warna ="bg-danger"; } ?> <td> <p class="<?php echo ($warna) ?> text-center"> <?php echo ($data["golongan_surat"]) ?> </p> </td> <td> <a href= <?php echo "?page=detail_disposisi&no_surat=$data[no_surat]"; ?> class="btn btn-success btn-sm"> detail </a> <a href= <?php echo "?page=input_disposisi&no_surat=$data[no_surat]"; ?> class="btn btn-primary btn-sm"> disposisi </a> </td> </tr> <?php $no++; } ?> </tbody> </table> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section>
889e2ecc5d13c02e0fafbb97da0fcbcb8824db4e
[ "Markdown", "SQL", "PHP" ]
19
PHP
octaxri/disposisi-surat
14fba26d89dbc8a9fe8bd7abf34669c4bf65998d
d0ff7c5caabecdd412c44ec7dc122adec4da8979
refs/heads/main
<repo_name>somnathdash/PUll4<file_sep>/code_4.cpp #include<bits/stdc++.h> #define pb push_back // #define int long long #define ll long long #define all(x) x.begin(),x.end() #define pii pair<int,int> #define vi vector<int> #define FOR(i,n) for(int i=0;i<n;i++) #define inf (ll) (9e18) #define sp(x , y) fixed << setprecision(y) << x #define mk(arr , n , type) type *arr = new type[n]; #define mar(arr , n , type) type arr[n]; #define w(x) ll x; cin >> x; while(x--) #define f(i,n) for(ll i = 0 ; i < n ; i++) #define ub(a , b) upper_bound(all(a) , b) #define lb(a , b) lower_bound(all(a) , b) #define MOD 1000000007 #define fi first #define se second using namespace std; int main() { w(t) { ll r,c,x; cin>>r>>c>>x; ll a[r+1][c+1]={0}; ll b[r+1][c+1]={0}; ll sa=0,sb=0; f(i,r) { f(j,c) { cin>>a[i][j]; } } f(i,r) { f(j,c) { cin>>b[i][j]; } } f(i,r) { f(j,c) { if((a[i][j]-b[i][j])!=0) { ll s=a[i][j]-b[i][j]; if(i+x<=r) { for(ll k=i;k<i+x;k++) { a[k][j]-=s; } } else if(j+x<=c) { for(ll k=j;k<j+x;k++) { a[i][k]-=s; } } } } } sa=0; f(i,r) { f(j,c) { // cout<<a[i][j]<<" "<<b[i][j]<<" "; if(a[i][j]!=b[i][j]) {sa=1; break;} } //cout<<"\n"; } //cout<<sa<<"\n"; if(sa==0) { cout<<"Yes\n"; } else cout<<"No\n"; } } <file_sep>/README.md # PUll4 https://www.codechef.com/MARCH21B/problems/CONSADD
0da3ea547c6907227365ad2effc8cdc18a1b2e87
[ "Markdown", "C++" ]
2
C++
somnathdash/PUll4
2b90e4b1042dd8a1efa1d3d3bdc564ed9cf8bfa5
7497d66f8565a6895e08582db1485201585d39d0
refs/heads/master
<file_sep>package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" appsv1 "k8s.io/api/apps/v1" "strings" ) const ( username = "root" password = "<PASSWORD>" ip = "127.0.0.1" port = "30944" dbName = "RUNOOB" ) var DB *sql.DB func InitDB() error { path := strings.Join([]string{username, ":", password, "@tcp(", ip, ":", port, ")/", dbName, "?charset=utf8"}, "") DB, _ = sql.Open("mysql", path) DB.SetConnMaxLifetime(100) DB.SetMaxIdleConns(10) if err := DB.Ping(); err != nil { fmt.Printf("opon database fail: %v\n", err) return err } fmt.Println("connnect success") return nil } func InserDeployment(dp *appsv1.Deployment) bool { tx, err := DB.Begin() if err != nil { fmt.Println("tx fail") return false } stmt, err := tx.Prepare("INSERT INTO deployment_test (`deployment_name`, `deployment_namespace`, `desired_replicas`, `ready_replicas`) VALUES (?, ?, ?, ?)") if err != nil { fmt.Println("Prepare fail") return false } res, err := stmt.Exec(dp.Name, dp.Namespace, dp.Spec.Replicas, dp.Status.ReadyReplicas) if err != nil { fmt.Println("Exec fail") return false } tx.Commit() fmt.Println(res.LastInsertId()) return true } func UpdateDeployment(dp *appsv1.Deployment) bool { tx, err := DB.Begin() if err != nil { fmt.Println("tx fail") } stmt, err := tx.Prepare("UPDATE deployment_test SET desired_replicas = ? , ready_replicas = ? WHERE deployment_name = ?") if err != nil { fmt.Println("Prepare fail") return false } res, err := stmt.Exec(dp.Spec.Replicas, dp.Status.ReadyReplicas, dp.Name) if err != nil { fmt.Println("Exec fail") return false } tx.Commit() fmt.Println(res.LastInsertId()) return true } func DeleteDeployment(key string) bool { strs := strings.Split(key, "/") name := strs[1] tx, err := DB.Begin() if err != nil { fmt.Println("tx fail") } fmt.Println("The key is:", name) stmt, err := tx.Prepare("DELETE FROM deployment_test WHERE deployment_name = ?") if err != nil { fmt.Println("Prepare fail") return false } res, err := stmt.Exec(name) if err != nil { fmt.Println("Exec fail") return false } tx.Commit() fmt.Println(res.LastInsertId()) return true } <file_sep>package main import ( "fmt" "time" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" appsinformers "k8s.io/client-go/informers/apps/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" appslisters "k8s.io/client-go/listers/apps/v1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/workqueue" "k8s.io/klog" ) const controllerAgentName = "deployment-controller" type Delta struct { key string event string } type Controller struct { kubeclientset kubernetes.Interface deploymentsLister appslisters.DeploymentLister deploymentsSynced cache.InformerSynced workqueue workqueue.RateLimitingInterface recorder record.EventRecorder } func NewController( kubeclientset kubernetes.Interface, deploymentInformer appsinformers.DeploymentInformer) *Controller { klog.V(4).Info("Creating event broadcaster") eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(klog.Infof) eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events("")}) recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName}) controller := &Controller{ kubeclientset: kubeclientset, deploymentsLister: deploymentInformer.Lister(), deploymentsSynced: deploymentInformer.Informer().HasSynced, workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Foos"), recorder: recorder, } klog.Info("Setting up event handlers") deploymentInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: controller.handleAdd, UpdateFunc: func(old, new interface{}) { newDepl := new.(*appsv1.Deployment) oldDepl := old.(*appsv1.Deployment) if newDepl.ResourceVersion == oldDepl.ResourceVersion { return } controller.handleUpdate(new) }, DeleteFunc: controller.handleDelete, }) return controller } func (c *Controller) handleAdd(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { utilruntime.HandleError(err) return } d := Delta{key: key, event: "Add"} c.workqueue.Add(d) } func (c *Controller) handleUpdate(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { utilruntime.HandleError(err) return } d := Delta{key: key, event: "Update"} c.workqueue.Add(d) } func (c *Controller) handleDelete(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { utilruntime.HandleError(err) return } d := Delta{key: key, event: "Delete"} c.workqueue.Add(d) } func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { defer utilruntime.HandleCrash() defer c.workqueue.ShutDown() // Start the informer factories to begin populating the informer caches klog.Info("Starting Foo controller") // Wait for the caches to be synced before starting workers klog.Info("Waiting for informer caches to sync") if ok := cache.WaitForCacheSync(stopCh, c.deploymentsSynced); !ok { return fmt.Errorf("failed to wait for caches to sync") } klog.Info("Starting workers") // Launch two workers to process Foo resources for i := 0; i < threadiness; i++ { go wait.Until(c.runWorker, time.Second, stopCh) } klog.Info("Started workers") <-stopCh klog.Info("Shutting down workers") return nil } func (c *Controller) runWorker() { for c.processNextWorkItem() { } } func (c *Controller) processNextWorkItem() bool { obj, shutdown := c.workqueue.Get() if shutdown { return false } err := func(obj interface{}) error { defer c.workqueue.Done(obj) // handle logic var d Delta var ok bool if d, ok = obj.(Delta); !ok { c.workqueue.Forget(obj) utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) return nil } namespace, name, err := cache.SplitMetaNamespaceKey(d.key) if err != nil { utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", d.key)) return nil } dp, err := c.deploymentsLister.Deployments(namespace).Get(name) if err != nil && d.event != "Delete" { if errors.IsNotFound(err) { utilruntime.HandleError(fmt.Errorf("deployment '%s' in work queue no longer exists", d.key)) return nil } return err } if dp != nil { fmt.Println("This is the output", dp.Name, dp.Status.ReadyReplicas, dp.Status.Replicas, dp.Namespace) if d.event == "Add" { InserDeployment(dp) } else if d.event == "Update" { UpdateDeployment(dp) } } else { DeleteDeployment(d.key) } c.workqueue.Forget(obj) klog.Infof("Successfully synced") return nil }(obj) if err != nil { utilruntime.HandleError(err) return true } return true } <file_sep># deployment-controller Deployment controller 目前的功能是同步数据到MySQL
089558f3b1ae4e566737a6450154bab04e2a01d8
[ "Markdown", "Go" ]
3
Go
zhouya0/deployment-controller
68bdb998f65bf85b7c8ed7991c134cfd8f41ed00
2db000920ec6bd519a8b6c6bcba16b138957fa67
refs/heads/master
<repo_name>organizations-loops/SR_2020<file_sep>/main.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- import os import argparse from solver import Solver from data_loader import get_loader from torch.backends import cudnn def str2bool(v): return v.lower() in ('true') def main(config): # For fast training. cudnn.benchmark = True # Create directories if not exist. if not os.path.exists(config.log_dir): os.makedirs(config.log_dir) if not os.path.exists(config.model_save_dir): os.makedirs(config.model_save_dir) if not os.path.exists(config.sample_dir): os.makedirs(config.sample_dir) if not os.path.exists(config.result_dir): os.makedirs(config.result_dir) # Data loader. celeba_loader = get_loader(config.celeba_image_dir, config.attr_path, config.selected_attrs, config.image_size, config.magnification, config.batch_size, config.dataset, config.mode, config.num_workers) # Solver for training and testing our networks. solver = Solver(celeba_loader, config) if config.mode == 'train': solver.train() elif config.mode == 'test': solver.test() if __name__ == '__main__': parser = argparse.ArgumentParser() # Model configuration. parser.add_argument('--c_dim', type=int, default=4, help='dimension of domain labels (1st dataset)') parser.add_argument('--image_size', type=int, default=128, help='output image resolution') parser.add_argument('--magnification', type=int, default=4, choices=[2, 4, 8, 16], help='image magnification scale') parser.add_argument('--tg_conv_dim', type=int, default=64, help='number of conv filters in the first layer of T_G') parser.add_argument('--td_conv_dim', type=int, default=64, help='number of conv filters in the first layer of T_D') parser.add_argument('--tg_repeat_num', type=int, default=6, help='number of residual blocks in TG') parser.add_argument('--td_repeat_num', type=int, default=6, help='number of strided conv layers in TD') parser.add_argument('--lambda_cls', type=float, default=1, help='weight for domain classification loss') parser.add_argument('--lambda_rec', type=float, default=10, help='weight for reconstruction loss') parser.add_argument('--lambda_gp', type=float, default=10, help='weight for gradient penalty') # Training configuration. parser.add_argument('--dataset', type=str, default='CelebA', choices=['CelebA'], help='dataset is CelebA') parser.add_argument('--batch_size', type=int, default=16, help='mini-batch size') parser.add_argument('--num_iters', type=int, default=300000, help='number of total iterations for training T_D') parser.add_argument('--num_iters_decay', type=int, default=100000, help='number of iterations for decaying lr') parser.add_argument('--tg_lr', type=float, default=1e-4, help='learning rate for T_G') parser.add_argument('--td_lr', type=float, default=1e-4, help='learning rate for T_D') parser.add_argument('--eg_lr', type=float, default=1e-4, help='learning rate for E_G') parser.add_argument('--edc_lr', type=float, default=1e-4, help='learning rate for E_Dc') parser.add_argument('--edt_lr', type=float, default=1e-4, help='learning rate for E_Dt') parser.add_argument('--tv_weight', type=float, default=10, help='tv_loss weight') parser.add_argument('--n_critic', type=int, default=5, help='number of T_D updates per each T_G update') parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for Adam optimizer') parser.add_argument('--beta2', type=float, default=0.999, help='beta2 for Adam optimizer') parser.add_argument('--resume_iters', type=int, default=None, help='resume training from this step') parser.add_argument('--selected_attrs', '--list', nargs='+', help='selected attributes for the CelebA dataset', default=['Male', 'Mustache', 'Big_Nose', 'Mouth_Slightly_Open']) # default=['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Male', 'Young'] # default=['Male', 'Young', 'Bags_Under_Eyes', 'Heavy_Makeup', 'No_Beard', '5_o_Clock_Shadow', 'Mustache', 'Pointy_Nose', 'Big_Nose', 'Blurry', 'Narrow_Eyes', 'Eyeglasses', 'Smiling', 'Mouth_Slightly_Open'] # Test configuration. parser.add_argument('--test_iters', type=int, default=300000, help='test model from this step') # Miscellaneous. parser.add_argument('--num_workers', type=int, default=1) parser.add_argument('--mode', type=str, default='train', choices=['train', 'test']) parser.add_argument('--use_tensorboard', type=str2bool, default=True) # Directories. parser.add_argument('--celeba_image_dir', type=str, default='/media/limy/新加卷1/Datasets/Faces/CelebA/Celeba-HQ/celeba-128') parser.add_argument('--attr_path', type=str, default='/media/limy/新加卷1/Datasets/Faces/CelebA/Anno/list_attr_celebahq.txt') parser.add_argument('--log_dir', type=str, default='stargan/logs') parser.add_argument('--model_save_dir', type=str, default='stargan/models') parser.add_argument('--sample_dir', type=str, default='stargan/samples') parser.add_argument('--result_dir', type=str, default='stargan/results') # Step size. parser.add_argument('--log_step', type=int, default=10) parser.add_argument('--sample_step', type=int, default=1000) parser.add_argument('--model_save_step', type=int, default=10000) parser.add_argument('--lr_update_step', type=int, default=1000) config = parser.parse_args() print(config) main(config) <file_sep>/solver.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- from model import Transform_Generator from model import Transform_Discriminator from model import Enhance_Generator from model import Enhance_DiscriminatorC, Enhance_DiscriminatorT from model import TVLoss from model import GaussianBlur from model import GrayLayer from model import VGG from torch.autograd import Variable from torchvision.utils import save_image from torchvision import transforms as T import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image import numpy as np import os import time import datetime class Solver(object): """Solver for training and testing StarGAN.""" def __init__(self, celeba_loader, config): """Initialize configurations.""" # Data loader. self.celeba_loader = celeba_loader # Model configurations. self.c_dim = config.c_dim self.image_size = config.image_size self.magnification = config.magnification ## Transform Network configurations. self.tg_conv_dim = config.tg_conv_dim self.td_conv_dim = config.td_conv_dim self.tg_repeat_num = config.tg_repeat_num self.td_repeat_num = config.td_repeat_num self.lambda_cls = config.lambda_cls self.lambda_rec = config.lambda_rec self.lambda_gp = config.lambda_gp ## Transform Network configurations. # Training configurations. self.dataset = config.dataset self.batch_size = config.batch_size self.num_iters = config.num_iters self.num_iters_decay = config.num_iters_decay self.tg_lr = config.tg_lr self.td_lr = config.td_lr self.eg_lr = config.eg_lr self.edc_lr = config.edc_lr self.edt_lr = config.edt_lr self.n_critic = config.n_critic self.beta1 = config.beta1 self.beta2 = config.beta2 self.resume_iters = config.resume_iters self.selected_attrs = config.selected_attrs # Test configurations. self.test_iters = config.test_iters # Miscellaneous. self.use_tensorboard = config.use_tensorboard self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Directories. self.log_dir = config.log_dir self.sample_dir = config.sample_dir self.model_save_dir = config.model_save_dir self.result_dir = config.result_dir # Step size. self.log_step = config.log_step self.sample_step = config.sample_step self.model_save_step = config.model_save_step self.lr_update_step = config.lr_update_step # TV loss self.tv_criterion = TVLoss(config.tv_weight) # Color loss self.color_criterion = nn.CrossEntropyLoss() # Texture loss self.texture_criterion = nn.CrossEntropyLoss() # identity loss self.identity_criterion = nn.L1Loss() # content loss self.content_criterion = nn.MSELoss() # reconstruction loss self.rec_criterion = nn.MSELoss() # Enhancement Operations self.blur = GaussianBlur() self.gray = GrayLayer() self.vgg = VGG() # Build the model and tensorboard. self.build_model() if self.use_tensorboard: self.build_tensorboard() def build_model(self): """Create generators and discriminators: Transform_Generator(T_G), Transform_Discriminator(T_D), Enhance_Generator(E_G), Enhance_Discriminator_color(E_Dc), Enhance_Discriminator_texture(E_Dt).""" self.T_G = Transform_Generator(self.tg_conv_dim, self.c_dim, self.tg_repeat_num) self.T_D = Transform_Discriminator(self.image_size, self.td_conv_dim, self.c_dim, self.td_repeat_num) self.E_G = Enhance_Generator() self.tg_optimizer = torch.optim.Adam(self.T_G.parameters(), self.tg_lr, [self.beta1, self.beta2]) self.td_optimizer = torch.optim.Adam(self.T_D.parameters(), self.td_lr, [self.beta1, self.beta2]) self.eg_optimizer = torch.optim.Adam(self.E_G.parameters(), self.eg_lr, [self.beta1, self.beta2]) self.print_network(self.T_G, 'T_G') self.print_network(self.T_D, 'T_D') self.print_network(self.E_G, 'E_G') self.T_G.to(self.device) self.T_D.to(self.device) self.E_G.to(self.device) def print_network(self, model, name): """Print out the network information.""" num_params = 0 for p in model.parameters(): num_params += p.numel() print(model) print(name) print("The number of parameters: {}".format(num_params)) def restore_model(self, resume_iters): """Restore the trained generator and discriminator.""" print('Loading the trained models from step {}...'.format(resume_iters)) T_G_path = os.path.join(self.model_save_dir, '{}-T_G.ckpt'.format(resume_iters)) T_D_path = os.path.join(self.model_save_dir, '{}-T_D.ckpt'.format(resume_iters)) E_G_path = os.path.join(self.model_save_dir, '{}-E_G.ckpt'.format(resume_iters)) self.T_G.load_state_dict(torch.load(T_G_path, map_location=lambda storage, loc: storage)) self.T_D.load_state_dict(torch.load(T_D_path, map_location=lambda storage, loc: storage)) self.E_G.load_state_dict(torch.load(E_G_path, map_location=lambda storage, loc: storage)) def build_tensorboard(self): """Build a tensorboard logger.""" from logger import Logger self.logger = Logger(self.log_dir) def update_lr(self, tg_lr, td_lr, eg_lr, edc_lr, edt_lr): """Decay learning rates of the generator and discriminator.""" for param_group in self.tg_optimizer.param_groups: param_group['lr'] = tg_lr for param_group in self.td_optimizer.param_groups: param_group['lr'] = td_lr for param_group in self.eg_optimizer.param_groups: param_group['lr'] = eg_lr def reset_grad(self): """Reset the gradient buffers.""" self.tg_optimizer.zero_grad() self.td_optimizer.zero_grad() self.eg_optimizer.zero_grad() def denorm(self, x): """Convert the range from [-1, 1] to [0, 1].""" out = (x + 1) / 2 return out.clamp_(0, 1) def gradient_penalty(self, y, x): """Compute gradient penalty: (L2_norm(dy/dx) - 1)**2.""" weight = torch.ones(y.size()).to(self.device) dydx = torch.autograd.grad(outputs=y, inputs=x, grad_outputs=weight, retain_graph=True, create_graph=True, only_inputs=True)[0] dydx = dydx.view(dydx.size(0), -1) dydx_l2norm = torch.sqrt(torch.sum(dydx**2, dim=1)) return torch.mean((dydx_l2norm-1)**2) def label2onehot(self, labels, dim): """Convert label indices to one-hot vectors.""" batch_size = labels.size(0) out = torch.zeros(batch_size, dim) out[np.arange(batch_size), labels.long()] = 1 return out def create_labels(self, c_org, c_dim=5, dataset='CelebA', selected_attrs=None): """Generate target domain labels for debugging and testing.""" # Get hair color indices. if dataset == 'CelebA': hair_color_indices = [] for i, attr_name in enumerate(selected_attrs): if attr_name in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair']: hair_color_indices.append(i) c_trg_list = [] for i in range(c_dim): if dataset == 'CelebA': c_trg = c_org.clone() if i in hair_color_indices: # Set one hair color to 1 and the rest to 0. c_trg[:, i] = 1 for j in hair_color_indices: if j != i: c_trg[:, j] = 0 else: c_trg[:, i] = (c_trg[:, i] == 0) # Reverse attribute value. c_trg_list.append(c_trg.to(self.device)) return c_trg_list def classification_loss(self, logit, target): """Compute binary or softmax cross entropy loss.""" return F.binary_cross_entropy_with_logits(logit, target, size_average=False) / logit.size(0) def train(self): """Train StarGAN within a single dataset.""" # Set data loader. data_loader = self.celeba_loader # Fetch fixed inputs for debugging. data_iter = iter(data_loader) x_H_fixed, x_Lm_fixed, x_L_fixed, y_org = next(data_iter) x_H_fixed = x_H_fixed.to(self.device) x_Lm_fixed = x_Lm_fixed.to(self.device) x_L_fixed = x_L_fixed.to(self.device) y_trg_list = self.create_labels(y_org, self.c_dim, self.dataset, self.selected_attrs) # Learning rate cache for decaying. tg_lr = self.tg_lr td_lr = self.td_lr eg_lr = self.eg_lr # Start training from scratch or resume training. start_iters = 0 if self.resume_iters: start_iters = self.resume_iters self.restore_model(self.resume_iters) # Start training. print('Start training...') start_time = time.time() for i in range(start_iters, self.num_iters): # =================================================================================== # # 1. Preprocess input data # # =================================================================================== # # Fetch real images and labels. try: x_H, x_Lm, x_L, label_org = next(data_iter) except: data_iter = iter(data_loader) x_H, x_Lm, x_L, label_org = next(data_iter) # Generate target domain labels randomly. rand_idx = torch.randperm(label_org.size(0)) label_trg = label_org[rand_idx] # lab y_org = label_org.clone() y_trg = label_trg.clone() x_H = x_H.to(self.device) # HR images x_Lm = x_Lm.to(self.device) # LR images x_L = x_L.to(self.device) # Input images. y_org = y_org.to(self.device) # Original domain labels. y_trg = y_trg.to(self.device) # Target domain labels. label_org = label_org.to(self.device) # Labels for computing classification loss. label_trg = label_trg.to(self.device) # Labels for computing classification loss. # =================================================================================== # # 2. Generators and Discriminators # # =================================================================================== # """ # Transform_Generator x_T = self.T_G(x_L, y_trg) x_T_TG = self.T_G(x_T, y_org) # Transform_Discriminator & Classifier x_T_TD, x_T_TC = self.T_D(x_T) x_H_TD, x_H_TC = self.T_D(x_H) # Enhancement_Generator x_E = self.E_G(x_T) # Enhancement_VGG for identity loss x_E_vgg = self.vgg(x_E) x_H_vgg = self.vgg(x_H) # Enhancement_Discriminator_Color for color loss x_E_blur = self.blur(x_E) x_H_blur = self.blur(x_H) x_E_blur_EDc = self.E_Dc(x_E_blur) x_H_blur_EDc = self.E_Dc(x_H_blur) # Enhancement_Discriminator_Texture for texture loss x_E_gray = self.gray(x_E) x_H_gray = self.gray(x_H) x_E_gray_EDt = self.E_Dt(x_E_gray) x_H_gray_EDt = self.E_Dt(x_H_gray) """ # =================================================================================== # # 2. Train the discriminator # # =================================================================================== # # Discriminators ## Transform Network x_H_TD, x_H_TC = self.T_D(x_H) x_T = self.T_G(x_L, y_trg) x_T_TD, x_T_TC = self.T_D(x_T.detach()) ### adv_loss td_loss_real = - torch.mean(x_H_TD) td_loss_fake = torch.mean(x_T_TD) td_loss_adv = td_loss_real + td_loss_fake ### att_loss td_loss_att = self.classification_loss(x_H_TC, label_org) ### gp_loss alpha = torch.rand(x_H.size(0), 1, 1, 1).to(self.device) x_hat = (alpha * x_H.data + (1 - alpha) * x_T.data).requires_grad_(True) x_hat_TD, _ = self.T_D(x_hat) td_loss_gp = self.gradient_penalty(x_hat_TD, x_hat) ### T_D Total Loss td_loss = td_loss_adv + td_loss_att + td_loss_gp * 10 ## Enhancement Network x_E = self.E_G(x_T) # Discriminators Loss d_loss = td_loss self.reset_grad() d_loss.backward() self.td_optimizer.step() # Logging. loss = {} loss['T_D/loss_TD'] = td_loss.item() loss['T_D/loss_adv'] = td_loss_adv.item() loss['T_D/loss_att'] = td_loss_att.item() loss['T_D/loss_gp'] = td_loss_gp.item() # =================================================================================== # # 3. Train the generators # # =================================================================================== # if (i+1) % self.n_critic == 0: # Generators ## Transform Network x_T = self.T_G(x_L, y_trg) x_T_TD, x_T_TC = self.T_D(x_T) x_T_TG = self.T_G(x_T, y_org) ### adv_loss tg_loss_fake = - torch.mean(x_T_TD) tg_loss_adv = tg_loss_fake ### att_loss tg_loss_att = self.classification_loss(x_T_TC, label_trg) ### rec_loss # tg_loss_rec = torch.mean(torch.abs(x_H - x_T_TG)) tg_loss_rec = self.rec_criterion(x_T_TG, x_H) ### T_G Total Loss tg_loss = tg_loss_adv + tg_loss_att + tg_loss_rec * 10 + tg_loss_tv ### identity_loss _, c1, h1, w1 = x_T.size() chw1 = c1 * h1 * w1 eg_loss_identity = 1.0/chw1 * self.content_criterion(x_E_vgg, x_H_vgg) ### content_loss eg_loss_content = self.content_criterion(x_E, x_H) ### E_G Total Loss eg_loss = eg_loss_identity + eg_loss_content # Generators Loss g_loss = tg_loss + eg_loss self.reset_grad() g_loss.backward() self.tg_optimizer.step() self.eg_optimizer.step() # Logging. loss = {} loss['T_G/loss_TG'] = tg_loss.item() loss['T_G/loss_adv'] = tg_loss_adv.item() loss['T_G/loss_att'] = tg_loss_att.item() loss['T_G/loss_rec'] = tg_loss_rec.item() loss['E_G/loss_EG'] = eg_loss.item() loss['E_G/loss_identity'] = eg_loss_identity.item() loss['E_G/loss_content'] = eg_loss_content.item() # =================================================================================== # # 4. Miscellaneous # # =================================================================================== # # Print out training information. if (i+1) % self.log_step == 0: et = time.time() - start_time et = str(datetime.timedelta(seconds=et))[:-7] log = "Elapsed [{}], Iteration [{}/{}]".format(et, i+1, self.num_iters) for tag, value in loss.items(): log += ", {}: {:.4f}".format(tag, value) print(log) if self.use_tensorboard: for tag, value in loss.items(): self.logger.scalar_summary(tag, value, i+1) # Translate fixed images for debugging. if (i+1) % self.sample_step == 0: with torch.no_grad(): x_output_list = [x_H_fixed, x_Lm_fixed, x_L_fixed] x_output_list.append(self.T_G(x_L_fixed, y_org)) x_output_list.append(self.E_G(self.T_G(x_L_fixed, y_org))) for y_trg in y_trg_list: x_output_list.append(self.T_G(x_L_fixed, y_trg)) x_output_list.append(self.E_G(self.T_G(x_L_fixed, y_trg))) x_concat = torch.cat(x_output_list, dim=3) sample_path = os.path.join(self.sample_dir, '{}-images.jpg'.format(i+1)) save_image(self.denorm(x_concat.data.cpu()), sample_path, nrow=1, padding=0) print('Saved real and fake images into {}...'.format(sample_path)) # Save model checkpoints. if (i+1) % self.model_save_step == 0: T_G_path = os.path.join(self.model_save_dir, '{}-T_G.ckpt'.format(i+1)) T_D_path = os.path.join(self.model_save_dir, '{}-T_D.ckpt'.format(i+1)) E_G_path = os.path.join(self.model_save_dir, '{}-E_G.ckpt'.format(i+1)) torch.save(self.T_G.state_dict(), T_G_path) torch.save(self.T_D.state_dict(), T_D_path) torch.save(self.E_G.state_dict(), E_G_path) print('Saved model checkpoints into {}...'.format(self.model_save_dir)) # Decay learning rates. if (i+1) % self.lr_update_step == 0 and (i+1) > (self.num_iters - self.num_iters_decay): tg_lr -= (self.tg_lr / float(self.num_iters_decay)) td_lr -= (self.td_lr / float(self.num_iters_decay)) eg_lr -= (self.eg_lr / float(self.num_iters_decay)) self.update_lr(tg_lr, td_lr, eg_lr) print ('Decayed learning rates, tg_lr: {}, td_lr: {}, eg_lr: {}, edc_lr: {}, edt_lr: {}.'.format(tg_lr, td_lr, eg_lr, edc_lr, edt_lr)) def test(self): """Translate images using StarGAN trained on a single dataset.""" # Load the trained generator. self.restore_model(self.test_iters) # Set data loader. data_loader = self.celeba_loader with torch.no_grad(): for i, (x_H, x_Lm, x_L, y_org) in enumerate(data_loader): # Prepare input images and target domain labels. x_H = x_H.to(self.device) x_Lm = x_Lm.to(self.device) x_L = x_L.to(self.device) y_org = y_org.to(self.device) y_trg_list = self.create_labels(y_org, self.c_dim, self.dataset, self.selected_attrs) # Translate images. x_output_list = [x_H, x_Lm, x_L] x_output_list.append(self.T_G(x_L, y_org)) x_output_list.append(self.E_G(self.T_G(x_L, y_org))) for y_trg in y_trg_list: x_output_list.append(self.T_G(x_L, y_trg)) x_output_list.append(self.E_G(self.T_G(x_L, y_trg))) # Save the translated images. x_concat = torch.cat(x_output_list, dim=3) result_path = os.path.join(self.result_dir, '{}-images.jpg'.format(i+1)) save_image(self.denorm(x_concat.data.cpu()), result_path, nrow=1, padding=0) print('Saved real and fake images into {}...'.format(result_path)) <file_sep>/data_loader.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- from torch.utils import data from torchvision import transforms as T from torchvision.datasets import ImageFolder from PIL import Image import torch import os import random class CelebA(data.Dataset): """Dataset class for the CelebA dataset.""" def __init__(self, image_dir, attr_path, selected_attrs, transform, mode): """Initialize and preprocess the CelebA dataset.""" self.image_dir = image_dir self.attr_path = attr_path self.selected_attrs = selected_attrs self.transform1 = transform[0] self.transform2 = transform[1] self.transform3 = transform[2] self.mode = mode self.train_dataset = [] self.test_dataset = [] self.attr2idx = {} self.idx2attr = {} self.preprocess() if mode == 'train': self.num_images = len(self.train_dataset) else: self.num_images = len(self.test_dataset) def preprocess(self): """Preprocess the CelebA attribute file.""" lines = [line.rstrip() for line in open(self.attr_path, 'r')] all_attr_names = lines[1].split() for i, attr_name in enumerate(all_attr_names): self.attr2idx[attr_name] = i self.idx2attr[i] = attr_name lines = lines[2:] random.seed(1234) random.shuffle(lines) for i, line in enumerate(lines): split = line.split() filename = split[0] values = split[1:] label = [] for attr_name in self.selected_attrs: idx = self.attr2idx[attr_name] label.append(values[idx] == '1') if (i+1) < 30000: self.test_dataset.append([filename, label]) else: self.train_dataset.append([filename, label]) print('Finished preprocessing the CelebA dataset...') def __getitem__(self, index): """Return three image and its corresponding attribute label.""" dataset = self.train_dataset if self.mode == 'train' else self.test_dataset filename, label = dataset[index] image = Image.open(os.path.join(self.image_dir, filename)) # Return: HR images, LR images, Input images, Selected attribute labels return self.transform1(image), self.transform2(image), self.transform3(image), torch.FloatTensor(label) def __len__(self): """Return the number of images.""" return self.num_images def get_loader(image_dir, attr_path, selected_attrs, image_size=128, magnification=4, batch_size=16, dataset='CelebA', mode='train', num_workers=1): """Build and return a data loader.""" # Transform1, Ground truth HR images to Tensor transform1 = [] transform1.append(T.ToTensor()) transform1.append(T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) transform1 = T.Compose(transform1) # Transform2, LR images to Tensor transform2 = [] transform2.append(T.Resize(image_size // magnification, interpolation=Image.BICUBIC)) transform2.append(T.Resize(image_size, interpolation=Image.NEAREST)) transform2.append(T.ToTensor()) transform2.append(T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) transform2 = T.Compose(transform2) # Transform3, HR ->downsample-> LR ->upsample-> Input images to Tensor transform3 = [] # if mode == 'train': # transform3.append(T.RandomHorizontalFlip()) transform3.append(T.Resize(image_size // magnification, interpolation=Image.BICUBIC)) transform3.append(T.Resize(image_size, interpolation=Image.BICUBIC)) transform3.append(T.ToTensor()) transform3.append(T.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))) transform3 = T.Compose(transform3) # Transform transform = [transform1, transform2, transform3] if dataset == 'CelebA': dataset = CelebA(image_dir, attr_path, selected_attrs, transform, mode) data_loader = data.DataLoader(dataset=dataset, batch_size=batch_size, shuffle=(mode=='train'), num_workers=num_workers) return data_loader <file_sep>/model.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models import vgg19_bn import numpy as np class ResidualBlock(nn.Module): """Residual Block with instance normalization.""" def __init__(self, dim_in, dim_out): super(ResidualBlock, self).__init__() self.main = nn.Sequential( nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True), nn.ReLU(inplace=True), nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False), nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True)) def forward(self, x): return x + self.main(x) class Transform_Generator(nn.Module): """Generator network.""" def __init__(self, conv_dim=64, c_dim=5, repeat_num=6): super(Transform_Generator, self).__init__() layers = [] layers.append(nn.Conv2d(3+c_dim, conv_dim, kernel_size=7, stride=1, padding=3, bias=False)) layers.append(nn.InstanceNorm2d(conv_dim, affine=True, track_running_stats=True)) layers.append(nn.ReLU(inplace=True)) # Down-sampling layers. curr_dim = conv_dim for i in range(2): layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1, bias=False)) layers.append(nn.InstanceNorm2d(curr_dim*2, affine=True, track_running_stats=True)) layers.append(nn.ReLU(inplace=True)) curr_dim = curr_dim * 2 # Bottleneck layers. for i in range(repeat_num): layers.append(ResidualBlock(dim_in=curr_dim, dim_out=curr_dim)) # Up-sampling layers. for i in range(2): layers.append(nn.ConvTranspose2d(curr_dim, curr_dim//2, kernel_size=4, stride=2, padding=1, bias=False)) layers.append(nn.InstanceNorm2d(curr_dim//2, affine=True, track_running_stats=True)) layers.append(nn.ReLU(inplace=True)) curr_dim = curr_dim // 2 layers.append(nn.Conv2d(curr_dim, 3, kernel_size=7, stride=1, padding=3, bias=False)) layers.append(nn.Tanh()) self.main = nn.Sequential(*layers) def forward(self, x, c): # Replicate spatially and concatenate domain information. c = c.view(c.size(0), c.size(1), 1, 1) c = c.repeat(1, 1, x.size(2), x.size(3)) x = torch.cat([x, c], dim=1) return self.main(x) class Transform_Discriminator(nn.Module): """Discriminator network with PatchGAN.""" def __init__(self, image_size=128, conv_dim=64, c_dim=5, repeat_num=6): super(Transform_Discriminator, self).__init__() layers = [] layers.append(nn.Conv2d(3, conv_dim, kernel_size=4, stride=2, padding=1)) layers.append(nn.LeakyReLU(0.01)) curr_dim = conv_dim for i in range(1, repeat_num): layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=4, stride=2, padding=1)) layers.append(nn.LeakyReLU(0.01)) curr_dim = curr_dim * 2 kernel_size = int(image_size / np.power(2, repeat_num)) self.main = nn.Sequential(*layers) self.conv1 = nn.Conv2d(curr_dim, 1, kernel_size=3, stride=1, padding=1, bias=False) self.conv2 = nn.Conv2d(curr_dim, c_dim, kernel_size=kernel_size, bias=False) def forward(self, x): h = self.main(x) out_src = self.conv1(h) out_cls = self.conv2(h) return out_src, out_cls.view(out_cls.size(0), out_cls.size(1)) class TVLoss(nn.Module): def __init__(self, tv_weight): super(TVLoss, self).__init__() self.tv_weight = tv_weight def forward(self, x): batch_size = x.size()[0] h_x = x.size()[2] w_x = x.size()[3] count_h = self._tensor_size(x[:, :, 1:, :]) count_w = self._tensor_size(x[:, :, :, 1:]) h_tv = torch.pow((x[:, :, 1:, :]-x[:, :, :h_x-1, :]), 2).sum() w_tv = torch.pow((x[:, :, :, 1:]-x[:, :, :, :w_x-1]),2).sum() return self.tv_weight*2*(h_tv/count_h+w_tv/count_w)/batch_size @staticmethod def _tensor_size(t): return t.size()[1]*t.size()[2]*t.size()[3] class ConvBlock(nn.Module): def __init__(self): super(ConvBlock, self).__init__() self.conv1 = nn.Conv2d(64, 64, 3, padding=1) self.conv2 = nn.Conv2d(64, 64, 3, padding=1) self.instance_norm1 = nn.InstanceNorm2d(64, affine=True) self.instance_norm2 = nn.InstanceNorm2d(64, affine=True) self.relu = nn.ReLU(inplace=True) def forward(self, x): y = self.relu(self.instance_norm1(self.conv1(x))) y = self.instance_norm2(self.conv2(y)) + x return y class Enhance_Generator(nn.Module): def __init__(self): super(Enhance_Generator, self).__init__() self.conv1 = nn.Conv2d(3, 64, 3, padding=1) self.blocks = nn.Sequential( ConvBlock(), ConvBlock(), ConvBlock(), ConvBlock(), ConvBlock(), ConvBlock(), ConvBlock(), ConvBlock(), ConvBlock(), ) self.conv2 = nn.Conv2d(64, 64, 3, padding=1) self.instance_norm = nn.InstanceNorm2d(64, affine=True) self.conv3 = nn.Conv2d(64, 64, 3, padding=1) self.conv4 = nn.Conv2d(64, 3, 1, padding=0) def forward(self, x): x = F.relu(self.conv1(x)) temp = x x = self.blocks(x) x = self.instance_norm(self.conv2(x)) + temp x = F.relu(self.conv3(x)) x = F.tanh(self.conv4(x)) return x class Enhance_DiscriminatorC(nn.Module): def __init__(self, input_ch): super(Enhance_DiscriminatorC, self).__init__() self.conv_layers = nn.Sequential( nn.Conv2d(input_ch, 48, 11, stride=4, padding=5), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(48, 128, 5, stride=2, padding=2), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(128, affine=True), nn.Conv2d(128, 192, 3, stride=1, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(192, affine=True), nn.Conv2d(192, 192, 3, stride=1, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(192, affine=True), nn.Conv2d(192, 128, 3, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(128, affine=True), ) self.fc = nn.Linear(128*9*9, 1024) self.out = nn.Linear(1024, 2) def forward(self, x): x = self.conv_layers(x) #print(x.shape) x = x.view(-1, 128*9*9) #print(x.shape) x = F.leaky_relu(self.fc(x), negative_slope=0.2) x = F.softmax(self.out(x)) return x class Enhance_DiscriminatorT(nn.Module): def __init__(self, input_ch): super(Enhance_DiscriminatorT, self).__init__() self.conv_layers = nn.Sequential( nn.Conv2d(input_ch, 48, 11, stride=4, padding=5), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(48, 128, 5, stride=2, padding=2), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(128, affine=True), nn.Conv2d(128, 192, 3, stride=1, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(192, affine=True), nn.Conv2d(192, 192, 3, stride=1, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(192, affine=True), nn.Conv2d(192, 128, 3, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.InstanceNorm2d(128, affine=True), ) self.fc = nn.Linear(128*8*8, 1024) self.out = nn.Linear(1024, 2) def forward(self, x): x = self.conv_layers(x) #print(x.shape) x = x.view(-1, 128*8*8) #print(x.shape) x = F.leaky_relu(self.fc(x), negative_slope=0.2) x = F.softmax(self.out(x)) return x class GaussianBlur(nn.Module): def __init__(self): super(GaussianBlur, self).__init__() kernel = [[0.03797616, 0.044863533, 0.03797616], [0.044863533, 0.053, 0.044863533], [0.03797616, 0.044863533, 0.03797616]] kernel = torch.FloatTensor(kernel).unsqueeze(0).unsqueeze(0) # self.weight = nn.Parameter(data=kernel, requires_grad=False) self.weight = kernel.cuda() def forward(self, x): x1 = x[:, 0] x2 = x[:, 1] x3 = x[:, 2] x1 = F.conv2d(x1.unsqueeze(1), self.weight, padding=2) x2 = F.conv2d(x2.unsqueeze(1), self.weight, padding=2) x3 = F.conv2d(x3.unsqueeze(1), self.weight, padding=2) x = torch.cat([x1, x2, x3], dim=1) return x class GrayLayer(nn.Module): def __init__(self): super(GrayLayer, self).__init__() def forward(self, x): result = 0.299 * x[:, 0] + 0.587 * x[:, 1] + 0.114 * x[:, 2] # print(result.unsqueeze(1).shape) return result.unsqueeze(1) class VGG(nn.Module): def __init__(self): super(VGG, self).__init__() self.model = vgg19_bn(True).features.cuda() self.mean = torch.Tensor([123.68, 116.779, 103.939]).cuda().view(1,3,1,1) for param in self.model.parameters(): param.requires_grad = False def forward(self, x): x = x*255 - self.mean #print(type(x), x.shape) x = self.model(x) return x <file_sep>/README.md # SR_2020 A python vision for our lastest face super-resolution method. #### TODO:The code will be updated until it is available and normalized. Hoping the COVID-19 will end soon.
63e0daf4b939655afb6120b896bba6082d14af6d
[ "Markdown", "Python" ]
5
Python
organizations-loops/SR_2020
39e20346ab83db40285d55c141969af080c29e93
6ead4e02f9a03e2a333b14671113d11e85c1d9d9
refs/heads/master
<repo_name>wangdi2014/staramr<file_sep>/CHANGELOG.md # Version 0.4.0 * Add support for campylobacter from PointFinder database. * Fix `read_table` deprecation warnings by replacing `read_table` with `read_csv`. * Handling issue with name of `16S` gene in PointFinder database for salmonella. * Refactoring and simplifying some of the git ResFinder/PointFinder database code. * Added automated type checking with [mypy](https://mypy.readthedocs.io). # Version 0.3.0 * Exclusion of `aac(6')-Iaa` from results by default. Added ability to override this with `--no-exclude-genes` or pass a custom list of genes to exclude from results with `--exclude-genes-file`. # Version 0.2.2 * Fix issue where `staramr` crashes if an input contig id is a number. # Version 0.2.1 * Minor * Updating default ResFinder/PointFinder databases to version from July 2018. * Fix regex extracting gene/variant/accession values from ResFinder/PointFinder databases. * Fixing a few entries in table mapping genes to phenotypes. * Print stderr for errors with `makeblastdb` # Version 0.2.0 * Major * Inclusion of predicted resistances to antimicrobial drugs thanks to gene/drug mappings from the NARMS/CIPARS Molecular Working Group. Resistance predictions are microbiological resistances and not clinical resistances (issue #4, #6). * Adding a `staramr db restore-default` command to restore the default `staramr` database (issue #3). * Switched to using BLAST Tabular data + pandas to read BLAST results (issue #10). * Inverted direction of BLAST (we now BLAST the AMR gene files against the input genomes). * Minor * Less verbose messages when encountering errors parsing the command-line options. * Able to support adding options after a list of files (e.g., `staramr search *.fasta -h` will print help docs). * Switched to including negative AMR results (samples with no AMR genes) by default. Must now use parameter `--exclude-negatives` to exclude them (issue #2). * Only print 2 decimals in Excel output (issue #5). * Automatically adjust Excel cells to better fit text (issue #7). * Many other coding improvements (issue #11, #13 and others). # Version 0.1.0 * Initial release. Supports batch scanning against the ResFinder and PointFinder databases. <file_sep>/staramr/blast/resfinder/ResfinderBlastDatabase.py import logging import os from staramr.blast.AbstractBlastDatabase import AbstractBlastDatabase logger = logging.getLogger('ResfinderBlastDatabase') """ A Class for pulling information from the ResFinder database. """ class ResfinderBlastDatabase(AbstractBlastDatabase): def __init__(self, database_dir): """ Creates a new ResfinderBlastDatabase. :param database_dir: The specific ResFinder database (drug class) directory. """ super().__init__(database_dir) def get_database_names(self): return [f[:-len(self.fasta_suffix)] for f in os.listdir(self.database_dir) if (os.path.isfile(os.path.join(self.database_dir, f)) and f.endswith(self.fasta_suffix))] def get_path(self, database_name): return os.path.join(self.database_dir, database_name + self.fasta_suffix) def get_name(self): return 'resfinder' <file_sep>/staramr/tests/unit/results/test_AMRDetectionSummary.py import unittest import pandas as pd from staramr.results.AMRDetectionSummary import AMRDetectionSummary class AMRDetectionSummaryTest(unittest.TestCase): def setUp(self): self.columns_resfinder = ('Isolate ID', 'Gene', '%Identity', '%Overlap', 'HSP Length/Total Length', 'Contig', 'Start', 'End', 'Accession') self.columns_pointfinder = ('Isolate ID', 'Gene', 'Type', 'Position', 'Mutation', '%Identity', '%Overlap', 'HSP Length/Total Length') # Resfinder tables self.resfinder_table_empty = pd.DataFrame([], columns=self.columns_resfinder) self.resfinder_table1 = pd.DataFrame([ ['file1', 'blaIMP-42', 99.73, 100.00, '741/741', 'blaIMP-42_1_AB753456', 1, 741, 'AB753456'], ], columns=self.columns_resfinder) self.resfinder_table1_files = ['file1'] self.resfinder_table_mult_resistance = pd.DataFrame([ ['file1', 'blaIMP-42', 99.73, 100.00, '741/741', 'blaIMP-42_1_AB753456', 1, 741, 'AB753456'], ['file1', 'newGene', 99.73, 100.00, '741/741', 'newGene', 1, 741, 'AB753456'], ], columns=self.columns_resfinder) self.resfinder_table_mult_resistance_files = ['file1'] self.resfinder_table_mult_gene_same_resistance = pd.DataFrame([ ['file1', 'blaIMP-42', 99.73, 100.00, '741/741', 'blaIMP-42_1_AB753456', 1, 741, 'AB753456'], ['file1', 'newGene', 99.73, 100.00, '741/741', 'newGene', 1, 741, 'AB753456'], ], columns=self.columns_resfinder) self.resfinder_table_mult_gene_same_resistance_files = ['file1'] self.resfinder_table_mult_same_gene_same_resistance = pd.DataFrame([ ['file1', 'blaIMP-42', 99.73, 100.00, '741/741', 'blaIMP-42_1_AB753456', 1, 741, 'AB753456'], ['file1', 'blaIMP-42', 99.73, 100.00, '741/741', 'newGene', 1, 741, 'AB753456'], ], columns=self.columns_resfinder) self.resfinder_table_mult_same_gene_same_resistance_files = ['file1'] self.resfinder_table_mult_file = pd.DataFrame([ ['file1', 'blaIMP-42', 99.73, 100.00, '741/741', 'blaIMP-42_1_AB753456', 1, 741, 'AB753456'], ['file1', 'newGene', 99.73, 100.00, '741/741', 'newGene', 1, 741, 'AB753456'], ['file2', 'blaIMP-42', 99.73, 100.00, '741/741', 'newGene', 1, 741, 'AB753456'], ], columns=self.columns_resfinder) self.resfinder_table_mult_file_files = ['file1', 'file2'] # Pointfinder tables self.pointfinder_table = pd.DataFrame([ ['file1', 'gyrA', 'codon', 67, 'GCC -> CCC (A -> P)', 99.96, 100.0, '2637/2637'], ], columns=self.columns_pointfinder) self.pointfinder_table_files = ['file1'] self.pointfinder_table_multiple_gene = pd.DataFrame([ ['file1', 'gyrA', 'codon', 67, 'GCC -> CCC (A -> P)', 99.96, 100.0, '2637/2637'], ['file1', 'gyrAB', 'codon', 67, 'GCC -> CCC (A -> P)', 99.96, 100.0, '2637/2637'], ], columns=self.columns_pointfinder) self.pointfinder_table_multiple_gene_files = ['file1'] def testResfinderSingleGene(self): amr_detection_summary = AMRDetectionSummary(self.resfinder_table1_files, self.resfinder_table1) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42', summary['Genotype'].iloc[0], 'Genes not equal') def testResfinderSingleGeneWithNegativesNonIncluded(self): files = ['file1', 'file2'] amr_detection_summary = AMRDetectionSummary(files, self.resfinder_table1) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42', summary['Genotype'].iloc[0], 'Genes not equal') def testResfinderSingleGeneWithNegativesIncluded(self): files = ['file1', 'file2'] amr_detection_summary = AMRDetectionSummary(files, self.resfinder_table1) summary = amr_detection_summary.create_summary(True) self.assertEqual(2, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42', summary['Genotype'].iloc[0], 'Genes not equal') self.assertEqual('file2', summary.index[1], 'Negative file not included') self.assertEqual('None', summary['Genotype'].iloc[1], 'Negative gene not valid') def testResfinderSingleGeneWithTwoNegativesIncluded(self): files = ['file1', 'file2', 'file3'] amr_detection_summary = AMRDetectionSummary(files, self.resfinder_table1) summary = amr_detection_summary.create_summary(True) self.assertEqual(3, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42', summary['Genotype'].iloc[0], 'Genes not equal') self.assertEqual('file2', summary.index[1], 'Negative file not included') self.assertEqual('None', summary['Genotype'].iloc[1], 'Negative gene not valid') self.assertEqual('file3', summary.index[2], 'Negative file not included') self.assertEqual('None', summary['Genotype'].iloc[2], 'Negative gene not valid') def testResfinderSingleGeneWithTwoNegativesIncludedDifferentOrder(self): files = ['file2', 'file1', 'file3'] amr_detection_summary = AMRDetectionSummary(files, self.resfinder_table1) summary = amr_detection_summary.create_summary(True) self.assertEqual(3, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42', summary['Genotype'].iloc[0], 'Genes not equal') self.assertEqual('file2', summary.index[1], 'Negative file not included') self.assertEqual('None', summary['Genotype'].iloc[1], 'Negative gene not valid') self.assertEqual('file3', summary.index[2], 'Negative file not included') self.assertEqual('None', summary['Genotype'].iloc[2], 'Negative gene not valid') def testResfinderMultipleGeneResistance(self): amr_detection_summary = AMRDetectionSummary(self.resfinder_table_mult_resistance_files, self.resfinder_table_mult_resistance) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42, newGene', summary['Genotype'].iloc[0], 'Genes not equal') def testResfinderMultipleGeneSameResistance(self): amr_detection_summary = AMRDetectionSummary(self.resfinder_table_mult_gene_same_resistance_files, self.resfinder_table_mult_gene_same_resistance) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42, newGene', summary['Genotype'].iloc[0], 'Genes not equal') def testResfinderMultipleSameGeneSameResistance(self): amr_detection_summary = AMRDetectionSummary(self.resfinder_table_mult_same_gene_same_resistance_files, self.resfinder_table_mult_same_gene_same_resistance) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42, blaIMP-42', summary['Genotype'].iloc[0], 'Genes not equal') def testResfinderMultipleFile(self): amr_detection_summary = AMRDetectionSummary(self.resfinder_table_mult_file_files, self.resfinder_table_mult_file) summary = amr_detection_summary.create_summary() self.assertEqual(2, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42, newGene', summary['Genotype'].iloc[0], 'Genes not equal') self.assertEqual('file2', summary.index[1], 'File name not equal') self.assertEqual('blaIMP-42', summary['Genotype'].iloc[1], 'Genes not equal') def testPointfinderSingleGene(self): amr_detection_summary = AMRDetectionSummary(self.pointfinder_table_files, self.resfinder_table_empty, self.pointfinder_table) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('gyrA', summary['Genotype'].iloc[0], 'Genes not equal') def testPointfinderSingleMultipleGene(self): amr_detection_summary = AMRDetectionSummary(self.pointfinder_table_multiple_gene_files, self.resfinder_table_empty, self.pointfinder_table_multiple_gene) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('gyrA, gyrAB', summary['Genotype'].iloc[0], 'Genes not equal') def testPointfinderSingleMultipleGeneSame(self): df = pd.DataFrame([ ['file1', 'gyrA', 'codon', 67, 'GCC -> CCC (A -> P)', 99.96, 100.0, '2637/2637'], ['file1', 'gyrA', 'codon', 67, 'GCC -> CCC (A -> P)', 99.96, 100.0, '2637/2637'], ], columns=self.columns_pointfinder) files = ['file1'] amr_detection_summary = AMRDetectionSummary(files, self.resfinder_table_empty, df) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('gyrA, gyrA', summary['Genotype'].iloc[0], 'Genes not equal') def testPointfinderResfinderSingleGene(self): files = ['file1'] amr_detection_summary = AMRDetectionSummary(files, self.resfinder_table1, self.pointfinder_table) summary = amr_detection_summary.create_summary() self.assertEqual(1, len(summary.index), 'Invalid number of rows in results') self.assertEqual('file1', summary.index[0], 'File name not equal') self.assertEqual('blaIMP-42, gyrA', summary['Genotype'].iloc[0], 'Genes not equal') <file_sep>/staramr/detection/AMRDetection.py from staramr.blast.results.pointfinder.BlastResultsParserPointfinder import BlastResultsParserPointfinder from staramr.blast.results.resfinder.BlastResultsParserResfinder import BlastResultsParserResfinder from staramr.results.AMRDetectionSummary import AMRDetectionSummary """ A Class to handle scanning files for AMR genes. """ class AMRDetection: def __init__(self, resfinder_database, amr_detection_handler, pointfinder_database=None, include_negative_results=False, output_dir=None, genes_to_exclude=[]): """ Builds a new AMRDetection object. :param resfinder_database: The staramr.blast.resfinder.ResfinderBlastDatabase for the particular ResFinder database. :param amr_detection_handler: The staramr.blast.BlastHandler to use for scheduling BLAST jobs. :param pointfinder_database: The staramr.blast.pointfinder.PointfinderBlastDatabase to use for the particular PointFinder database. :param include_negative_results: If True, include files lacking AMR genes in the resulting summary table. :param output_dir: The directory where output fasta files are to be written into (None for no output fasta files). :param genes_to_exclude: A list of gene IDs to exclude from the results. """ self._resfinder_database = resfinder_database self._amr_detection_handler = amr_detection_handler self._pointfinder_database = pointfinder_database self._include_negative_results = include_negative_results if pointfinder_database is None: self._has_pointfinder = False else: self._has_pointfinder = True self._output_dir = output_dir self._genes_to_exclude = genes_to_exclude def _create_amr_summary(self, files, resfinder_dataframe, pointfinder_dataframe): amr_detection_summary = AMRDetectionSummary(files, resfinder_dataframe, pointfinder_dataframe) return amr_detection_summary.create_summary(self._include_negative_results) def _create_resfinder_dataframe(self, resfinder_blast_map, pid_threshold, plength_threshold, report_all): resfinder_parser = BlastResultsParserResfinder(resfinder_blast_map, self._resfinder_database, pid_threshold, plength_threshold, report_all, output_dir=self._output_dir, genes_to_exclude=self._genes_to_exclude) return resfinder_parser.parse_results() def _create_pointfinder_dataframe(self, pointfinder_blast_map, pid_threshold, plength_threshold, report_all): pointfinder_parser = BlastResultsParserPointfinder(pointfinder_blast_map, self._pointfinder_database, pid_threshold, plength_threshold, report_all, output_dir=self._output_dir, genes_to_exclude=self._genes_to_exclude) return pointfinder_parser.parse_results() def run_amr_detection(self, files, pid_threshold, plength_threshold_resfinder, plength_threshold_pointfinder, report_all=False): """ Scans the passed files for AMR genes. :param files: The files to scan. :param pid_threshold: The percent identity threshold for BLAST results. :param plength_threshold_resfinder: The percent length overlap for BLAST results (resfinder). :param plength_threshold_pointfinder: The percent length overlap for BLAST results (pointfinder). :param report_all: Whether or not to report all blast hits. :return: None """ self._amr_detection_handler.run_blasts(files) resfinder_blast_map = self._amr_detection_handler.get_resfinder_outputs() self._resfinder_dataframe = self._create_resfinder_dataframe(resfinder_blast_map, pid_threshold, plength_threshold_resfinder, report_all) if self._has_pointfinder: pointfinder_blast_map = self._amr_detection_handler.get_pointfinder_outputs() self._pointfinder_dataframe = self._create_pointfinder_dataframe(pointfinder_blast_map, pid_threshold, plength_threshold_pointfinder, report_all) else: self._pointfinder_dataframe = None self._summary_dataframe = self._create_amr_summary(files, self._resfinder_dataframe, self._pointfinder_dataframe) def get_resfinder_results(self): """ Gets a pd.DataFrame for the ResFinder results. :return: A pd.DataFrame for the ResFinder results. """ return self._resfinder_dataframe def get_pointfinder_results(self): """ Gets a pd.DataFrame for the PointFinder results. :return: A pd.DataFrame for the PointFinder results. """ return self._pointfinder_dataframe def get_summary_results(self): """ Gets a pd.DataFrame for a summary table of the results. :return: A pd.DataFrame for a summary table of the results. """ return self._summary_dataframe <file_sep>/README.md [![Build Status](https://travis-ci.org/phac-nml/staramr.svg?branch=development)](https://travis-ci.org/phac-nml/staramr) [![pypi](https://badge.fury.io/py/staramr.svg)](https://pypi.python.org/pypi/staramr/) [![conda](https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg)](https://anaconda.org/bioconda/staramr) # `staramr` `staramr` (*AMR) scans bacterial genome contigs against both the [ResFinder][resfinder-db] and [PointFinder][pointfinder-db] databases (used by the [ResFinder webservice][resfinder-web]) and compiles a summary report of detected antimicrobial resistance genes. **Note: The predicted phenotypes/drug resistances are for microbiological resistance and *not* clinical resistance. This is provided with support from the NARMS/CIPARS Molecular Working Group and is continually being improved. A small comparison between phenotype/drug resistance predictions produced by `staramr` and those available from NCBI can be found in the [tutorial][tutorial]. We welcome any feedback or suggestions.** For example: ``` staramr search -o out --pointfinder-organism salmonella *.fasta ``` **out/summary.tsv**: | Isolate ID | Genotype | Predicted Phenotype | |------------|-----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------| | SRR1952908 | aadA1, aadA2, blaTEM-57, cmlA1, gyrA (S83Y), sul3, tet(A) | streptomycin, ampicillin, chloramphenicol, ciprofloxacin I/R, nalidixic acid, sulfisoxazole, tetracycline | | SRR1952926 | blaTEM-57, gyrA (S83Y), tet(A) | ampicillin, ciprofloxacin I/R, nalidixic acid, tetracycline | **out/resfinder.tsv**: | Isolate ID | Gene | Predicted Phenotype | %Identity | %Overlap | HSP Length/Total Length | Contig | Start | End | Accession | |------------|------------|----------------------|------------|-----------|--------------------------|--------------|--------|-------|-----------| | SRR1952908 | sul3 | sulfisoxazole | 100.00 | 100.00 | 792/792 | contig00030 | 2091 | 2882 | AJ459418 | | SRR1952908 | tet(A) | tetracycline | 99.92 | 100.00 | 1200/1200 | contig00032 | 1551 | 2750 | AJ517790 | | SRR1952908 | cmlA1 | chloramphenicol | 99.92 | 100.00 | 1260/1260 | contig00030 | 6707 | 5448 | M64556 | | SRR1952908 | aadA1 | streptomycin | 100.00 | 100.00 | 792/792 | contig00030 | 5355 | 4564 | JQ414041 | | SRR1952908 | aadA2 | streptomycin | 99.75 | 100.00 | 792/792 | contig00030 | 7760 | 6969 | JQ364967 | | SRR1952908 | blaTEM-57 | ampicillin | 99.88 | 100.00 | 861/861 | contig00032 | 6247 | 5387 | FJ405211 | | SRR1952926 | tet(A) | tetracycline | 99.92 | 100.00 | 1200/1200 | contig00027 | 1480 | 2679 | AJ517790 | | SRR1952926 | blaTEM-57 | ampicillin | 99.88 | 100.00 | 861/861 | contig00027 | 6176 | 5316 | FJ405211 | **out/pointfinder.tsv**: | Isolate ID | Gene | Predicted Phenotype | Type | Position | Mutation | %Identity | %Overlap | HSP Length/Total Length | Contig | Start | End | |-------------|--------------|------------------------------------|--------|-----------|----------------------|------------|-----------|--------------------------|--------------|---------|--------| | SRR1952908 | gyrA (S83Y) | ciprofloxacin I/R, nalidixic acid | codon | 83 | TCC -> TAC (S -> Y) | 99.96 | 100.00 | 2637/2637 | contig00008 | 22801 | 20165 | | SRR1952926 | gyrA (S83Y) | ciprofloxacin I/R, nalidixic acid | codon | 83 | TCC -> TAC (S -> Y) | 99.96 | 100.00 | 2637/2637 | contig00011 | 157768 | 160404 | # Table of Contents - [Quick Usage](#quick-usage) * [Search contigs](#search-contigs) * [Database Info](#database-info) * [Update Database](#update-database) * [Restore Database](#restore-database) - [Installation](#installation) * [Bioconda](#bioconda) * [PyPI/Pip](#pypipip) * [Latest Code](#latest-code) * [Dependencies](#dependencies) - [Output](#output) * [summary.tsv](#summarytsv) * [resfinder.tsv](#resfindertsv) * [pointfinder.tsv](#pointfindertsv) * [settings.txt](#settingstxt) * [hits/](#hits) - [Tutorial](#tutorial) - [Usage](#usage) * [Main Command](#main-command) * [Search](#search) * [Database Build](#database-build) * [Database Update](#database-update) * [Database Info](#database-info-1) * [Database Restore Default](#database-restore-default) - [Caveats](#caveats) - [Acknowledgements](#acknowledgements) - [Citations](#citations) - [Legal](#legal) # Quick Usage ## Search contigs To search a list of contigs (in **fasta** format) for AMR genes using ResFinder please run: ```bash staramr search -o out *.fasta ``` Output files will be located in the directory `out/`. To include acquired point-mutation resistances using PointFinder, please run: ```bash staramr search --pointfinder-organism salmonella -o out *.fasta ``` Where `--pointfinder-organism` is the specific organism you are interested in (currently only *salmonella* and *campylobacter* are supported). ## Database Info To print information about the installed databases, please run: ``` staramr db info ``` ## Update Database If you wish to update to the latest ResFinder and PointFinder databases, you may run: ```bash staramr db update --update-default ``` If you wish to switch to specific git commits of the ResFinder and PointFinder databases you may also pass `--resfinder-commit [COMMIT]` and `--pointfinder-commit [COMMIT]`. ## Restore Database If you have updated the ResFinder/PointFinder databases and wish to restore to the default version, you may run: ``` staramr db restore-default ``` # Installation ## Bioconda The easiest way to install `staramr` is through [Bioconda][bioconda]. ```bash conda install -c bioconda staramr ``` This will install the `staramr` Python package as well as all necessary dependencies and databases. You can now run: ```bash staramr --help ``` If you wish to use `staramr` in an isolated environment (in case dependencies conflict) you may alternatively install with: ```bash conda create -c bioconda --name staramr staramr ``` To run `staramr` in this case, you must first activate the environment. That is: ```bash source activate staramr staramr --help ``` ## PyPI/Pip You can also install `staramr` from [PyPI][pypi-staramr] using `pip`: ``` pip install staramr ``` However, you will have to install the external dependencies (listed below) separately. ## Latest Code If you wish to make use of the latest in-development version of `staramr`, you may update directly from GitHub using `pip`: ```bash pip install git+https://github.com/phac-nml/staramr ``` This will only install the Python code, you will still have to install the dependencies listed below (or run the `pip` command from the previously installed Bioconda environment). Alternatively, if you wish to do development with `staramr` you can use a Python virtual environment (you must still install the non-Python dependencies separately). ```bash # Clone code git clone https://github.com/phac-nml/staramr.git cd staramr # Setup virtual environment virtualenv -p /path/to/python-bin .venv source .venv/bin/activate # Install staramr. Use '-e' to update the install on code changes. pip install -e . # Now run `staramr` staramr ``` Due to the way I package the ResFinder/PointFinder databases, the development code will not come with a default database. You must first build the database before usage. E.g. ``` staramr db restore-default ``` ## Dependencies * Python 3.5+ * BLAST+ * Git # Input ## List of genes to exclude By default, the ResFinder/PointFinder genes listed in [genes_to_exclude.tsv][] will be excluded from the final results. To pass a custom list of genes the option `--exclude-genes-file` can be used, where the file specified will contains a list of the sequence ids (one per line) from the ResFinder/PointFinder databases. For example: ``` #gene_id aac(6')-Iaa_1_NC_003197 ``` Please make sure to include `#gene_id` in the first line. The default exclusion list can also be disabled with `--no-exclude-genes`. # Output There are 5 different output files produced by `staramr`: 1. `summary.tsv`: A summary of all detected AMR genes/mutations in each genome, one genome per line. 2. `resfinder.tsv`: A tabular file of each AMR gene and additional BLAST information from the **ResFinder** database, one gene per line. 3. `pointfinder.tsv`: A tabular file of each AMR point mutation and additional BLAST information from the **PointFinder** database, one gene per line. 4. `settings.txt`: The command-line, database versions, and other settings used to run `staramr`. 5. `results.xlsx`: An Excel spreadsheet containing the previous 4 files as separate worksheets. In addition, the directory `hits/` stores fasta files of the specific blast hits. ## summary.tsv The **summary.tsv** output file generated by `staramr` contains the following columns: * __Isolate ID__: The id of the isolate/genome file(s) passed to `staramr`. * __Genotype__: The AMR genotype of the isolate. * __Predicted Phenotype__: The predicted AMR phenotype (drug resistances) for the isolate. ### Example | Isolate ID | Genotype | Predicted Phenotype | |------------|-----------------------------------------------------------|-----------------------------------------------------------------------------------------------------------| | SRR1952908 | aadA1, aadA2, blaTEM-57, cmlA1, gyrA (S83Y), sul3, tet(A) | streptomycin, ampicillin, chloramphenicol, ciprofloxacin I/R, nalidixic acid, sulfisoxazole, tetracycline | | SRR1952926 | blaTEM-57, gyrA (S83Y), tet(A) | ampicillin, ciprofloxacin I/R, nalidixic acid, tetracycline | ## resfinder.tsv The **resfinder.tsv** output file generated by `staramr` contains the following columns: * __Isolate ID__: The id of the isolate/genome file(s) passed to `staramr`. * __Gene__: The particular AMR gene detected. * __Predicted Phenotype__: The predicted AMR phenotype (drug resistances) for this gene. * __%Identity__: The % identity of the top BLAST HSP to the AMR gene. * __%Overlap__: THe % overlap of the top BLAST HSP to the AMR gene (calculated as __hsp length/total length * 100__). * __HSP Length/Total Length__ The top BLAST HSP length over the AMR gene total length (nucleotides). * __Contig__: The contig id containing this AMR gene. * __Start__: The start of the AMR gene (will be greater than __End__ if on minus strand). * __End__: The end of the AMR gene. * __Accession__: The accession of the AMR gene in the ResFinder database. ### Example | Isolate ID | Gene | Predicted Phenotype | %Identity | %Overlap | HSP Length/Total Length | Contig | Start | End | Accession | |------------|------------|----------------------|------------|-----------|--------------------------|--------------|--------|-------|-----------| | SRR1952908 | sul3 | sulfisoxazole | 100.00 | 100.00 | 792/792 | contig00030 | 2091 | 2882 | AJ459418 | | SRR1952908 | tet(A) | tetracycline | 99.92 | 100.00 | 1200/1200 | contig00032 | 1551 | 2750 | AJ517790 | ## pointfinder.tsv The **pointfinder.tsv** output file generated by `staramr` contains the following columns: * __Isolate ID__: The id of the isolate/genome file(s) passed to `staramr`. * __Gene__: The particular AMR gene detected, with the point mutation within *()*. * __Predicted Phenotype__: The predicted AMR phenotype (drug resistances) for this gene. * __Type__: The type of this mutation from PointFinder (either **codon** or **nucleotide**). * __Position__: The position of the mutation. For **codon** type, the position is the codon number in the gene, for **nucleotide** type it is the nucleotide number. * __Mutation__: The particular mutation. For **codon** type lists the codon mutation, for **nucleotide** type lists the single nucleotide mutation. * __%Identity__: The % identity of the top BLAST HSP to the AMR gene. * __%Overlap__: The % overlap of the top BLAST HSP to the AMR gene (calculated as __hsp length/total length * 100__). * __HSP Length/Total Length__ The top BLAST HSP length over the AMR gene total length (nucleotides). * __Contig__: The contig id containing this AMR gene. * __Start__: The start of the AMR gene (will be greater than __End__ if on minus strand). * __End__: The end of the AMR gene. ### Example | Isolate ID | Gene | Predicted Phenotype | Type | Position | Mutation | %Identity | %Overlap | HSP Length/Total Length | Contig | Start | End | |-------------|--------------|------------------------------------|--------|-----------|----------------------|------------|-----------|--------------------------|--------------|---------|--------| | SRR1952908 | gyrA (S83Y) | ciprofloxacin I/R, nalidixic acid | codon | 83 | TCC -> TAC (S -> Y) | 99.96 | 100.00 | 2637/2637 | contig00008 | 22801 | 20165 | | SRR1952926 | gyrA (S83Y) | ciprofloxacin I/R, nalidixic acid | codon | 83 | TCC -> TAC (S -> Y) | 99.96 | 100.00 | 2637/2637 | contig00011 | 157768 | 160404 | ## settings.txt The **settings.txt** file contains the particular settings used to run `staramr`. * __command_line__: The command line used to run `staramr`. * __version__: The version of `staramr`. * __start_time__,__end_time__,__total_minutes__: The start, end, and duration for running `staramr`. * __resfinder_db_dir__, __pointfinder_db_dir__: The directory containing the ResFinder and PointFinder databases. * __resfinder_db_url__, __pointfinder_db_url__: The URL to the git repository for the ResFinder and PointFinder databases. * __resfinder_db_commit__, __pointfinder_db_commit__: The git commit ids for the ResFinder and PointFinder databases. * __resfinder_db_date__, __pointfinder_db_date__: The date of the git commits of the ResFinder and PointFinder databases. * __pointfinder_gene_drug_version__, __resfinder_gene_drug_version__: A version identifier for the gene/drug mapping table used by `staramr`. ### Example ``` command_line = staramr search -o out --pointfinder-organism salmonella SRR1952908.fasta SRR1952926.fasta version = 0.2.0 start_time = 2018-06-08 10:28:47 end_time = 2018-06-08 10:28:59 total_minutes = 0.20 resfinder_db_dir = staramr/databases/data/dist/resfinder resfinder_db_url = https://bitbucket.org/genomicepidemiology/resfinder_db.git resfinder_db_commit = dc33e2f9ec2c420f99f77c5c33ae3faa79c999f2 resfinder_db_date = Tue, 20 Mar 2018 16:49 pointfinder_db_dir = staramr/databases/data/dist/pointfinder pointfinder_db_url = https://bitbucket.org/genomicepidemiology/pointfinder_db.git pointfinder_db_commit = ba65c4d175decdc841a0bef9f9be1c1589c0070a pointfinder_db_date = Fri, 06 Apr 2018 09:02 pointfinder_gene_drug_version = 050218 resfinder_gene_drug_version = 050218 ``` ## hits/ The **hits/** directory contains the BLAST HSP nucleotides for the entries listed in the **resfinder.tsv** and **pointfinder.tsv** files. There are up to two files per input genome, one for ResFinder and one for PointFinder. For example, with an input genome named **SRR1952908.fasta** there would be two files `hits/resfinder_SRR1952908.fasta` and `hits/pointfinder_SRR1952908.fasta`. These files contain mostly the same information as in the **resfinder.tsv** and **pointfinder.tsv** files. Additional information is the **resistance_gene_start** and **resistance_gene_end** listing the start/end of the BLAST HSP on the AMR resistance gene from the ResFinder/PointFinder databases. ### Example ``` >aadA1_3_JQ414041 isolate: SRR1952908, contig: contig00030, contig_start: 5355, contig_end: 4564, resistance_gene_start: 1, resistance_gene_end: 792, hsp/length: 792/792, pid: 100.00%, plength: 100.00% ATGAGGGAAGCGGTGATCGCCGAAGTATCGACTCAACTATCAGAGGTAGTTGGCGTCATC GAGCGCCATCTCGAACCGACGTTGCTGGCCGTACATTTGTACGGCTCCGCAGTGGATGGC ... ``` # Tutorial A tutorial guiding you though the usage of `staramr`, interpreting the results, and comparing with antimicrobial resistances available on NCBI can be found at [staramr tutorial][tutorial]. # Usage ## Main Command Main `staramr` command. Can be used to set global options (primarily `--verbose`). ``` usage: staramr [-h] [--verbose] [-V] {search,db} ... Do AMR detection for genes and point mutations positional arguments: {search,db} Subcommand for AMR detection. search Search for AMR genes db Download ResFinder/PointFinder databases optional arguments: -h, --help show this help message and exit --verbose Turn on verbose logging [False]. -V, --version show program's version number and exit ``` ## Search Searches input FASTA files for AMR genes. ``` usage: staramr search [-h] [--pointfinder-organism POINTFINDER_ORGANISM] [-d DATABASE] [-n NPROCS] [--pid-threshold PID_THRESHOLD] [--percent-length-overlap-resfinder PLENGTH_THRESHOLD_RESFINDER] [--percent-length-overlap-pointfinder PLENGTH_THRESHOLD_POINTFINDER] [--no-exclude-genes] [--exclude-genes-file EXCLUDE_GENES_FILE] [--exclude-negatives] [--exclude-resistance-phenotypes] [--report-all-blast] [-o OUTPUT_DIR] [--output-summary OUTPUT_SUMMARY] [--output-resfinder OUTPUT_RESFINDER] [--output-pointfinder OUTPUT_POINTFINDER] [--output-settings OUTPUT_SETTINGS] [--output-excel OUTPUT_EXCEL] [--output-hits-dir HITS_OUTPUT_DIR] files [files ...] positional arguments: files optional arguments: -h, --help show this help message and exit --pointfinder-organism POINTFINDER_ORGANISM The organism to use for pointfinder {salmonella, campylobacter}. Defaults to disabling search for point mutations. [None]. -d DATABASE, --database DATABASE The directory containing the resfinder/pointfinder databases [staramr/databases/data]. -n NPROCS, --nprocs NPROCS The number of processing cores to use [MAX CPU CORES]. BLAST Thresholds: --pid-threshold PID_THRESHOLD The percent identity threshold [98.0]. --percent-length-overlap-resfinder PLENGTH_THRESHOLD_RESFINDER The percent length overlap for resfinder results [60.0]. --percent-length-overlap-pointfinder PLENGTH_THRESHOLD_POINTFINDER The percent length overlap for pointfinder results [95.0]. Reporting options: --no-exclude-genes Disable the default exclusion of some genes from ResFinder/PointFinder [False]. --exclude-genes-file EXCLUDE_GENES_FILE A containing a list of ResFinder/PointFinder gene names to exclude from results [staramr/databases/exclude/data/genes_to_exclude.tsv]. --exclude-negatives Exclude negative results (those sensitive to antimicrobials) [False]. --exclude-resistance-phenotypes Exclude predicted antimicrobial resistances [False]. --report-all-blast Report all blast hits (vs. only top blast hits) [False]. Output: Use either --output-dir or specify individual output files -o OUTPUT_DIR, --output-dir OUTPUT_DIR The output directory for results [None]. --output-summary OUTPUT_SUMMARY The name of the output file containing the summary results. Not be be used with '--output-dir'. [None] --output-resfinder OUTPUT_RESFINDER The name of the output file containing the resfinder results. Not be be used with '--output-dir'. [None] --output-pointfinder OUTPUT_POINTFINDER The name of the output file containing the pointfinder results. Not be be used with '--output-dir'. [None] --output-settings OUTPUT_SETTINGS The name of the output file containing the settings. Not be be used with '--output-dir'. [None] --output-excel OUTPUT_EXCEL The name of the output file containing the excel results. Not be be used with '--output-dir'. [None] --output-hits-dir HITS_OUTPUT_DIR The name of the directory to contain the BLAST hit files. Not be be used with '--output-dir'. [None] Example: staramr search -o out *.fasta Searches the files *.fasta for AMR genes using only the ResFinder database, storing results in the out/ directory. staramr search --pointfinder-organism salmonella --output-excel results.xlsx *.fasta Searches *.fasta for AMR genes using ResFinder and PointFinder database with the passed organism, storing results in results.xlsx. ``` ## Database Build Downloads and builds the ResFinder and PointFinder databases. ``` usage: staramr db build [-h] [--dir DESTINATION] [--resfinder-commit RESFINDER_COMMIT] [--pointfinder-commit POINTFINDER_COMMIT] optional arguments: -h, --help show this help message and exit --dir DESTINATION The directory to download the databases into [staramr/databases/data]. --resfinder-commit RESFINDER_COMMIT The specific git commit for the resfinder database [latest]. --pointfinder-commit POINTFINDER_COMMIT The specific git commit for the pointfinder database [latest]. Example: staramr db build Builds a new ResFinder/PointFinder database under staramr/databases/data if it does not exist staramr db build --dir databases Builds a new ResFinder/PointFinder database under databases/ ``` ## Database Update Updates an existing download of the ResFinder and PointFinder databases. ``` usage: staramr db update [-h] [-d] [--resfinder-commit RESFINDER_COMMIT] [--pointfinder-commit POINTFINDER_COMMIT] [directories [directories ...]] positional arguments: directories optional arguments: -h, --help show this help message and exit -d, --update-default Updates default database directory (staramr/databases/data). --resfinder-commit RESFINDER_COMMIT The specific git commit for the resfinder database [latest]. --pointfinder-commit POINTFINDER_COMMIT The specific git commit for the pointfinder database [latest]. Example: staramr db update databases/ Updates the ResFinder/PointFinder database under databases/ staramr db update -d Updates the default ResFinder/PointFinder database under staramr/databases/data ``` ## Database Info Prints information about an existing build of the ResFinder/PointFinder databases. ``` usage: staramr db info [-h] [directories [directories ...]] positional arguments: directories optional arguments: -h, --help show this help message and exit Example: staramr db info Prints information about the default database in staramr/databases/data staramr db info databases Prints information on the database stored in databases/ ``` ## Database Restore Default Restores the default database for `staramr`. ``` usage: staramr db restore-default [-h] [-f] optional arguments: -h, --help show this help message and exit -f, --force Force restore without asking for confirmation. Example: staramr db restore-default Restores the default ResFinder/PointFinder database ``` # Caveats This software is still a work-in-progress. In particular, not all organisms stored in the PointFinder database are supported (only *salmonella* and *campylobacter* are currently supported). Additionally, the predicted phenotypes are for microbiological resistance and *not* clinical resistance. Phenotype/drug resistance predictions are an experimental feature which is continually being improved. `staramr` only works on assembled genomes and not directly on reads. A quick genome assembler you could use is [Shovill][shovill]. Or, you may also wish to try out the [ResFinder webservice][resfinder-web], or the command-line tools [rgi][] or [ariba][] which will work on sequence reads as well as genome assemblies. You may also wish to check out the [CARD webservice][card-web]. # Acknowledgements Some ideas for the software were derived from the [ResFinder][resfinder-git] and [PointFinder][pointfinder-git] command-line software, as well as from [ABRicate][abricate]. Phenotype/drug resistance predictions are provided with support from the NARMS/CIPARS Molecular Working Group. # Citations If you find `staramr` useful, please consider citing this GitHub repository (https://github.com/phac-nml/staramr) as well as the original ResFinder and PointFinder publications. > **<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Lund O, Aarestrup FM, Larsen MV**. 2012. Identification of acquired antimicrobial resistance genes. J. Antimicrob. Chemother. 67:2640–2644. doi: [10.1093/jac/dks261][resfinder-cite] > **<NAME>, <NAME>, <NAME>, <NAME>M, Lund O, Aarestrup F**. PointFinder: a novel web tool for WGS-based detection of antimicrobial resistance associated with chromosomal point mutations in bacterial pathogens. J Antimicrob Chemother. 2017; 72(10): 2764–8. doi: [10.1093/jac/dkx217][pointfinder-cite] # Legal Copyright 2018 Government of Canada Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. [resfinder-db]: https://bitbucket.org/genomicepidemiology/resfinder_db [pointfinder-db]: https://bitbucket.org/genomicepidemiology/pointfinder_db [resfinder-web]: https://cge.cbs.dtu.dk/services/ResFinder/ [resfinder-cite]: https://dx.doi.org/10.1093/jac/dks261 [pointfinder-cite]: https://doi.org/10.1093/jac/dkx217 [Bioconda]: https://bioconda.github.io/ [requirements.txt]: requirements.txt [resfinder-git]: https://bitbucket.org/genomicepidemiology/resfinder [pointfinder-git]: https://bitbucket.org/genomicepidemiology/pointfinder-3.0 [abricate]: https://github.com/tseemann/abricate [shovill]: https://github.com/tseemann/shovill [ariba]: https://github.com/sanger-pathogens/ariba [rgi]: https://github.com/arpcard/rgi [pypi-staramr]: https://pypi.org/project/staramr/ [bioconda]: https://bioconda.github.io/ [card-web]: https://card.mcmaster.ca/ [tutorial]: doc/tutorial/staramr-tutorial.ipynb [genes_to_exclude.tsv]: staramr/databases/exclude/data/genes_to_exclude.tsv <file_sep>/staramr/results/AMRDetectionSummaryResistance.py from collections import OrderedDict import pandas as pd from staramr.results.AMRDetectionSummary import AMRDetectionSummary """ Summarizes both ResFinder and PointFinder database results into a single table. """ class AMRDetectionSummaryResistance(AMRDetectionSummary): def __init__(self, files, resfinder_dataframe, pointfinder_dataframe=None): """ Creates a new AMRDetectionSummaryResistance. :param files: The list of genome files we have scanned against. :param resfinder_dataframe: The pd.DataFrame containing the ResFinder results. :param pointfinder_dataframe: The pd.DataFrame containing the PointFinder results. """ super().__init__(files, resfinder_dataframe, pointfinder_dataframe) def _aggregate_gene_phenotype(self, dataframe): flattened_phenotype_list = [y.strip() for x in dataframe['Predicted Phenotype'].tolist() for y in x.split(self.SEPARATOR)] uniq_phenotype = OrderedDict.fromkeys(flattened_phenotype_list) return {'Gene': (self.SEPARATOR + ' ').join(dataframe['Gene']), 'Predicted Phenotype': (self.SEPARATOR + ' ').join(list(uniq_phenotype)) } def _compile_results(self, df): df_summary = df.copy() # Used to sort by gene names, ignoring case df_summary['Gene.Lower'] = df['Gene'].str.lower() # Compiles the gene/phenotype results into a single entry per isolate (groupby) df_summary = df_summary \ .sort_values(by=['Gene.Lower']) \ .groupby(['Isolate ID'], sort=True) \ .aggregate(self._aggregate_gene_phenotype) return df_summary[['Gene', 'Predicted Phenotype']] def _include_negatives(self, df): result_names_set = set(df.index.tolist()) names_set = set(self._names) negative_names_set = names_set - result_names_set negative_entries = pd.DataFrame([[x, 'None', 'Sensitive'] for x in negative_names_set], columns=('Isolate ID', 'Gene', 'Predicted Phenotype')).set_index( 'Isolate ID') return df.append(negative_entries, sort=True) <file_sep>/staramr/results/AMRDetectionSummary.py from os import path import pandas as pd """ Summarizes both ResFinder and PointFinder database results into a single table. """ class AMRDetectionSummary: SEPARATOR = ',' def __init__(self, files, resfinder_dataframe, pointfinder_dataframe=None): """ Constructs an object for summarizing AMR detection results. :param files: The list of genome files we have scanned against. :param resfinder_dataframe: The pd.DataFrame containing the ResFinder results. :param pointfinder_dataframe: The pd.DataFrame containing the PointFinder results. """ self._names = [path.splitext(path.basename(x))[0] for x in files] self._resfinder_dataframe = resfinder_dataframe if pointfinder_dataframe is not None: self._has_pointfinder = True self._pointfinder_dataframe = pointfinder_dataframe else: self._has_pointfinder = False def _compile_results(self, df): df_summary = df.sort_values(by=['Gene']).groupby(['Isolate ID']).aggregate( lambda x: {'Gene': (self.SEPARATOR + ' ').join(x['Gene'])}) return df_summary[['Gene']] def _include_negatives(self, df): result_names_set = set(df.index.tolist()) names_set = set(self._names) negative_names_set = names_set - result_names_set negative_entries = pd.DataFrame([[x, 'None'] for x in negative_names_set], columns=('Isolate ID', 'Gene')).set_index('Isolate ID') return df.append(negative_entries, sort=True) def create_summary(self, include_negatives=False): """ Constructs a summary pd.DataFrame for all ResFinder/PointFinder results. :param include_negatives: If True, include files with no ResFinder/PointFinder results. :return: A pd.DataFrame summarizing the results. """ df = self._resfinder_dataframe if self._has_pointfinder: df = df.append(self._pointfinder_dataframe, sort=True) df = self._compile_results(df) if include_negatives: df = self._include_negatives(df) df.rename(columns={'Gene': 'Genotype'}, inplace=True) return df.sort_index()
6327d0ea45b1df258876e429c68c6d38bcd3c01a
[ "Markdown", "Python" ]
7
Markdown
wangdi2014/staramr
e58cce19570e056968ca2cd88b8d8caebb2fcda5
52e1b09755e40d8b2feb5f9872f14f139c453cde
refs/heads/master
<repo_name>arian/underprime<file_sep>/list/compact.js "use strict"; var list = require('prime/collection/list') list.implement({ compact: function(){ return list.filter(this, function(value){ return !!value; }) } }) require('../').implement('compact', list) module.exports = list.compact <file_sep>/list/pluck.js "use strict"; var list = require('prime/collection/list') list.implement({ pluck: function(key){ return list.map(this, function(value){ return value[key] }) } }) require('../').implement('pluck', list) module.exports = list.pluck <file_sep>/list/flatten.js "use strict"; var array = require('prime/es5/array') var list = require('prime/collection/list') var flatten = function(input, shallow, output){ list.forEach(input, function(value){ if (array.isArray(value)){ if (shallow){ output.push.apply(output, value) } else { flatten(value, shallow, output) } } else { output.push(value) } }) return output } list.implement({ flatten: function(shallow) { return flatten(this, shallow, []) } }) require('../').implement('flatten', list) module.exports = list.flatten <file_sep>/list/first.js "use strict"; var list = require('prime/collection/list') list.implement({ first: function(n){ return (n != null) ? this.slice(0, n) : this[0] } }) require('../').implement('first', list) module.exports = list.first
3f059373fd507aae5e0f19e5967685761a6cf8b8
[ "JavaScript" ]
4
JavaScript
arian/underprime
6acd9101ee5ea834c22a2c2fa0b4b2fe4b54fe39
02edc625a0bd0cd38e4e13426ec7d43a28ac8c2c
refs/heads/master
<repo_name>wangyanilizhongshuo/react<file_sep>/mobile1/src/components/TabDetail.js import React,{Component} from 'react'; import axios from 'axios'; import { Card, WingBlank, WhiteSpace } from 'antd-mobile'; export default class TabDetail extends Component{ constructor(props){ super(props); this.state={ list:[], } } getData=()=>{ axios({ url : `http://localhost:3000/product/${this.props.match.params.id}`, method: 'get' }).then(res=>{ this.setState({ list:[this.state.list,res.data] }) }) } componentDidMount(){ var headurl=this.props.match.path; if(headurl.match(/product/g).length>0){ this.getData(); } } render(){ // console.log(this.state.list); const { Meta } = Card; const {carousel} = this.props; let jsx=[]; for(var i=0;i<this.state.list.length;i++){ if(this.state.list[i].text !=null ){ jsx.push( <WingBlank size="lg"> <WhiteSpace size="lg" /> <Card> <Card.Header title={this.state.list[i].text} thumb={this.state.list[i].img} thumbStyle={{border:'1px solid black',borderRadius:'25px' }} extra={<span>{this.state.list[ i].id}</span>} /> <Card.Body> <div >{this.state.list[i].content}</div> </Card.Body> </Card> <WhiteSpace size="lg" /> </WingBlank> ) } } return ( <div> {jsx} </div> )} }<file_sep>/mobile1/src/components/Tabs1.js import React,{Component} from 'react'; import { NavBar,Card, WingBlank, WhiteSpace, Tabs,Button} from 'antd-mobile'; import { Carousel} from 'antd-mobile'; import { connect } from 'react-redux'; import { fetchCarsouelList } from '../actions'; import { StickyContainer, Sticky } from 'react-sticky'; import axios from 'axios'; const mapStateToProps = state=>{ return { carousel: state.carousel } } function renderTabBar(props) { return (<Sticky> {({ style }) => <div style={{ ...style, zIndex: 1 }}><Tabs.DefaultTabBar {...props} /></div>} </Sticky>); } const tabs = [ { title: 'News List' }, { title: 'Product List' }, { title: 'Third List' }, ]; class Tabs1 extends Component{ constructor(props){ super(props); this.state={ list:[], page:1, listnews:[], } } getData = ()=>{ axios({ url : `http://localhost:3000/product?_page=1&_limit=3&_sort=id&_order=desc`, method: 'get' }).then(res=>{ this.setState({ list:[...this.state.list,...res.data] }) } ) } getData1 = ()=>{ axios({ url : `http://localhost:3000/news?_page=1&_limit=3&_sort=id&_order=desc`, method: 'get' }).then(res=>{ this.setState({ listnews:[...this.state.listnews,...res.data] }) } ) } componentDidMount(){ this.getData(); this.getData1(); this.props.fetchCarsouelList(); } render(){ const { Meta } = Card; const {carousel} = this.props; let jsx=[]; for(var i=0;i<this.state.list.length;i++){ jsx.push( <WingBlank size="lg"> <WhiteSpace size="lg" /> <Card> <Card.Header title={this.state.list[i].text} thumb={this.state.list[i].img} extra={<span>{this.state.list[ i].id}</span>} thumbStyle={{border:'1px solid black',borderRadius:'25px' }} /> <Card.Body > <div style={{ 'white-space': 'nowrap', 'text-overflow': 'ellipsis', 'overflow': 'hidden', 'display':'block','width':'100%' }}>{this.state.list[i].content}</div> </Card.Body> </Card> <WhiteSpace size="lg" /> </WingBlank> ) } let jsxnews=[]; for(var i=0;i<this.state.listnews.length;i++){ jsxnews.push( <WingBlank size="lg"> <WhiteSpace size="lg" /> <Card> <Card.Header title={this.state.listnews[i].text} thumb={this.state.listnews[i].img} extra={<span>{this.state.listnews[ i].id}</span>} thumbStyle={{border:'1px solid black',borderRadius:'25px' }} /> <Card.Body> <div style={{ 'white-space': 'nowrap', 'text-overflow': 'ellipsis', 'overflow': 'hidden', 'display':'block','width':'100%' }}>{this.state.listnews[i].content}</div> </Card.Body> </Card> <WhiteSpace size="lg" /> </WingBlank> ) } return ( <div> <NavBar mode= "dark">首页</NavBar> <WingBlank> <Carousel autoplay = {false} infinite beforeChange = {(from, to) => console.log(`slide from ${from} to ${to}`)} afterChange = {index => console.log('slide to', index)} > {carousel.map(val => ( <a key = {val.id} href = {val.url} style = {{ display: 'inline-block', width: '100%', height: 200 }} > <img src = {val.img} alt = {val.title} style = {{ width: '100%', verticalAlign: 'top' }} /> </a> ))} </Carousel> </WingBlank> <div> <br/> <Button type="primary">产品模块</Button><WhiteSpace /> {jsx} <Button type="primary">新闻模块</Button><WhiteSpace /> {jsxnews} </div> </div> ) } } export default connect(mapStateToProps,{fetchCarsouelList})(Tabs1);<file_sep>/admin/mockData.js const faker =require('faker'); const Mock = require('mockjs'); const _ = require('lodash'); module.exports = function(){ return { people:_.times(100,function(n){ return { id : n, name: Mock.Random.cname(), img : Mock.Random.image('50x50', Mock.Random.color()), text: Mock.Random.csentence(8,14), time: Mock.Random.date('yyyy-MM-dd'), star: Mock.mock({ 'number|1-100': 100 }) } }), product:_.times(100,function(n){ return { id : n, name : Mock.Random.cname(), img : Mock.Random.image('50x50', Mock.Random.color()), content:Mock.Random.csentence(200,300), text : Mock.Random.csentence(4,14), time : Mock.Random.date('yyyy-MM-dd'), price: Mock.mock({ 'number|1-100': 100 }) } }), news:_.times(100,function(n){ return { id : n, name : Mock.Random.cname(), img : Mock.Random.image('50x50', Mock.Random.color()), content:Mock.Random.csentence(200,600), text : Mock.Random.csentence(4,14), time : Mock.Random.date('yyyy-MM-dd'), } }), carousel:_.times(6,function(n){ return { id : n, name : Mock.Random.cname(), img : Mock.Random.image('50x50', Mock.Random.color()), url:Mock.Random.url() } }), } }
06c305cf8e84f14b34fe818ddaa0f9df86b9fd5f
[ "JavaScript" ]
3
JavaScript
wangyanilizhongshuo/react
34af541aa250734d9207448be3cac004bb3fad39
3654f193ee929cfde4db67e6b397c8b588c5129e
refs/heads/main
<repo_name>emil-khamatnurov/Web-technologies<file_sep>/Лабораторная работа 1/JS/main.js alert('Привет дорогой друг');
e5f0637c18c9e04fa23547e3f4250832fd5ec9a4
[ "JavaScript" ]
1
JavaScript
emil-khamatnurov/Web-technologies
8366ef80234df5e1d9b02aa41fc5c36e85eac225
56864277c094452335bd7ff2f2f137f20a5e303d
refs/heads/main
<repo_name>3103ski/react-sudoku<file_sep>/src/components/gameboard/Gameboard.jsx import React, { useContext } from 'react'; import { GameContext } from '../../context/game'; import Block from '../block/Block.jsx'; import { NumberButtons } from '../../components/'; import * as style from './gameboard.module.scss'; export default function Gameboard() { const game = useContext(GameContext); const renderBlocks = () => { let blocks = []; for (let i = 0; i <= 8; i++) { blocks.push(game.cells.filter((cell) => cell.block === i)); } return blocks.map((block, i) => <Block key={`block__${i}`} cells={block} />); }; return ( <div className={style.BoardContainer}> {renderBlocks()} {game.focusCell ? ( <div className={style.CellButtons}> <NumberButtons isNotes={true} /> <NumberButtons /> </div> ) : null} </div> ); } <file_sep>/src/context/game.js import React, { createContext, useReducer } from 'react'; import { updateObj } from '../util/util.js'; import { generateSudoku, returnBlock, returnRow, returnCol } from '../util/sudokuFunctions.js'; const initialState = { puzzleAnswers: generateSudoku(), difficulty: 'medium', cells: null, clues: null, focusCell: null, wrongAnswerCount: null, gameComplete: false, }; initialState.cells = generateCells(initialState.puzzleAnswers); initialState.clues = buildClueArray(initialState.difficulty); //••••••••••••••••••• // •• Game Utilities //••••••••••••••••••• function generateCells(puzzleAnswers) { return puzzleAnswers.map((cell, i) => ({ correctAnswer: cell, notes: [], row: returnRow(i), col: returnCol(i), block: returnBlock(i), answer: null, cellIndex: i, })); } function buildClueArray(difficulty) { let [indexList, limit] = [[], null]; switch (difficulty) { case 'easy': limit = 40; break; case 'hard': limit = 20; break; default: limit = 30; break; } while (indexList.length < limit) { let num = Math.floor(Math.random() * 80); if (!indexList.includes(num)) indexList.push(num); } return indexList; } //••••••••••••••••••••••• // •• Build game reducer //••••••••••••••••••••••• const reducer = ( state, { type, clues, puzzleAnswers, wrongAnswerCount, difficulty, cells, focusCell } ) => { switch (type) { case 'UPDATE_CELL': return updateObj(state, { cells, focusCell: null }); case 'SET_FOCUS_CELL': return updateObj(state, { focusCell }); case 'CHECK_PUZZLE': return updateObj(state, { wrongAnswerCount }); case 'SET_DIFFICULTY': return updateObj(state, { difficulty }); case 'NEW_PUZZLE': return updateObj(state, { clues, puzzleAnswers, cells, focusCell: null, gameComplete: false, }); case 'END_GAME': return updateObj(state, { gameComplete: true, cells, focusCell: null }); default: return state; } }; const GameContext = createContext(initialState); const GameProvider = (props) => { // •• Game State const [state, dispatch] = useReducer(reducer, initialState); // •• Game Options const setDifficulty = (difficulty) => dispatch({ type: 'SET_DIFFICULTY', difficulty }); //•••••••••••••••••• // •• Puzzle & Game //•••••••••••••••••• // Create new puzzle const newPuzzle = () => { const puzzleAnswers = generateSudoku(); let [clues, cells] = [buildClueArray(state.difficulty), generateCells(puzzleAnswers)]; return dispatch({ type: 'NEW_PUZZLE', clues, cells, puzzleAnswers }); }; // Check if the values entered by user are correct and provide wrong answer count const checkPuzzle = () => { let wrongAnswerCount = state.cells .filter((c) => !state.clues.includes(c.cellIndex)) .filter((cell) => cell.answer !== cell.correctAnswer).length; dispatch({ type: 'CHECK_PUZZLE', wrongAnswerCount }); if (wrongAnswerCount > 0) setTimeout(() => dispatch({ type: 'CHECK_PUZZLE', wrongAnswerCount: null }), 2000); }; // End the game when the user clicks the end button const endGame = () => dispatch({ type: 'END_GAME', cells: state.cells.map((cell) => ({ ...cell, answer: cell.correctAnswer })), }); //•••••••••• // •• Cells //•••••••••• // toggle or select focus cell's when clicking around the window or board const setFocusCell = (focusCell) => dispatch({ type: 'SET_FOCUS_CELL', focusCell }); // update cell notes // Recieve an updated cell from cell component and update stored cells in state const updateCell = (newCell) => { dispatch({ type: 'UPDATE_CELL', cells: state.cells.map((cell) => { if (newCell.answer) { if ( cell.row === newCell.row || cell.block === newCell.block || cell.col === newCell.col ) cell.notes = cell.notes.filter((n) => n !== newCell.answer); newCell.notes = []; } return cell.cellIndex === newCell.cellIndex ? newCell : cell; }), }); }; // TODO - return ( <GameContext.Provider value={{ puzzleAnswers: state.puzzleAnswers, cells: state.cells, clues: state.clues, difficulty: state.difficulty, flaggedBoxes: state.flaggedBoxes, focusCell: state.focusCell, wrongAnswerCount: state.wrongAnswerCount, gameComplete: state.gameComplete, setDifficulty, setFocusCell, updateCell, checkPuzzle, newPuzzle, endGame, }} {...props} /> ); }; export { GameContext, GameProvider }; <file_sep>/README.md <!-- Todo --> - add hint option - refine styling - buttons don't show when clicking the first cell on the board <file_sep>/src/components/numberButtons/NumberButtons.jsx import React, { useContext } from 'react'; import { GameContext } from '../../context/game.js'; import { updateObj } from '../../util/util.js'; import * as style from './numberButtons.module.scss'; export default function NumberButtons({ isNotes = false }) { const game = useContext(GameContext); let cell = game.cells[game.focusCell]; const handleButtonOnClick = (num) => { if (isNotes) { if (!cell.notes.includes(num)) { cell.notes.push(num); } else { cell.notes = cell.notes.filter((n) => { return n !== num; }); } } else { if (cell.answer && num === cell.answer) { cell = updateObj(cell, { answer: null }); } else { cell = updateObj(cell, { answer: num }); } } return game.updateCell(cell); }; const Btn = ({ num }) => ( <div onClick={() => handleButtonOnClick(num)} data-fill={ (cell.notes.includes(num) && isNotes) || (cell.answer === num && !isNotes) ? 1 : 0 } className={style.NumberButton}> <span>{num}</span> </div> ); const renderBtns = () => new Array(9) .fill(null) .map((_, i) => <Btn num={i + 1} key={`${isNotes ? 'note-btn' : 'ans-btn'}-${i}`} />); return <div className={style.Container}>{renderBtns()}</div>; } <file_sep>/src/components/gameOptions/GameOptions.jsx import React, { useContext, useEffect, useState } from 'react'; import { GameContext } from '../../context/game.js'; import { Button as Btn, DropMenu as Drop } from '../../components'; import * as style from './gameOptions.module.scss'; export default function GameOptions() { const game = useContext(GameContext); const [currDifficulty, setCurrentDifficulty] = useState(game.difficulty); const gameOptions = [{ value: 'easy' }, { value: 'medium' }, { value: 'hard' }]; useEffect(() => { if (currDifficulty !== game.difficulty) { setCurrentDifficulty(game.difficulty); game.newPuzzle(); } }, [currDifficulty, game, game.difficulty]); return ( <div className={style.GameOptionsContainer}> <Btn text='Check Answers' callback={game.checkPuzzle} color='green' /> <Btn text='New Puzzle' callback={game.newPuzzle} /> <Btn text='Show Solution' callback={game.endGame} color='orange' /> <Drop selected={game.difficulty} callback={game.setDifficulty} options={gameOptions} /> </div> ); } <file_sep>/src/components/UI/index.js export { default as Button } from './Button/Button.jsx'; export { default as DropMenu } from './DropMenu/DropMenu.jsx'; <file_sep>/src/components/cell/Cell.jsx import React, { useContext, useState, useEffect, useCallback } from 'react'; import { GameContext } from '../../context/game.js'; import { updateObj } from '../../util/util.js'; import * as style from './cell.module.scss'; export default function Cell({ cell }) { const game = useContext(GameContext); const isClue = game.clues.includes(cell.cellIndex); const [isEditing, setIsEditing] = useState(false); const [cellValue, setCellValue] = useState(null); const [userInput, setUserInput] = useState(''); // •• Validate and handle user input before setting value of cell const handleInputOnChange = (e) => { if ((!isNaN(e.target.value) && userInput.length < 1) || e.target.value === '') setUserInput(e.target.value); }; // •• If user input doesn't match stored value set the new value const handleInputSubmit = useCallback(() => { if (cellValue !== userInput) { setCellValue(userInput); game.updateCell(updateObj(cell, { answer: parseInt(userInput) })); } }, [cell, cellValue, game, userInput]); // •• Create function that fills cell answer const fillAnswer = useCallback(() => setCellValue(cell.correctAnswer), [cell.correctAnswer]); // •• Create a function that renders the notes assigned to the cell inside the block const renderNotes = (notes) => { const noteComponents = []; for (let i = 1; i <= 9; i++) { let note = ( <Note key={`${cell.block}_${cell.row}_${cell.col}_cell-note_${i}`} num={i} cellIndex={cell.cellIndex} /> ); noteComponents.push(note); } return noteComponents.map((n) => n); }; // •• Handle enter key when cell is active input const handleOnEnterKey = (e) => (e.key === 'Enter' ? game.setFocusCell(null) : null); // •• Let game context know if a cell should be focused when clicked const handleCellClick = () => !isClue && !game.gameComplete ? game.setFocusCell(cell.cellIndex) : game.setFocusCell(null); //•••••••• // •• SideEffects //•••••••• // •• Check if cell should show the answer as a clue useEffect(() => { if (isClue) fillAnswer(); }, [fillAnswer, isClue]); // •• Fill answer if the game has been ended useEffect(() => { if (game.gameComplete === true && cell.answer !== cellValue) fillAnswer(); }, [cell, cell.correctAnswer, cellValue, fillAnswer, game.gameComplete]); // •• Toggle input editing; set answer if new value is present useEffect(() => { if (!game.gameComplete) { if (game.focusCell === cell.cellIndex) { setIsEditing(true); } else if (game.focusCell !== cell.cellIndex) { setIsEditing(false); if (cell.answer !== userInput && !isClue) handleInputSubmit(); } } }, [ cellValue, isClue, userInput, handleInputSubmit, game.focusCell, game.gameComplete, cell.cellIndex, cell.answer, ]); // •• Focus On Input When Visible useEffect(() => { let input = document.querySelector('input'); if (isEditing && input) input.focus(); }, [isEditing]); // •• Listen for updates to cell notes return ( <div onClick={handleCellClick} className={style.CellContainer} data-show-correct={game.wrongAnswerCount ? 1 : 0} data-game-complete={game.gameComplete ? 1 : 0} data-is-correct={cell.answer === cell.correctAnswer ? 1 : 0} data-is-clue={isClue ? 1 : 0}> {isEditing && game.gameComplete === false ? ( <input type='text' value={userInput} onKeyDown={handleOnEnterKey} onChange={handleInputOnChange} /> ) : ( <p>{isClue ? cell.correctAnswer : cell.answer ? cell.answer : null}</p> )} {!isClue && !isEditing && !cell.answer ? ( <div className={style.CellNotes}> {renderNotes(game.cells[cell.cellIndex].notes)} </div> ) : null} </div> ); } function Note({ num, cellIndex }) { const [isVisible, setIsVisible] = useState(false); const game = useContext(GameContext); useEffect(() => { if (game.cells[cellIndex].notes.includes(num)) { setIsVisible(true); } else { setIsVisible(false); } }, [cellIndex, game.cells, num]); return ( <div className={style.NoteBox}> {num ? <p className={style.NoteNum}>{isVisible ? num : null}</p> : null} </div> ); } <file_sep>/src/components/index.js export { default as Gameboard } from './gameboard/Gameboard.jsx'; export { default as Block } from './block/Block.jsx'; export { default as Cell } from './cell/Cell.jsx'; export { default as GameOptions } from './gameOptions/GameOptions.jsx'; export { default as NumberButtons } from './numberButtons/NumberButtons.jsx'; export * from './UI/'; <file_sep>/src/App.js import React, { useContext } from 'react'; import * as style from './app.module.css'; import { GameContext } from './context/game.js'; import { Gameboard, GameOptions } from './components'; export default function App() { const game = useContext(GameContext); // Cancels focus on a cell if the user clicks outside of the board function TransparentCancelFocusBackdrop() { return <div onClick={() => game.setFocusCell(null)} className={style.ClearBG} />; } // Render game status when checked function RenderGameStatus() { return game.wrongAnswerCount && game.wrongAnswerCount > 0 ? ( <h3>You have {game.wrongAnswerCount} wrong answers</h3> ) : game.wrongAnswerCount === 0 ? ( <h3>All Solved!</h3> ) : null; } return ( <> <GameOptions /> <div className={style.AppContainer}> <Gameboard /> </div> <RenderGameStatus /> <TransparentCancelFocusBackdrop /> </> ); } <file_sep>/src/components/block/Block.jsx import React from 'react'; import Cell from '../cell/Cell.jsx'; import * as style from './block.module.scss'; export default function Block({ cells }) { const renderCells = () => cells.map((cell, i) => <Cell key={`cell${i}`} cell={cell} />); return <div className={style.BlockContainer}>{renderCells()}</div>; }
a56983b72d77c6448e1c83f45618f65fd17cf7c6
[ "JavaScript", "Markdown" ]
10
JavaScript
3103ski/react-sudoku
cc4d24b8014fa8ddca9b8f5cac716e0e2559a95c
6b7e5c1232cb5161d2161e96e6abc308b4c962f1
refs/heads/master
<file_sep>package paintWizard; public class Paint { private String name; private int size; private double cost; private double area; public Paint(String name, int size, double cost, double area) { this.name = name; this.size = size; this.cost = cost; this.area = area; } public void toString(String name, int size, double cost, double area) { System.out.println(name + " " + size + " " + cost + " " + area); } } <file_sep>package library; import static org.junit.Assert.*; import org.junit.Test; public class libraryTest { Storage S =new Storage(); // @Test // public void addItemTest() { // int size =Storage.Items.size(); // Storage.addBook("test", true, 100, "Fantasy","J.k.lowing"); // assertEquals(Storage.Items.size(),size+1); // Storage.removeItem("test"); // // } // // @Test // public void removeItemTest() { // // Storage.addBook("test", true, 100, "Fantasy","J.k.lowing"); // int size =Storage.Items.size(); // Storage.removeItem("test"); // assertEquals(Storage.Items.size(),size-1); // // } @Test public void updateItemTest() { S.addBook("test", true, 150, "Fantasy","J.k.lowing"); S.updateItemName(150,"test2"); System.out.println(S.Items.get(S.Items.size()-1).name); assertEquals("test2",S.Items.get(S.Items.size()-1).name); } }<file_sep>package battleship; public class Main { public static void main(String[] args) { Board b = new Board(); b.createBoard(); Ship.placeShip(ShipType.BATTLESHIP, b); Ship s = new Ship("j", 4, 4, 4, 4); s.place("igh",b); } } <file_sep>package battleship; import java.util.Scanner; public class Board { int playerBoard[][]; int computerBoard[][]; public void createBoard() { System.out.println("What size width would you like the board to be? It should be between 2 and 15"); Scanner w = new Scanner(System.in); int width = w.nextInt(); System.out.println("What size height would you like the board to be? it should be bewtween 2 and 15"); Scanner h = new Scanner(System.in); int height = h.nextInt(); playerBoard = new int[width][height]; computerBoard = new int[width][height]; if (width < 16 && width > 1 && height < 16 && height > 1) { System.out.println("You have a board size of " + width + " by " + height + "\nYour board has " + width * height + " spaces"); } else { System.out.println("Your values are out not between 2 and 15"); createBoard(); w.close(); h.close(); } } public int[][] getPlayerBoard() { return playerBoard; } public void setPlayerBoard(int[][] playerBoard) { this.playerBoard = playerBoard; } public int[][] getComputerBoard() { return computerBoard; } public void setComputerBoard(int[][] computerBoard) { this.computerBoard = computerBoard; } } <file_sep>public class Person { private String name; private int age; private String Job; public Person(String name, int age, String Job) { this.name = name; this.age = age; this.Job = Job; //System.out.println("Person name is " + name + " age is " + age + " Job is " + Job); } public String getName() { return name; } public String toString() { return ("Person name : " + name + " age : " + age + " Job : " + Job); } } <file_sep>package factorials; public class Factorial { public static void main(String[] args) { float f = 1; System.out.println(fact1(f)); } public static String fact1(float f) { int i = 1; float result = 0; do { if (i >= f) { break; } i++; result = f / i; if (result == 1) { return (i + "!"); } else { f = result; } } while (f > i); return "Not a factorial"; } } <file_sep>package library; public class Magazine extends Item{ private String name; private boolean isAvailable; private int id; private String publisher; public Magazine(String name, boolean isAvailable, int id, String publisher) { super(name, isAvailable, id); this.publisher = publisher; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isAvailable() { return isAvailable; } public void setAvailable(boolean isAvailable) { this.isAvailable = isAvailable; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } } <file_sep>#Mon Jul 02 15:18:11 BST 2018 org.eclipse.core.runtime=2 org.eclipse.platform=4.7.0.v20170612-0950 <file_sep>package battleship; public enum ShipType { PATROLBOAT, BATTLESHIP, SUBMARINE, DESTROYER, CARRIER } <file_sep>package Vehicle; public class Vehicle { public int speed; public int cost; public int getSpeed() { return speed; } public int getCost() { return cost; } } class Car extends Vehicle { public int noOfSeats; public Car(int maxSpeed, int price, int seats) { this.speed = maxSpeed; this.cost = price; this.noOfSeats = seats; } public int getNoOfSeats() { return noOfSeats; } public String toString() { return (speed + " " + cost + " " + noOfSeats); } } class Boat extends Vehicle { public int propelers; public Boat(int maxSpeed, int price, int propeler) { this.speed = maxSpeed; this.cost = price; this.propelers = propeler; } public int getPropelers() { return propelers; } public String toString() { return (speed + " " + cost + " " + propelers); } } class Bus extends Vehicle { int number; public int psng; public Bus(int maxSpeed, int price, int busNo, int passengers) { this.speed = maxSpeed; this.cost = price; this.psng = passengers; this.number = busNo; } public int getNumber() { return number; } public int getPsng() { return psng; } public String toString() { return (speed + " " + cost + " " + psng); } } <file_sep>package library; public class Map extends Item{ private String name; private boolean isAvailable; private int id; private String location; public Map(String name, boolean isAvailable, int id, String location) { super(name, isAvailable, id); this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isAvailable() { return isAvailable; } public void setAvailable(boolean isAvailable) { this.isAvailable = isAvailable; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } <file_sep>package goldilocks; public class Goldilocks { public static void main(String[] args) { int array[][] = { { 30, 50 }, { 130, 75 }, { 90, 60 }, { 150, 85 }, { 120, 70 }, { 200, 200 }, { 110, 100 } }; int array2[][]= {{297,90},{66,110},{257,113},{276,191},{280,129},{219,163},{254,193},{86,153},{206,147},{71,137},{104,40},{238,127},{52,146},{129,197},{144,59},{157,124},{210,59},{11,54},{268,119},{261,121},{12,189},{186,108},{174,21},{77,18},{54,90},{174,52},{16,129},{59,181},{290,123},{248,132}}; chairs(array2); //System.out.println(array2.length); } public static void chairs(int array[][]) { int weight = 100; int temp = 120; for (int i = 0; i < array.length; i++) { int j = 0; if (array[i][j] > weight) { int k = 1; if (array[i][k] < temp) { System.out.println(i + 1); } } } } }
c28f4750152fe937df0f4369d223bc6777340843
[ "Java", "INI" ]
12
Java
Sharm16/qa_java
a102493ea5b60f99e273e6f3175a84a53585f001
ec324723be89451b1ec7f65fe7fabd0f5acc7d73
refs/heads/master
<repo_name>MariangelaC/biblioteca<file_sep>/applications/libro/admin.py from django.contrib import admin from .models import Categoria, Libro admin.site.register(Categoria) admin.site.register(Libro) <file_sep>/applications/libro/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path( 'libros/', views.ListLibros.as_view(), name="libros" ), path( 'libros-2/', views.ListLibros2.as_view(), name="libros2" ), path( 'libros-trg/', views.ListLibrosTrg.as_view(), name="libros-trg" ), path( 'libro-detalle/<pk>/', views.LibroDetailView.as_view(), name="libro-detalle" ), ]<file_sep>/applications/lector/admin.py from django.contrib import admin from .models import Lector, Prestamo admin.site.register(Prestamo) admin.site.register(Lector) <file_sep>/applications/libro/managers.py import datetime from django.db import models from django.db.models import Q from django.contrib.postgres.search import TrigramSimilarity class LibroManager(models.Manager): """ managers para el modelo autor """ def listar_libros(self, kword): resultado = self.filter( titulo__icontains=kword, fecha__range=('2000-01-01', '2010-01-01') ) return resultado def listar_libros_trg(self, kword): if kword: resultado = self.filter( titulo__trigram_similar=kword, ) return resultado else: return self.all()[:10] def listar_libros2(self, kword, fecah1, fecha2): date1 = datetime.datetime.strptime(fecah1, "%Y-%m-%d").date() date2 = datetime.datetime.strptime(fecha2, "%Y-%m-%d").date() resultado = self.filter( titulo__icontains=kword, fecha__range=(date1, date2) ) return resultado def listar_libros_categoria(self, categoria): return self.filter( categoria__id=categoria ).order_by('titulo') def add_autor_libro(self, libro_id, autor): libro = self.get(id=libro_id) libro.autores.add(autor) return libro class CategoriaManager(models.Manager): """ managers para el modelo autor """ def categoria_por_autor(self, autor): return self.filter( categoria_libro__autores__id=autor ).distinct()<file_sep>/applications/libro/models.py from django.db import models from django.db.models.signals import post_save # apps tercero from PIL import Image # from local apps from applications.autor.models import Autor # Create your models here. from .managers import LibroManager, CategoriaManager class Categoria(models.Model): nombre = models.CharField(max_length=30) objects = CategoriaManager() def __str__(self): return str(self.id) + ' - ' + self.nombre class Libro(models.Model): categoria = models.ForeignKey( Categoria, on_delete=models.CASCADE, related_name='categoria_libro' ) autores = models.ManyToManyField(Autor) titulo = models.CharField( max_length=50 ) fecha = models.DateField('Fecha de lanzamiento') portada = models.ImageField(upload_to='portada') visitas = models.PositiveIntegerField() stok = models.PositiveIntegerField(default=0) objects = LibroManager() class Meta: verbose_name = 'Libro' verbose_name_plural = 'Libros' def __str__(self): return str(self.id) + '-' + self.titulo def optimize_image(sender, instance, **kwargs): print(" ==================== ") if instance.portada: portada = Image.open(instance.portada.path) portada.save(instance.portada.path, quality=20, optimize=True) post_save.connect(optimize_image, sender=Libro)<file_sep>/applications/lector/managers.py from django.db import models class PrestamoManager(models.Manager): """ managers para el modelo Lector """ def prestamo_all(self): resultado = self.filter.all() return resultado<file_sep>/applications/lector/models.py from django.db import models from django.db.models.signals import post_delete # from autor from applications.autor.models import Persona # from local apps from applications.libro.models import Libro # from .managers import PrestamoManager from .signals import update_libro_stok class Lector(Persona): class Meta: verbose_name = 'Lector' verbose_name_plural = 'Lectores' class Prestamo(models.Model): lector = models.ForeignKey( Lector, on_delete=models.CASCADE ) libro = models.ForeignKey( Libro, on_delete=models.CASCADE ) fecha_prestamo = models.DateField() fecha_devolucion = models.DateField( blank=True, null=True ) devuelto = models.BooleanField() objects = PrestamoManager() def save(self, *args, **kwargs): self.libro.stok = self.libro.stok - 1 self.libro.save() super(Prestamo, self).save(*args, **kwargs) def __str__(self): return self.libro.titulo # def update_libro_stok(sender, instance, **kwargs): # # actualizamos el stok si se elimina un prestamo # instance.libro.stok = instance.libro.stok + 1 # instance.libro.save() post_delete.connect(update_libro_stok, sender=Prestamo)<file_sep>/applications/lector/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path( 'prestamo/add/', views.AddPrestamo.as_view(), name="prestamo_add" ), path( 'prestamo/multiple-add/', views.AddMultiplePrestamo.as_view(), name="prestamo_add_multiple" ), ]<file_sep>/templates/libro/lista2.html <h1>Lista de Libros</h1> <ul> {% for l in lista_libros %} <li>{{ l.titulo }} - {{ l.fecha }}</li> {% endfor %} </ul><file_sep>/applications/lector/views.py from datetime import date from django.shortcuts import render from django.http import HttpResponseRedirect from django.views.generic.edit import FormView # local apps from .models import Prestamo, Lector # forms from .forms import PrestamoForm, MultiplePrestamoForm class RegistrarPrestamo(FormView): template_name = "lector/add_prestamo.html" form_class = PrestamoForm success_url = '.' def form_valid(self, form): # Prestamo.objects.create( # lector=form.cleaned_data['lector'], # libro=form.cleaned_data['libro'], # fecha_prestamo=date.today(), # devuelto=False # ) # prestamo = Prestamo( lector=form.cleaned_data['lector'], libro=form.cleaned_data['libro'], fecha_prestamo=date.today(), devuelto=False ) prestamo.save() libro = form.cleaned_data['libro'] libro.stok = libro.stok - 1 libro.save() return super(RegistrarPrestamo, self).form_valid(form) class AddPrestamo(FormView): template_name = "lector/add_prestamo.html" form_class = PrestamoForm success_url = '.' def form_valid(self, form): obj, created = Prestamo.objects.get_or_create( lector=form.cleaned_data['lector'], libro=form.cleaned_data['libro'], devuelto = False, defaults={ 'fecha_prestamo': date.today() } ) if created: return super(AddPrestamo, self).form_valid(form) else: return HttpResponseRedirect('/') class AddMultiplePrestamo(FormView): template_name = "lector/add_multiple_prestamo.html" form_class = MultiplePrestamoForm success_url = '.' def form_valid(self, form): # print(form.cleaned_data['lector']) print(form.cleaned_data['libros']) # prestamos = [] for l in form.cleaned_data['libros']: prestamo = Prestamo( lector=form.cleaned_data['lector'], libro=l, fecha_prestamo=date.today(), devuelto=False ) prestamos.append(prestamo) Prestamo.objects.bulk_create( prestamos ) return super(AddMultiplePrestamo, self).form_valid(form) <file_sep>/applications/lector/signals.py def update_libro_stok(sender, instance, **kwargs): # actualizamos el stok si se elimina un prestamo instance.libro.stok = instance.libro.stok + 1 instance.libro.save()<file_sep>/applications/lector/forms.py from django import forms from applications.libro.models import Libro from .models import Prestamo class PrestamoForm(forms.ModelForm): class Meta: model = Prestamo fields = ( 'lector', 'libro' ) class MultiplePrestamoForm(forms.ModelForm): libros = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple, ) class Meta: model = Prestamo fields = ( 'lector', ) def __init__(self, *args, **kwargs): super(MultiplePrestamoForm, self).__init__(*args, **kwargs) self.fields['libros'].queryset = Libro.objects.all() <file_sep>/biblioteca/urls.py """ biblioteca URL Configuration """ from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path('', include('applications.autor.urls')), re_path('', include('applications.libro.urls')), re_path('', include('applications.lector.urls')), ] <file_sep>/applications/autor/models.py from django.db import models # managers from .managers import AutorManager class Persona(models.Model): nombres = models.CharField( max_length=50 ) apellidos = models.CharField( max_length=50 ) nacionaldiad = models.CharField( max_length=20 ) edad = models.PositiveIntegerField() class Meta: abstract = True def __str__(self): return str(self.id) + '-' + self.nombres + '-' + self.apellidos class Autor(Persona): objects = AutorManager()<file_sep>/applications/libro/views.py from django.shortcuts import render from django.views.generic import ListView, DetailView # mdols local from .models import Libro class ListLibros(ListView): context_object_name = 'lista_libros' template_name = 'libro/lista.html' def get_queryset(self): palabra_clave = self.request.GET.get("kword", '') #fecha 1 f1 = self.request.GET.get("fecha1", '') #fecah 2 f2 = self.request.GET.get("fecha2", '') if f1 and f2: return Libro.objects.listar_libros2(palabra_clave, f1, f2) else: return Libro.objects.listar_libros(palabra_clave) class ListLibrosTrg(ListView): context_object_name = 'lista_libros' template_name = 'libro/lista.html' def get_queryset(self): palabra_clave = self.request.GET.get("kword", '') return Libro.objects.listar_libros_trg(palabra_clave) class ListLibros2(ListView): context_object_name = 'lista_libros' template_name = 'libro/lista2.html' def get_queryset(self): return Libro.objects.listar_libros_categoria('4') class LibroDetailView(DetailView): model = Libro template_name = "libro/detalle.html" <file_sep>/applications/autor/managers.py from django.db import models from django.db.models import Q class AutorManager(models.Manager): """ managers para el modelo autor """ def buscar_autor(self, kword): resultado = self.filter( nombre__icontains=kword ) return resultado def buscar_autor2(self, kword): resultado = self.filter( Q(nombre__icontains=kword) | Q(apellidos__icontains=kword) ) return resultado def buscar_autor3(self, kword): resultado = self.filter( nombre__icontains=kword ).exclude( Q(edad__icontains=35) | Q(edad__icontains=65) ) return resultado def buscar_autor4(self, kword): resultado = self.filter( edad__gt=40, edad__lt=65 ).order_by('apellidos', 'nombre', 'id') return resultado
667dd66c2cb23eef287428c16b0d3604ab17c8f6
[ "Python", "HTML" ]
16
Python
MariangelaC/biblioteca
1412e1db1732deb95adacab7c4425d9d4b54198a
eb052fb5f1766199bf3ec3ba11539a315014e960
refs/heads/master
<file_sep>#include "stdafx.h" #include "DllProvider.h" DllProvider::DllProvider() { this->hDll = LoadLibrary(PATH); if (this->hDll == INVALID_HANDLE_VALUE) { this->isBad = true; return; } this->serialize = GetProcAddress(this->hDll, SERIALIZE); this->deserialize = GetProcAddress(this->hDll, DESERIALIZE); if (!this->serialize || !this->deserialize) this->isBad = true; this->Deserialize(); } void DllProvider::ListEmptyMessage(void) const { std::wcout << L"list of binds is empty!" << std::endl; } void DllProvider::InvalidIndex(void) const { std::wcout << "Invalid index operation" << std::endl; } bool DllProvider::IsError(size_t index) const { if (!this->pairs) { this->ListEmptyMessage(); return false; } if (this->sizePairs >= index) { this->InvalidIndex(); return false; } return true; } DllProvider* DllProvider::getInstance(void) { if (!DllProvider::instance) DllProvider::instance = new DllProvider(); return DllProvider::instance; } bool DllProvider::Serialize(void) const { if (!this->pairs) return false; return reinterpret_cast <BOOL(*)(const PPAIR, DWORD)> (this->serialize) (this->pairs, this->sizePairs) == TRUE; } bool DllProvider::Deserialize(void) { return reinterpret_cast <BOOL(*)(PPAIR, LPDWORD)> (this->deserialize) (this->pairs, (LPDWORD)&this->sizePairs) == TRUE; } void DllProvider::get(size_t id) const { if (!this->IsError(id)) return; std::wcout << L"LPARAM: " << std::endl; for (size_t i = 0; i < this->pairs[id].sizeArr; ++i) std::wcout << L"\t" << i << ": " << this->pairs->arr[i] << std::endl; std::wcout << L"Is Caps: " << (bool)(this->pairs[id].isCaps) << std::endl; std::wcout << L"Is Shift: " << (bool)(this->pairs[id].isShift) << std::endl; std::wcout << L"Is Control: " << (bool)(this->pairs[id].isControl) << std::endl; std::wcout << L"Is Alt: " << (bool)(this->pairs[id].isAlt) << std::endl; std::wcout << L"Command: " << (this->pairs[id].strParams == nullptr ? L"Empty" : this->pairs[id].strParams) << std::endl; } void DllProvider::set(const LPARAM* pLparam, size_t cntParams, BOOL isCaps, BOOL isShift, BOOL isAlt, BOOL isControl, LPCWSTR strParam) { if (this->sizePairs == 0) this->pairs = (PPAIR)calloc(1, sizeof(Pair)); else this->pairs = (PPAIR)realloc(this->pairs, (this->sizePairs + 1) * sizeof(Pair)); ++this->sizePairs; for (size_t i = 0; i < this->sizePairs; ++i) { if (this->pairs[i].arr == nullptr) continue; if (this->pairs[i].arr[0] == pLparam[0] && this->pairs[i].sizeArr == cntParams) { bool isCorrect = false; for (size_t j = 1; j < this->sizePairs; ++j) { if (this->pairs[i].arr[j] != pLparam[j]) { isCorrect = true; break; } } if (!isCorrect) { std::wcout << L"Element already exists!" << std::endl; std::wcout << L"Try remove or edit element by index: " << i << std::endl; return; } } } Pair& p = this->pairs[this->sizePairs - 1]; p.sizeArr = cntParams; p.arr = (LPARAM*)calloc(p.sizeArr, sizeof(LPARAM)); memcpy_s(p.arr, p.sizeArr * sizeof(LPARAM), pLparam, cntParams * sizeof(LPARAM)); p.isCaps = isCaps; p.isShift = isShift; p.isAlt = isAlt; p.isControl = isControl; p.strParams = (LPWSTR)calloc(wcslen(strParam) + 1, sizeof(WCHAR)); memcpy_s(p.strParams, wcslen(strParam) * sizeof(wchar_t), strParam, wcslen(strParam) * sizeof(wchar_t)); this->Serialize(); } void DllProvider::edit(size_t id, LPCWSTR strParam) { if (!this->IsError(id)) return; if (strParam == nullptr || !wcscmp(strParam, L"")) { this->remove(id); return; } free(this->pairs[id].strParams); this->pairs[id].strParams = (LPWSTR)calloc(wcslen(strParam) + 1, sizeof(WCHAR)); wcscpy_s(this->pairs[id].strParams, (wcslen(strParam) + 1), strParam); } void DllProvider::remove(size_t id) { if (!this->IsError(id)) return; free(this->pairs[id].arr); free(this->pairs[id].strParams); if (this->sizePairs == 1) { free(this->pairs); this->pairs = nullptr; return; } for (size_t i = id; i < this->sizePairs - 1; ++i) this->pairs[i] = this->pairs[i + 1]; this->sizePairs -= 1; this->pairs = (PPAIR)realloc(this->pairs, this->sizePairs * sizeof(Pair)); } void DllProvider::list(void) const { if (this->sizePairs == 0) { this->ListEmptyMessage(); return; } std::wcout << " id:\tButtons:\tCaps:\tShift:\tControl:\tAlt:\tCommand:" << std::endl; for (size_t i = 0; i < this->sizePairs; ++i) { std::wcout << ' ' << i << ' \t' << this->pairs[i].arr[0] << '\t' << this->pairs[i].isCaps << '\t' << this->pairs[i].isControl << '\t' << this->pairs[i].isAlt << '\t' << this->pairs[i].isAlt << '\t' << this->pairs[i].strParams << std::endl; for (size_t j = 1; j < this->pairs[i].sizeArr; ++j) std::wcout << L" \t" << this->pairs[i].arr[j]; } } DllProvider::~DllProvider(void) { if (!this->hDll || this->hDll != INVALID_HANDLE_VALUE) FreeLibrary(this->hDll); if (this->pairs) { free(this->pairs); this->pairs = nullptr; } }<file_sep>#include "stdafx.h" #include "Parser.h" void Parser::Get(void) const { if (this->argc != 3) { std::wcout << L"Incorrect count of params!" << std::endl; std::wcout << L"\t-g <id> - get data by id" << std::endl; return; } size_t index = atoi(this->args[2]); if (index == 0 && this->args[2][0] != '0') { std::wcout << L"Incorrect value of index!" << std::endl; std::wcout << L"Index must be a numeric value" << std::endl; return; } DllProvider::getInstance()->get(index); } void Parser::Set(void) const { if (this->argc < 8) { std::wcout << L"Error of count of params! This variant must have this params:" << std::endl; std::wcout << L"\t-s <id button> <isCaps> <isShift> <isControl> <isAlt> <command> - add\nbind" << std::endl; std::wcout << L"You can add more than one button. Separate codes by space" << std::endl; return; } size_t cntParams = this->argc - 7; std::auto_ptr<LPARAM> arr(new LPARAM[cntParams]); for (size_t i = 0; i < cntParams; ++i) { int id = atoi(this->args[2 + i]); if (id == 0 && this->args[2 + i][0] != '0') { std::wcout << L"Incorrect param of id button! Value must be integer!" << std::endl; return; } arr.get()[i] = (LPARAM)id; } std::auto_ptr<int> pArr(new int[1 << 2]); int(*pFn)(const char*) = [](const char* str) { if (strlen(str) != 1) return -1; if (str[0] == '1' || str[0] == 't' || str[0] == 'y') return 1; if (str[0] == '0' || str[0] == 'f' || str[0] == 'n') return 0; return -1; }; for (size_t i = 0; i < 1 << 2; ++i) { pArr.get()[i] = pFn(this->args[this->argc - 5 + i]); if (pArr.get()[i] == -1) { std::wcout << L"Incorrect logical param!" << std::endl; std::wcout << L"Params must be 0, f or n - for false, 1, t or y - for true" << std::endl; return; } } if (!strlen(this->args[this->argc - 1])) { std::wcout << L"Empty string of params! Bind don't added" << std::endl; return; } std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv; DllProvider::getInstance()->set(arr.get(), cntParams, pArr.get()[0], pArr.get()[1], pArr.get()[2], pArr.get()[3], (conv.from_bytes(this->args[this->argc - 1]).c_str())); } void Parser::Edit(void) const { if (this->argc != 4) { std::wcout << L"Incorrect count of params!" << std::endl; std::wcout << L"\t-e <id> <command> - edit bind" << std::endl; return; } size_t index = atoi(this->args[2]); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv; std::wstring wstr = conv.from_bytes(this->args[3]); DllProvider::getInstance()->edit(index, wstr.data()); } void Parser::Remove(void) const { if (this->argc != 3) { std::wcout << L"Incorrect count of params!" << std::endl; std::wcout << L"\t-r <id> - remove bind by id" << std::endl; return; } size_t index = atoi(this->args[2]); if (index == 0 && this->args[2][0] != '0') { std::wcout << L"Incorrect value of index!" << std::endl; std::wcout << L"Index must be a numeric value" << std::endl; return; } DllProvider::getInstance()->remove(index); } void Parser::List(void) { if (this->argc != 2) { std::wcout << L"This command must have only -l param" << std::endl; return; } DllProvider::getInstance()->list(); } <file_sep>#pragma once #include "DllProvider.h" #include <locale> #include <codecvt> #include <string> #include <memory> class Parser { int argc = 0; char** args = nullptr; public: Parser() = delete; Parser(int argc, char** args) : argc(argc), args(args) {} Parser(const Parser&) = delete; Parser(Parser&&) = delete; Parser& operator =(const Parser&) = delete; Parser& operator =(Parser&&) = delete; ~Parser() = default; void Get(void) const; void Set(void) const; void Edit(void) const; void Remove(void) const; void List(void); }; <file_sep>// BindHandler.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include "Pair.h" #include "DllProvider.h" #include "Parser.h" #include <string> //g(get) id //s(set) buttons, command //e(edit) id, comand //r(remove) id //l(list) //h, ?, help DllProvider* DllProvider::instance = nullptr; void Help(void); void ShowError(void); void ShowErrorLoadDLL(void); int main(int argc, char** args) { std::boolalpha(std::wcout); Parser p(argc, args); try { if (argc == 1) { Help(); return 0; } if (DllProvider::getInstance()->bad()) { ShowErrorLoadDLL(); return 2; } std::string strParam(args[1]); if (strParam.length() != 2) { if (!strParam.compare("-help") || !strParam.compare("/help")) { Help(); return 0; } ShowError(); return 1; } switch (strParam[1]) { case '?': case 'h': Help(); break; case 'g': p.Get(); break; case 's': p.Set(); break; case 'e': p.Edit(); break; case 'r': p.Remove(); break; case 'l': p.List(); break; } } catch (const std::exception& ex) { std::cout << ex.what(); } catch (...) { std::wcout << L"Unhandled exception" << std::endl; } return 0; } void Help(void) { std::wcout << L"List of commands:" << std::endl; std::wcout << L"\t-g <id> - get data by id" << std::endl; std::wcout << L"\t-s <id button> <isCaps> <isShift> <isControl> <isAlt> <command> - add\nbind" << std::endl; std::wcout << L"\t-e <id> <command> - edit bind" << std::endl; std::wcout << L"\t-r <id> - remove bind by id" << std::endl; std::wcout << "\t-l - get list data" << std::endl; std::wcout << "\t-h, -?, -help - get help about programm" << std::endl; std::wcout << "\tBy VoidPtr (c)2018" << std::endl; } void ShowError(void) { std::wcout << L"Incorrect param!" << std::endl; std::wcout << L"Use -h, -?, -help for help" << std::endl; } void ShowErrorLoadDLL(void) { std::wcout << L"Error of load DLL!" << std::endl; std::wcout << L"Try reinstall programm" << std::endl; }<file_sep>#pragma once #include <Windows.h> #include <malloc.h> #include <string.h> #include <stdio.h> #define PATH L".\\combination.data" #define EXPORT __declspec(dllexport) typedef struct Pair { LPDWORD arr; //arr iKey not LPARAM DWORD sizeArr; BOOL isCaps, isShift, isControl, isAlt; LPWSTR strParams; } Pair; typedef Pair* PPAIR; typedef union ByteData { INT32 val; BOOL arr[4]; } ByteData; BOOL EXPORT Serialize(const PPAIR pairArr, DWORD size); BOOL EXPORT Deserialize(PPAIR pairArr, LPDWORD size); DWORD EXPORT IsFileEdit(PLARGE_INTEGER sizeFile); BOOL EXPORT Serialize(const PPAIR pairArr, DWORD size) { // HANDLE hFile = CreateFile(PATH, // GENERIC_WRITE, // FILE_SHARE_READ, // NULL, // CREATE_ALWAYS, // FILE_ATTRIBUTE_NORMAL, // NULL); // if (hFile == INVALID_HANDLE_VALUE) // return FALSE; // // DWORD iCountWrited = 0; // if (!WriteFile(hFile, &size, sizeof(DWORD), &iCountWrited, NULL) && // sizeof(DWORD) != iCountWrited) // goto err; // for (DWORD i = 0; i < size; ++i) // { // if (!WriteFile(hFile, &pairArr[i].sizeArr, sizeof(DWORD), &iCountWrited, NULL) && // sizeof(DWORD) != iCountWrited) // goto err; // //if (!WriteFile(hFile, pairArr[i].arr, sizeof(DWORD)*pairArr[i].sizeArr, &iCountWrited, NULL))// // //goto err; // for (size_t j = 0; i < pairArr[i].sizeArr; ++j) // { // if (!WriteFile(hFile, &pairArr[i].arr[j], sizeof(DWORD), &iCountWrited, NULL) && // sizeof(DWORD) != iCountWrited) // goto err; // } // // ByteData bd = { 0 }; // bd.arr[0] = pairArr[i].isCaps; // bd.arr[1] = pairArr[i].isShift; // bd.arr[2] = pairArr[i].isControl; // bd.arr[3] = pairArr[i].isAlt; // if (!WriteFile(hFile, &bd.val, sizeof(INT32), &iCountWrited, NULL) && // sizeof(INT32) != iCountWrited) // goto err; // DWORD sizeStr = wcslen(pairArr[i].strParams); // if (!WriteFile(hFile, &sizeStr, sizeof(DWORD), &iCountWrited, NULL) && // sizeof(DWORD) != iCountWrited) // goto err; // if (!WriteFile(hFile, pairArr[i].strParams, sizeStr * sizeof(WCHAR), &iCountWrited, NULL) && // sizeStr * sizeof(WCHAR) != iCountWrited) // goto err; // } // // CloseHandle(hFile); // return TRUE; //err: // CloseHandle(hFile); // return FALSE; if (pairArr == NULL) return FALSE; if (size == 0) return TRUE; FILE* f = NULL; if (_wfopen_s(&f, PATH, L"w")) return FALSE; fwprintf(f, L"%d\n\n", size); for (size_t i = 0; i < size; ++i) { fwprintf(f, L"%d %d\n", pairArr[i].sizeArr, wcslen(pairArr[i].strParams)); for (size_t j = 0; j < pairArr[i].sizeArr; ++j) { fwprintf(f, L"%d", pairArr[i].arr[j]); fwprintf(f, j == pairArr[i].sizeArr - 1 ? L"\n" : L" "); } fwprintf(f, L"%s\n", pairArr[i].strParams); fwprintf(f, L"%d %d %d %d\n\n", pairArr[i].isCaps, pairArr[i].isShift, pairArr[i].isControl, pairArr[i].isAlt); } fclose(f); return TRUE; } BOOL EXPORT Deserialize(PPAIR pairArr, LPDWORD size) { // if (!size || !pairArr) // { // for (DWORD i = 0; i < *size; ++i) // { // free(pairArr[i].arr); // free(pairArr[i].strParams); // } // *size = 0; // free(pairArr); // } // // HANDLE hFile = CreateFile(PATH, // GENERIC_READ, // FILE_SHARE_READ, // NULL, // OPEN_ALWAYS, // FILE_ATTRIBUTE_NORMAL, // NULL); // if (hFile == INVALID_HANDLE_VALUE) // return FALSE; // // DWORD iCountReaded = 0; // if (!ReadFile(hFile, size, sizeof(DWORD), &iCountReaded, NULL) && // sizeof(DWORD) != iCountReaded) // goto err; // pairArr = (PPAIR)calloc(*size, sizeof(Pair)); // for (DWORD i = 0; i < *size; ++i) // { // if (!ReadFile(hFile, &pairArr[i].sizeArr, sizeof(DWORD), &iCountReaded, NULL) || iCountReaded != sizeof(DWORD)) // goto err; // pairArr[i].arr = (LPDWORD)calloc(pairArr[i].sizeArr, sizeof(DWORD)); // //if (!ReadFile(hFile, pairArr[i].arr, sizeof(DWORD) * pairArr[i].sizeArr, &iCountReaded, NULL) || iCountReaded != sizeof(DWORD) * pairArr[i].sizeArr) // // goto err; // for (size_t j = 0; j < pairArr[i].sizeArr; ++j) // { // if (!ReadFile(hFile, &pairArr[i].arr[j], sizeof(DWORD), &iCountReaded, NULL) && // sizeof(DWORD) != iCountReaded) // goto err; // } // // ByteData bd = { 0 }; // if (!ReadFile(hFile, &bd.val, sizeof(INT32), &iCountReaded, NULL) || iCountReaded != sizeof(INT32)) // goto err; // pairArr[i].isCaps = bd.arr[0]; // pairArr[i].isShift = bd.arr[1]; // pairArr[i].isControl = bd.arr[2]; // pairArr[i].isAlt = bd.arr[3]; // // DWORD sizeStr = 0; // if (!ReadFile(hFile, &sizeStr, sizeof(DWORD), &iCountReaded, NULL) || iCountReaded != sizeof(DWORD)) // goto err; // pairArr[i].strParams = (LPWSTR)calloc(sizeStr + 1, sizeof(WCHAR)); // if (!ReadFile(hFile, pairArr[i].strParams, sizeStr * sizeof(WCHAR), &iCountReaded, NULL) || iCountReaded != sizeStr * sizeof(WCHAR)) // goto err; // } // CloseHandle(hFile); // return TRUE; //err: // CloseHandle(hFile); // return FALSE; if (pairArr != NULL && *size != 0) { for (size_t i = 0; i < *size; ++i) { free(pairArr[i].arr); free(pairArr[i].strParams); } free(pairArr); *size = 0; } FILE* f = NULL; if (_wfopen_s(&f, PATH, L"r")) return FALSE; fwscanf_s(f, L"%d\n\n", size); pairArr = (PPAIR)calloc(*size, sizeof(Pair)); for (size_t i = 0; i < *size; ++i) { DWORD sizeStr = 0; fwscanf_s(f, L"%d %d\n", &pairArr[i].sizeArr, &sizeStr); pairArr[i].arr = (LPDWORD)calloc(pairArr[i].sizeArr, sizeof(DWORD)); pairArr[i].strParams = (LPWSTR)calloc(sizeStr + 1, sizeof(WCHAR)); for (size_t j = 0; j < pairArr[i].sizeArr; ++j) { fwscanf_s(f, L"%d", &pairArr[i].arr[j]); fwscanf_s(f, j == pairArr[i].sizeArr - 1 ? L"\n" : L" "); } fgetws(pairArr[i].strParams, sizeStr, f); //fwscanf_s(f, L"%s\n", pairArr[i].strParams); int iArr[4] = { 0 }; fwscanf_s(f, L"%d %d %d %d\n\n", &iArr[0], &iArr[1], &iArr[2], &iArr[3]); pairArr[i].isCaps = iArr[0] == 0 ? FALSE : TRUE; pairArr[i].isShift = iArr[1] == 0 ? FALSE : TRUE; pairArr[i].isControl = iArr[2] == 0 ? FALSE : TRUE; pairArr[i].isAlt = iArr[3] == 0 ? FALSE : TRUE; } fclose(f); return TRUE; } //Return val: 0 - good, 1 - value edit, 2 - error DWORD EXPORT IsFileEdit(PLARGE_INTEGER sizeFile) { LARGE_INTEGER tmp; HANDLE hFile = CreateFile(PATH, GENERIC_READ, FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return 2; GetFileSizeEx(hFile, &tmp); DWORD result = tmp.QuadPart == sizeFile->QuadPart ? 0 : 1; if (result) sizeFile->QuadPart = tmp.QuadPart; CloseHandle(hFile); return result; }<file_sep>#pragma once #include "stdafx.h" #include "Pair.h" #define PATH L"FileSystemProvider.dll" #define SERIALIZE "Serialize" #define DESERIALIZE "Deserialize" #define IS_FILE_EDIT "IsFileEdit" class DllProvider { HMODULE hDll = nullptr; FARPROC serialize = nullptr; FARPROC deserialize = nullptr; LARGE_INTEGER li = { 0 }; PPAIR pairs = nullptr; size_t sizePairs = 0; bool isBad = false; DllProvider(void); static DllProvider* instance; void ListEmptyMessage(void) const; void InvalidIndex(void) const; bool IsError(size_t index) const; public: static DllProvider* getInstance(void); bool Serialize(void) const; bool Deserialize(void); void get(size_t id) const; void set(const LPARAM* pLparam, size_t cntParams, BOOL isCaps, BOOL isShift, BOOL isAlt, BOOL isControl, LPCWSTR strParam); void edit(size_t id, LPCWSTR strParam); void remove(size_t id); void list(void) const; inline bool bad(void) const throw() { return this->isBad; } ~DllProvider(void); }; <file_sep>#pragma once #include "stdafx.h" typedef struct Pair { LPARAM* arr; DWORD sizeArr; BOOL isCaps, isShift, isControl, isAlt; LPWSTR strParams; } Pair; typedef Pair* PPAIR;
8be10217104100f3c973490cb2115bd625277c1d
[ "C", "C++" ]
7
C++
VoidPtrYT/BindButton
bd4a19dbc364b01b9d995833628251c68be35226
e5b6de3f767c1bc6c19bb828d53ca2f6cdcd273b
refs/heads/master
<file_sep># Rocnikova-prace https://github.com/Shinigun/Rocnikova-prace.git <file_sep><html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css">@import url("css.css");</style> </head> <body> <?php function nactiTridu($trida) { require("tridy/$trida.php"); } spl_autoload_register("nactiTridu"); if (isset($_POST['Jmeno']) && isset($_POST['DatumNarozeni']) && isset($_POST['Prijmeni']) && isset($_POST['Obor'])){ db::connect(); $Jmeno = filter_input(INPUT_POST,'Jmeno'); $DatumNarozeni = filter_input(INPUT_POST,'DatumNarozeni'); $Prijmeni = filter_input(INPUT_POST,'Prijmeni'); $Obor = filter_input(INPUT_POST,'Obor'); $id = filter_input(INPUT_POST, 'id'); db::update($id, $Jmeno, $Prijmeni, $DatumNarozeni, $Obor); } if(isset($_POST['Jmeno'])){ if ($_POST['Jmeno'] && $_POST['Prijmeni'] && $_POST['DatumNarozeni'] != '') { db::connect(); $Jmeno = filter_input(INPUT_POST, 'Jmeno'); $Prijmeni = filter_input(INPUT_POST, 'Prijmeni'); $DatumNarozeni = filter_input(INPUT_POST, 'DatumNarozeni'); if ($_POST['Obor'] != '') { $Obor = filter_input(INPUT_POST, 'Obor'); } else { $Obor = ''; } db::novy($Jmeno, $Prijmeni, $DatumNarozeni, $Obor); } } db::connect(); db::dotaz(); db::vypis(); ?> </body> </html><file_sep><?php class db { private static $pripojeni; /** * @param recognize $host umístění databáze * @param string $name vložení uživatele pro připojení * @param string $heslo vložení hesla pro připojení * @param string $databaze připojení k databázy */ public static function connect (){ $host = 'localhost'; $name = 'root'; $heslo = ''; $databaze = 'rocnikovka'; self::$pripojeni = mysqli_connect($host, $name, $heslo, $databaze); mysqli_set_charset(self::$pripojeni, "utf8"); } /** * $param $dotaz zapsání dotazu * @param $vysledek * @return @vysledek vrácení výsledku dotazu */ public static function dotaz(){ $dotaz = mysqli_query(self::$pripojeni, "SELECT s.id, Jmeno, Prijmeni, DatumNarozeni, Nazev FROM studenti AS s LEFT JOIN obory AS o ON s.Obor = o.id"); $vysledek = mysqli_fetch_all($dotaz, MYSQLI_ASSOC); return $vysledek; } /** * @param $i * @param $v */ public static function vypis(){ echo ("<table border='1'><tr><th>Id</th><th>Jméno</th><th>Příjmení</th><th>Datum narození</th><th>Obor</th><th><form action=form.php method='POST'><input type='image' src='icons/new.png' style='width: 30px; height: 30px'></form></th></tr>"); $i = 0; foreach (self::dotaz() as $v){ echo ('<tr id=$i><td>'.$v['id'].'</td>'); echo ('<td>'.$v['Jmeno'].'</td>'); echo ('<td>'.$v['Prijmeni'].'</td>'); echo ('<td>'.$v['DatumNarozeni'].'</td>'); echo ('<td>'.$v['Nazev'].'</td>'); echo ('<td><form action="update.php?radek='.$i.'" method="POST">'.'<input type="image" src="icons/change.png" style="width: 30px; height: 30px">'.'</td></tr></form>'); $i ++; } echo ('<table>'); } public static function novy($Jmeno, $Prijmeni, $DatumNarozeni, $Obor){ if ($Obor != ''){ $dotaz = mysqli_query(self::$pripojeni, "INSERT INTO studenti (Jmeno, Prijmeni, DatumNarozeni, Obor) VALUES ('".$Jmeno."', '".$Prijmeni."', '".$DatumNarozeni."', '".$Obor."')"); } else { $dotaz = mysqli_query(self::$pripojeni, "INSERT INTO studenti (Jmeno, Prijmeni, DatumNarozeni) VALUES ('".$Jmeno."', '".$Prijmeni."', '".$DatumNarozeni."'"); } } public static function update($id, $Jmeno, $Prijmeni, $DatumNarozeni, $Obor){ $dotaz = mysqli_query(self::$pripojeni, "UPDATE studenti SET Jmeno ='".$Jmeno."', Prijmeni ='".$Prijmeni."', DatumNarozeni ='".$DatumNarozeni."', Obor ='".$Obor."' WHERE id=".$id.""); } public static function napln(){ $radek = filter_input(INPUT_GET, 'radek'); $id = self::dotaz()[$radek]['id']; $dotaz = mysqli_query(self::$pripojeni, "SELECT * FROM studenti WHERE id='".$id."'"); $napln = $vysledek = mysqli_fetch_all($dotaz, MYSQLI_ASSOC); return $napln; } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.4.14 -- http://www.phpmyadmin.net -- -- Počítač: 127.0.0.1 -- Vytvořeno: Úte 12. dub 2016, 11:40 -- Verze serveru: 5.6.26 -- Verze PHP: 5.6.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Databáze: `rocnikovka` -- -- -------------------------------------------------------- -- -- Struktura tabulky `obory` -- CREATE TABLE IF NOT EXISTS `obory` ( `id` int(10) unsigned NOT NULL, `Nazev` varchar(45) NOT NULL, `DelkaStudia` tinyint(5) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- -- Vypisuji data pro tabulku `obory` -- INSERT INTO `obory` (`id`, `Nazev`, `DelkaStudia`) VALUES (1, 'Automechanik', 3), (2, 'Informační technologie', 4), (3, 'Elektrikář', 3), (4, 'Prodavač', 2); -- -------------------------------------------------------- -- -- Struktura tabulky `studenti` -- CREATE TABLE IF NOT EXISTS `studenti` ( `id` int(10) unsigned NOT NULL, `Jmeno` varchar(45) DEFAULT NULL, `Prijmeni` varchar(45) NOT NULL, `DatumNarozeni` date DEFAULT NULL, `Obor` int(10) unsigned NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; -- -- Vypisuji data pro tabulku `studenti` -- INSERT INTO `studenti` (`id`, `Jmeno`, `Prijmeni`, `DatumNarozeni`, `Obor`) VALUES (4, 'Pavel', 'Kos', '1997-08-20', 1), (5, 'Petr', 'Pevel', '1999-04-08', 2), (6, 'Vanesa', 'Veselá', '2000-10-05', 4), (7, 'Lukaš', 'Moris', '1998-09-26', 3), (8, 'Marie', 'Červáková', '1996-07-24', 2); -- -- Klíče pro exportované tabulky -- -- -- Klíče pro tabulku `obory` -- ALTER TABLE `obory` ADD PRIMARY KEY (`id`); -- -- Klíče pro tabulku `studenti` -- ALTER TABLE `studenti` ADD PRIMARY KEY (`id`), ADD KEY `fk_Studenti_Obory_idx` (`Obor`); -- -- AUTO_INCREMENT pro tabulky -- -- -- AUTO_INCREMENT pro tabulku `obory` -- ALTER TABLE `obory` MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5; -- -- AUTO_INCREMENT pro tabulku `studenti` -- ALTER TABLE `studenti` MODIFY `id` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=9; -- -- Omezení pro exportované tabulky -- -- -- Omezení pro tabulku `studenti` -- ALTER TABLE `studenti` ADD CONSTRAINT `fk_Studenti_Obory` FOREIGN KEY (`Obor`) REFERENCES `obory` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
a6ec8f77a5c7831c30e3e0f1fc53e44c6c794418
[ "Markdown", "SQL", "PHP" ]
4
Markdown
Shinigun/Rocnikova-prace
07cb108faf193ee67b5f95d23dcfbbd554120a03
45c4a28c6ae9038094c6643a90c71a10da6edde1
refs/heads/master
<file_sep>import { FormlyConfig } from 'react-native-formly'; import _ from 'lodash'; const { FieldsConfig, WrappersConfig, ControllersConfig, ValidationsConfig } = FormlyConfig; // require formly types const inputComponent = require('./types/formlyTextInput'); const textareaComponent = require('./types/formlyTextarea'); const radioComponent = require('./types/formlyRadio'); const checkboxComponent = require('./types/formlyCheckbox'); const selectComponent = require('./types/formlySelect'); // require formly wrappers const labelWrapper = require('./wrappers/formlyLabel'); const descOrErrorWrapper = require('./wrappers/formlyDescriptionOrError'); FieldsConfig.addType([ { name: 'input', controller: ['inputTypeValidators', 'templateOptionsValidators'], component: inputComponent }, { name: 'textarea', controller: ['inputTypeValidators', 'templateOptionsValidators'], component: textareaComponent }, { name: 'radio', wrapper: ['label', 'descriptionOrError'], controller: ['templateOptionsValidators'], component: radioComponent }, { name: 'checkbox', wrapper: ['descriptionOrError'], controller: ['templateOptionsValidators'], component: checkboxComponent }, { name: 'select', controller: ['templateOptionsValidators'], component: selectComponent } ]); WrappersConfig.setWrapper([ { name: 'label', component: labelWrapper }, { name: 'descriptionOrError', component: descOrErrorWrapper } ]); ControllersConfig.addType([ { name: 'templateOptionsValidators', controller: { componentWillMount() { // for initial component adding validation const to = this.props.config.templateOptions || {}; const fieldValidator = this.state.fieldValidator; if (fieldValidator) { if (to.required) { fieldValidator.subscribeToValidation('required', to.required); } else { fieldValidator.unsubscribeToValidation('required'); } if (to.pattern) { fieldValidator.subscribeToValidation('pattern', to.pattern); } else { fieldValidator.unsubscribeToValidation('pattern'); } if (to.minlength) { fieldValidator.subscribeToValidation('minlength', to.minlength); } else { fieldValidator.unsubscribeToValidation('minlength'); } if (to.maxlength) { fieldValidator.subscribeToValidation('maxlength', to.maxlength); } else { fieldValidator.unsubscribeToValidation('maxlength'); } } }, componentWillUpdate(nextProps) { const to = nextProps.config.templateOptions || {}; const fieldValidator = this.state.fieldValidator; if (fieldValidator) { if (to.required) { fieldValidator.subscribeToValidation('required', to.required); } else { fieldValidator.unsubscribeToValidation('required'); } if (to.pattern) { fieldValidator.subscribeToValidation('pattern', to.pattern); } else { fieldValidator.unsubscribeToValidation('pattern'); } if (to.minlength) { fieldValidator.subscribeToValidation('minlength', to.minlength); } else { fieldValidator.unsubscribeToValidation('minlength'); } if (to.maxlength) { fieldValidator.subscribeToValidation('maxlength', to.maxlength); } else { fieldValidator.unsubscribeToValidation('maxlength'); } } } } }, { name: 'inputTypeValidators', controller: { componentWillMount() { // for initial component adding validation const to = this.props.config.templateOptions || {}; const fieldValidator = this.state.fieldValidator; if (fieldValidator) { fieldValidator.unsubscribeToValidation(['email', 'number', 'url']); switch (to.type) { case 'number': case 'email': case 'url': fieldValidator.subscribeToValidation(to.type); break; default: break; } } }, componentWillUpdate(nextProps) { const to = nextProps.config.templateOptions || {}; const fieldValidator = this.state.fieldValidator; if (fieldValidator) { fieldValidator.unsubscribeToValidation(['email', 'number', 'url']); switch (to.type) { case 'number': case 'email': case 'url': fieldValidator.subscribeToValidation(to.type); break; default: break; } } } } } ]); ValidationsConfig.addType({ required: { expression({ viewValue }) { let isValid; if (_.isString(viewValue)) { isValid = _.trim(viewValue).length !== 0; } else if (_.isArray(viewValue) || _.isPlainObject(viewValue)) { isValid = !_.isEmpty(viewValue); } else { isValid = viewValue !== null && viewValue !== undefined; } return isValid; } }, url: { expression({ viewValue }) { const regex = /^([a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?)?$/i; return viewValue === undefined || viewValue === null || regex.test(viewValue); } }, email: { expression({ viewValue }) { // eslint-disable-next-line const regex = /^((?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*)?$/; return viewValue === undefined || viewValue === null || regex.test(viewValue); } }, number: { expression({ viewValue }) { // eslint-disable-next-line const regex = /^(\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*)?$/; return viewValue === undefined || viewValue === null || regex.test(viewValue); } }, pattern: { expression({ viewValue, param }) { const stringifiedViewValue = _.isString(viewValue) ? viewValue : ''; return new RegExp(param).test(stringifiedViewValue); } }, minlength: { expression({ viewValue, param }) { return viewValue && viewValue.length >= param; } }, maxlength: { expression({ viewValue, param }) { return (!viewValue && param >= 0) || (viewValue && !(viewValue.length > param)); } } }); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, StyleSheet } from 'react-native'; const FormlyLabel = (props) => { const to = props.config.templateOptions || {}; const fieldValidationResult = props.fieldValidation || {}; return ( <View style={[{ marginVertical: 1 }, defaultComponentStyle.Container]}> {to.label ? <Text style={[defaultComponentStyle.Label, { color: fieldValidationResult.isValid ? undefined : 'rgba(213, 0, 0, 1)' }]}>{to.label + (to.required ? ' *' : '')}</Text> : null} {props.children} </View> ); }; FormlyLabel.propTypes = { config: PropTypes.shape({ templateOptions: PropTypes.shape({ label: PropTypes.string, required: PropTypes.bool }) }).isRequired, fieldValidation: PropTypes.shape({ messages: PropTypes.object }), children: PropTypes.element }; const defaultComponentStyle = StyleSheet.create({ Label: { color: 'rgba(0, 0, 0, .38)', fontSize: 12, paddingTop: 32 }, Container: { flex: 1 } }); module.exports = FormlyLabel; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Ripple from 'react-native-material-ripple'; import { Text, View, Easing, Animated } from 'react-native'; class RadioButton extends Component { state = { innerScaleValue: new Animated.Value(this.props.isSelected ? 1 : 0) } componentWillReceiveProps(nextProps) { if (this.props.isSelected !== nextProps.isSelected) { this.selectionChanged(nextProps.isSelected); } } selectionChanged = (isSelected) => { if (isSelected) { Animated.timing(this.state.innerScaleValue, { toValue: 1, duration: 400, easing: Easing.bounce }).start(); } else { Animated.timing(this.state.innerScaleValue, { toValue: 0, duration: 150, easing: Easing.bounce }).start(); } } _getRadioButtonColor = () => { let color; if (this.props.disabled) { color = this.props.disabledColor; } else if (this.props.isSelected) { color = this.props.tintColor; } else { color = this.props.baseColor; } return color; } render() { const { scale, innerToOuterRatio } = this.props; const color = this._getRadioButtonColor(); const outerSize = 24 * scale; const outerBorderWidth = 3 * scale; const rippleSize = outerSize * 2; const maxInnerSize = (outerSize - (outerBorderWidth * 2)) * innerToOuterRatio; const currentInnerSize = this.state.innerScaleValue.interpolate({ inputRange: [0, 1], outputRange: [0, maxInnerSize] }); // give the label the same padding arround the radio const labelPaddingHorizontal = this.props.labelHorizontal ? 0 : outerSize / 2; return ( <View style={{ flexDirection: this.props.labelHorizontal ? 'row' : 'column', alignItems: 'center', alignSelf: 'flex-start' }}> <Ripple rippleColor={color} rippleOpacity={1} rippleDuration={400} rippleSize={rippleSize} rippleContainerBorderRadius={rippleSize / 2} rippleCentered style={{ height: rippleSize, width: rippleSize }} onPress={() => { if (this.props.onButtonPress && !this.props.disabled) { this.props.onButtonPress(this.props.id); } } } > <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }} > <View style={{ width: outerSize, height: outerSize, borderRadius: outerSize / 2, borderColor: color, borderWidth: outerBorderWidth, alignItems: 'center', justifyContent: 'center' }} > <Animated.View style={ { width: currentInnerSize, height: currentInnerSize, borderRadius: maxInnerSize / 2, backgroundColor: color } } /> </View> </View> </Ripple> <View style={{ paddingHorizontal: labelPaddingHorizontal }}> <Text style={[ this.props.labelStyle, { color: this.props.disabled ? this.props.disabledColor : this.props.labelColor } ]} > {this.props.label} </Text> </View> </View> ); } } RadioButton.defaultProps = { onButtonPress: () => { }, isSelected: false, tintColor: 'rgb(0, 145, 234)', disabledColor: 'rgba(0,0,0,0.26)', baseColor: 'rgba(0,0,0,0.54)', scale: 1, innerToOuterRatio: 0.65, labelHorizontal: true, labelColor: 'rgba(0, 0, 0, .87)' }; RadioButton.propTypes = { id: PropTypes.any, onButtonPress: PropTypes.func, isSelected: PropTypes.bool, label: PropTypes.string, tintColor: PropTypes.string, disabledColor: PropTypes.string, baseColor: PropTypes.string, scale: PropTypes.number, disabled: PropTypes.bool, innerToOuterRatio: PropTypes.number, labelHorizontal: PropTypes.bool, labelColor: PropTypes.string, labelStyle: PropTypes.object }; module.exports = RadioButton; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, Text, StyleSheet } from 'react-native'; class FormlyDescriptionOrError extends Component { _getText = () => { const to = this.props.config.templateOptions || {}; const fieldValidationResult = this.props.fieldValidation || {}; const messages = fieldValidationResult.messages; if (messages && Object.keys(messages).length !== 0) { return ( <Text style={defaultComponentStyle.VaildationErrorText}> {Object.values(messages)[0]} </Text> ); } else if (to.description) { return <Text style={defaultComponentStyle.DescriptionText}>{to.description}</Text>; } return null; } render() { return ( <View style={defaultComponentStyle.Container}> {this.props.children} {this._getText()} </View> ); } } FormlyDescriptionOrError.propTypes = { config: PropTypes.shape({ key: PropTypes.string.isRequired, templateOptions: PropTypes.shape({ description: PropTypes.string }) }).isRequired, fieldValidation: PropTypes.shape({ messages: PropTypes.object }), children: PropTypes.element }; const defaultComponentStyle = StyleSheet.create({ VaildationErrorText: { color: 'rgba(213, 0, 0, 1)', fontSize: 12 }, DescriptionText: { color: 'rgba(0, 0, 0, .38)', fontSize: 12 }, Container: { flex: 1 } }); module.exports = FormlyDescriptionOrError; <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { View } from 'react-native'; import RadioButton from './radioButton'; class RadioGroup extends Component { state = {} componentWillMount() { if (!_.isEqual(this.state.selectedKey, this.props.selectedItem)) { if (this.props.onSelectionChange) this.props.onSelectionChange(this.props.selectedItem); this.setState({ selectedKey: this.props.selectedItem }); } } componentWillReceiveProps(nextProps) { if (!_.isEqual(this.state.selectedKey, nextProps.selectedItem)) { this.setState({ selectedKey: nextProps.selectedItem }); } } componentWillUpdate(nextProps, nextState) { if (nextProps.onSelectionChange && !_.isEqual(nextState.selectedKey, this.state.selectedKey)) { nextProps.onSelectionChange(nextState.selectedKey); } } _renderValidChildren = () => { const buttonOnPress = this._onButtonPress; const selectedKey = this.state.selectedKey; const that = this; const children = React.Children.toArray(this.props.children); const uniqueChildren = _.uniqWith(children, (childOne, childTwo) => _.isEqual(childOne.props.id, childTwo.props.id)); if (children.length > uniqueChildren.length) { console.warn('RadioGroup contains RadioButtons with duplicate ids'); } return _.map(uniqueChildren, (child) => { if (child.type === RadioButton) { return React.cloneElement(child, { isSelected: _.isEqual(selectedKey, child.props.id), onButtonPress: buttonOnPress, tintColor: that.props.tintColor || child.props.tintColor, disabledColor: that.props.disabledColor || child.props.disabledColor, baseColor: that.props.baseColor || child.props.baseColor, scale: that.props.scale || child.props.scale, disabled: that.props.disabled || child.props.disabled, innerToOuterRatio: child.props.innerToOuterRatio || that.props.innerToOuterRatio, labelHorizontal: that.props.labelHorizontal !== undefined ? that.props.labelHorizontal : child.props.labelHorizontal, labelColor: that.props.labelColor || child.props.labelColor, labelStyle: that.props.labelStyle || child.props.labelStyle }); } console.warn(`RadioGroup childrens must be of type ${RadioButton.displayName}`); return null; }); } _onButtonPress = (id) => { this.setState({ selectedKey: id }); } render() { return ( <View {...this.props} style={[{ flexDirection: this.props.formHorizontal ? 'row' : 'column', flexWrap: 'wrap' }]}> {this._renderValidChildren()} </View> ); } } RadioGroup.defaultProps = { formHorizontal: false }; RadioGroup.propTypes = { onSelectionChange: PropTypes.func.isRequired, selectedItem: PropTypes.any, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.element), PropTypes.element ]).isRequired, formHorizontal: PropTypes.bool }; module.exports = RadioGroup; <file_sep># React-native-formly: Material Template ## Getting Started ### Prerequisites This is a material template for [react-native-formly](https://github.com/Assem-Hafez/react-native-formly). So make sure that it is installed first. ### Installing ``` npm install react-native-formly-templates-md --save ``` ## Components ### input `templateOptions` Configuration: | name | description | type | default |------------| ---------------------------------------|-------------------------------------------------|-------------- |label | Input Label | string | - |placeholder | Input placeholder | string | - |description | Input description | string | - |required | Input should have a value | bool | - |disabled | Input is disabled | bool | - |minlength | Minimum character length to be entered | number | - |maxlength | Maximum character length to be entered | number | - |type | Input text type | string of (`text`, `number`, `url`, `email`, `password`)| 'text' |pattern | The property that contains radio value | string regex |- Example: ```js { key: 'myMaterialInput', type: 'input', templateOptions: { label: "Number Input", placeholder:"Write a number here", required:true, minlength: 3, type:"number" } } ``` ### textarea `templateOptions` Configuration: | name | description | type | default |------------| ---------------------------------------|-------------------------------------------------|-------------- |label | Input Label | string | - |placeholder | Input placeholder | string | - |description | Input description | string | - |required | Input should have a value | bool | - |disabled | Input is disabled | bool | - |minlength | Minimum character length to be entered | number | - |maxlength | Maximum character length to be entered | number | - |type | Input text type | string of (`text`, `number`, `url`, `email`) | 'text' |pattern | The property that contains radio value | string regex |- Example: ```js { key: 'myMaterialTextarea', type: 'textarea', templateOptions: { label: "Textarea", placeholder:"Say something here", required:true, maxlength: 200 } } ``` ### select | name | description | type | default | |---------------|---------------------------------------------------------------|---------------|---------------| |label | Radio group Label| string | - | | |description | Radio group description| string | - | | |required | Radio group should have a value | bool | - | |disabled | Radio group is disabled| bool | - | | |minlength | Minimum character length to be entered | number | - | |maxlength | Maximum character length to be entered | number | - | |options | Array of select options to be rendered | array | [] | |labelProp | The property that contains radio label if option is object | string | 'name' | |valueProp | The property that contains radio value if option is object | string | 'value' | |pattern | The property that contains radio value | string regex | - Example: ```js { key: 'myMaterialSelect', type: 'select', templateOptions: { label: 'Select', required: true, description : 'Select your type', options:[ 'string', 2, {name:'label', value:'value'} ] } } ``` ### radio | name | description | type | default | |---------------|---------------------------------------------------------------|---------------|---------------| |label | Radio group Label| string | - | | |description | Radio group description| string | - | | |required | Radio group should have a value | bool | - | |disabled | Radio group is disabled| bool | - | | |minlength | Minimum character length to be entered | number | - | |maxlength | Maximum character length to be entered | number | - | |options | Array of radio buttons to be rendered | array | [] | |labelProp | The property that contains radio label if option is object | string | 'name' | |valueProp | The property that contains radio value if option is object | string | 'value' | |pattern | The property that contains radio value | string regex | - Example: ```js { key: 'myMaterialRadio', type: 'radio', templateOptions: { label: 'Radio Input', required:true, description : 'Select your type', options:[ "string", 2, {name:'array', value:[1,2,3]}, {name:'date', value: new Date()}, {name:'object', value:{prop1:'value1'}} ] } } ``` ## Configuring Validation Available validations are: * required * url * email * number * pattern * minlength * maxlength ### Customize validation message You can customize any of the previous validations messages by adding a message to formly's `MessagesConfig`. ```js import { Formly, FormlyConfig } from 'react-native-formly'; let {MessagesConfig } = FormlyConfig; MessagesConfig.addType([ { name: 'required', message: "'This field is Required!!!'" }, { name: 'number', message: "viewValue+' is not a number'" } ]); ``` ### Overriding validations If you ever wanted to change a validation you can override it using formly's `ValidationsConfig`. ```js import { Formly, FormlyConfig } from 'react-native-formly'; let {ValidationsConfig} = FormlyConfig; ValidationsConfig.addType({ minlength: { expression: function ({ viewValue, modelValue, param }) { return viewValue && viewValue.length >= param; }, message:"'Minimum length is '+ param" } }); ``` Make sure that you add this validations after requiring the template ## Roadmap * [x] input * [x] radio * [x] textarea * [ ] checkbox * [ ] multicheckbox * [ ] customizable themes * [x] select <file_sep>import React, { Component } from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import { View } from 'react-native'; import RadioButton from './../../controls/radioButton'; import RadioGroup from './../../controls/radioGroup'; import * as helpers from './../../helpers'; class FormlyRadio extends Component { componentWillReceiveProps(nextProps) { const key = nextProps.config.key; const to = nextProps.config.templateOptions || {}; const model = nextProps.model[key]; if (model !== undefined && !helpers.valueExistsInOptions(to.labelProp, to.valueProp, to.options, model)) { // if the value doesn't exists in options update the model with undefined this.props.onChange(undefined); } } _renderItemsFromTemplateOptions = (to = {}) => { const items = []; // check if the options is of type array if (Array.isArray(to.options)) { to.options.forEach((option, i) => { const currentRadioIndex = i; const { label, value } = helpers.extractLabelAndValueFromOption(to.labelProp, to.valueProp, option); items.push( <RadioButton key={currentRadioIndex + _.toString(value)} id={value} label={label} /> ); }, this); } return items; } render() { const key = this.props.config.key; const to = this.props.config.templateOptions || {}; const viewValue = this.props.viewValues[key]; return ( <View style={defaultComponentStyle.Container}> <View style={defaultComponentStyle.RadioContainer}> <RadioGroup selectedItem={viewValue} formHorizontal={to.inline} labelHorizontal={!to.labelVertical} disabled={to.disabled} onSelectionChange={this.props.onChange} > {this._renderItemsFromTemplateOptions(to)} </RadioGroup> </View> </View> ); } } FormlyRadio.propTypes = { config: PropTypes.shape({ key: PropTypes.string.isRequired, templateOptions: PropTypes.shape({ required: PropTypes.bool, pattern: PropTypes.string, minlength: PropTypes.number, maxlength: PropTypes.number, disabled: PropTypes.bool, description: PropTypes.string, label: PropTypes.string, inline: PropTypes.bool, labelProp: PropTypes.string, valueProp: PropTypes.string, options: PropTypes.arrayOf(PropTypes.any).isRequired }) }).isRequired, model: PropTypes.any, viewValues: PropTypes.any, onChange: PropTypes.func }; const defaultComponentStyle = { RadioContainer: { margin: 1 } }; module.exports = FormlyRadio; <file_sep>import _ from 'lodash'; export function extractLabelAndValueFromOption(labelProp = 'name', valueProp = 'value', option) { let extractedLabelAndValue = { label: '', value: undefined }; // helper function that makes sure that label is string function perpareLabelAndValue(l, v) { const label = _.isString(l) ? l : JSON.stringify(l); const value = v; return { label, value }; } /* the options could be in one of the following formats: -literal value -object with a label and value (the default value of the label and value is "name" and "value" respectively) */ // if the option is a literal value make it the label and the value if (_.isString(option) || _.isNumber(option)) { extractedLabelAndValue = perpareLabelAndValue(option, option); } else if (_.isPlainObject(option)) { // if the option is a object take the value of the labelprop // to the label and the value of valueprop to value extractedLabelAndValue = perpareLabelAndValue(option[labelProp], option[valueProp]); } else { extractedLabelAndValue = perpareLabelAndValue(option, option); } return extractedLabelAndValue; } export function valueExistsInOptions(labelProp, valueProp, options, model) { let valueExistInOptions = false; // check if the value from recieved exists inside the available options if (Array.isArray(options)) { options.forEach((option) => { const { value } = extractLabelAndValueFromOption(labelProp, valueProp, option); if (_.isEqual(value, model)) { valueExistInOptions = true; } }, this); } return valueExistInOptions; }
f145c1d7b9763a10552d9b9854a8ee8856163841
[ "JavaScript", "Markdown" ]
8
JavaScript
Austyns/react-native-formly-templates-md
c01c7ce6f7407b4f42a9e21984d583ef7d4d0df4
f2ee498bf89a709b966b4bd96a12b8a20b7d313a
refs/heads/master
<repo_name>yuliapi/carousel-carousel<file_sep>/README.md # Carousel-carousel slider Easy to use responsive slider. Tested in last versions of Chrome, Safari, Firefox and Opera Check [live demo](http://yuliapi.github.io/projects/carousel/index.html?utm_source=github&utm_campaign=carousel) Also available as [React component](https://github.com/yuliapi/carousel-carousel-react) ## How to use Component can be used either with direct links to CDN resources or by installing as NPM package. ### 1. Use as CDN links Include following into head section of html page: ```` <link href="https://cdn.jsdelivr.net/npm/carousel-carousel@latest/css/carousel-carousel.css" rel="stylesheet"/> ```` ```` <script src="https://cdn.jsdelivr.net/npm/carousel-carousel@latest/js/dist/carousel-carousel.min.js"></script> ```` Create HTML markup ```` <div id="myCarousel" class="carousel"> <div class="carousel-body"> <div class="carousel-slide"> <div class="slide-content"> Slide 1 content goes here </div> </div> <div class="carousel-slide"> <div class="slide-content"> Slide 2 content goes here </div> </div> </div> <div class="carousel-controls"> <button class="slide-control control-next" data-controls="myCarousel" data-target="next"><span></span> </button> <button class="slide-control control-prev" data-controls="myCarousel" data-target="previous"><span></span> </button> </div> </div> ```` Activate carousel on your javascript file or in script section of page html ```` window.onload = function () { let myCarousel = new Carousel(document.getElementById('myCarousel')); myCarousel.activate() }; ```` ### 2. Use as NPM package with your build tool (Grunt, Gulp, Webpack) #### Install component ```` npm install --save carousel-carousel ```` #### Load the required files This component is distributed with: + js/src/carousel-carousel.js - non-minified original source file compatible with browsers of latest version (support ECMAScript 6 is required) + js/dist/carousel-carousel.js - processed with Babel main JS file + js/dist/carousel-carousel.min.js - minified JS + scss/carousel-carousel.scss - SASS file for styling the carousel + css/carousel-carousel.css - compiled styles + demo - webpack bundled demo of carousel usage You can styles and Javascript files that satisfy your project needs. <file_sep>/js/src/carousel-carousel.js class Div { constructor(c) { this.class = c; } render() { let div = document.createElement('div'); div.classList.add(this.class); return div } } class BulletItem { constructor(carousel, number) { this.carousel = carousel; this.number = number; let item = document.createElement('li'); item.classList.add('progress-bullet'); if (this.number === 0) { item.classList.add("active") } let link = document.createElement('a'); link.setAttribute('href', '#'); link.setAttribute('data-slide', this.number); link.addEventListener('click', this.carousel.showSlide.bind(this.carousel, this.number)); item.appendChild(link); this.item = item } render() { return this.item } activate() { this.item.classList.add('active'); } deactivate() { this.item.classList.remove('active') } } class Slide { constructor(slide) { this.slide = slide; } checkAndRemoveClass(name) { if (this.slide.classList.contains(name)) { this.slide.classList.remove(name) } } addNewClass(name) { if (this.slide && this.slide.classList.contains(name) === false) { this.slide.classList.add(name) } } } class Carousel { constructor(e) { this.element = e; this.slides = this.element.getElementsByClassName('carousel-slide'); this.modifiedSlides = []; for (let s of this.slides) { this.modifiedSlides.push(new Slide(s)) } this.controls = this.element.getElementsByClassName('slide-control'); let {nextButton, previousButton} = this.getDirectionControls(); this.nextButton = nextButton; this.previousButton = previousButton; this.addEventListener(this.nextButton, this.nextSlide); this.addEventListener(this.previousButton, this.prevSlide); this.bullets = []; this.currentActiveNumber = 0; } addEventListener(component, action) { component.addEventListener('click', action.bind(this)); } getDirectionControls() { let nextButton, previousButton; for (let button of this.controls) { if (button.dataset.target === 'next') { nextButton = button } if (button.dataset.target === 'previous') { button.setAttribute('disabled', true); previousButton = button } } return {nextButton: nextButton, previousButton: previousButton}; } activate() { this.initStyles(); this.addCarouselProgress(); this.element.style.visibility = 'visible'; } addCarouselProgress() { let wrapper = new Div('progress-wrapper'); let progressWrapper = wrapper.render(); let list = document.createElement('ul'); for (let j = 0; j < this.modifiedSlides.length; j++) { let bullet = new BulletItem(this, j); list.appendChild(bullet.render()) this.bullets.push(bullet) } console.log(this.bullets) let prevControl = this.previousButton.cloneNode(true); let nextControl = this.nextButton.cloneNode(true); this.addEventListener(prevControl, this.prevSlide); this.addEventListener(nextControl, this.nextSlide); progressWrapper.appendChild(prevControl); progressWrapper.appendChild(list); progressWrapper.appendChild(nextControl); let progress = new Div('carousel-progress'); let carouselProgress = progress.render(); carouselProgress.appendChild(progressWrapper); this.element.appendChild(carouselProgress); } initStyles() { for (let i = 0; i < this.modifiedSlides.length; i++) { this.modifiedSlides[i].addNewClass('slide'); if (i === 1) { this.modifiedSlides[i].addNewClass('next') } if (i > 0) { this.modifiedSlides[i].addNewClass('slide-right') } if (i === 0) { this.modifiedSlides[i].addNewClass('active'); } } } nextSlide() { if (this.currentActiveNumber === 0) { this.switchDisabled('previous', false); } if (this.currentActiveNumber !== this.modifiedSlides.length - 1) { this.switchActive(this.currentActiveNumber + 1); this.currentActiveNumber++; if (this.currentActiveNumber === this.modifiedSlides.length - 1) { this.switchDisabled('next', true); } } } prevSlide() { if ((this.currentActiveNumber + 1) === this.modifiedSlides.length) { this.switchDisabled('next', false); } if (this.currentActiveNumber !== 0) { this.switchActive(this.currentActiveNumber - 1); this.currentActiveNumber--; } if (this.currentActiveNumber === 0) { this.switchDisabled('previous', true); } } showSlide(n) { n = parseInt(n); this.switchActive(n); if (n === this.modifiedSlides.length - 1) { this.switchDisabled('next', true) } if (this.currentActiveNumber === this.modifiedSlides.length - 1 && n < this.modifiedSlides.length - 1) { this.switchDisabled('next', false) } if (n === 0) { this.switchDisabled('previous', true) } if (this.currentActiveNumber === 0 && n > 0) { this.switchDisabled('previous', false) } this.currentActiveNumber = n; } switchActive(targetNumber) { this.modifiedSlides[targetNumber].checkAndRemoveClass('slide-right'); this.modifiedSlides[targetNumber].checkAndRemoveClass('slide-left'); this.modifiedSlides[targetNumber].checkAndRemoveClass('next'); this.modifiedSlides[targetNumber].checkAndRemoveClass('previous'); this.modifiedSlides[targetNumber].addNewClass('active'); for (let s = 0; s < targetNumber; s++) { this.modifiedSlides[s].addNewClass('slide-left'); this.modifiedSlides[s].checkAndRemoveClass('slide-right'); this.modifiedSlides[s].checkAndRemoveClass('active'); this.modifiedSlides[s].checkAndRemoveClass('previous'); this.modifiedSlides[s].checkAndRemoveClass('next'); } for (let k = targetNumber + 1; k < this.modifiedSlides.length; k++) { this.modifiedSlides[k].addNewClass('slide-right'); this.modifiedSlides[k].checkAndRemoveClass('slide-left'); this.modifiedSlides[k].checkAndRemoveClass('active'); this.modifiedSlides[k].checkAndRemoveClass('previous'); this.modifiedSlides[k].checkAndRemoveClass('next'); } if (this.modifiedSlides[targetNumber - 1]) { this.modifiedSlides[targetNumber - 1].addNewClass('previous'); } if (this.modifiedSlides[targetNumber + 1]) { this.modifiedSlides[targetNumber + 1].addNewClass('next'); } for (let b of this.bullets) { b.deactivate() } this.bullets[targetNumber].activate(); } switchDisabled(target, value) { for (let c of this.controls) { if (c.dataset.target === target) { c.disabled = value } } } } export default Carousel;<file_sep>/js/dist/carousel-carousel.js function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Div = function () { function Div(c) { _classCallCheck(this, Div); this.class = c; } Div.prototype.render = function render() { var div = document.createElement('div'); div.classList.add(this.class); return div; }; return Div; }(); var BulletItem = function () { function BulletItem(carousel, number) { _classCallCheck(this, BulletItem); this.carousel = carousel; this.number = number; var item = document.createElement('li'); item.classList.add('progress-bullet'); if (this.number === 0) { item.classList.add("active"); } var link = document.createElement('a'); link.setAttribute('href', '#'); link.setAttribute('data-slide', this.number); link.addEventListener('click', this.carousel.showSlide.bind(this.carousel, this.number)); item.appendChild(link); this.item = item; } BulletItem.prototype.render = function render() { return this.item; }; BulletItem.prototype.activate = function activate() { this.item.classList.add('active'); }; BulletItem.prototype.deactivate = function deactivate() { this.item.classList.remove('active'); }; return BulletItem; }(); var Slide = function () { function Slide(slide) { _classCallCheck(this, Slide); this.slide = slide; } Slide.prototype.checkAndRemoveClass = function checkAndRemoveClass(name) { if (this.slide.classList.contains(name)) { this.slide.classList.remove(name); } }; Slide.prototype.addNewClass = function addNewClass(name) { if (this.slide && this.slide.classList.contains(name) === false) { this.slide.classList.add(name); } }; return Slide; }(); var Carousel = function () { function Carousel(e) { _classCallCheck(this, Carousel); this.element = e; this.slides = this.element.getElementsByClassName('carousel-slide'); this.modifiedSlides = []; for (var _iterator = this.slides, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var s = _ref; this.modifiedSlides.push(new Slide(s)); } this.controls = this.element.getElementsByClassName('slide-control'); var _getDirectionControls = this.getDirectionControls(), nextButton = _getDirectionControls.nextButton, previousButton = _getDirectionControls.previousButton; this.nextButton = nextButton; this.previousButton = previousButton; this.addEventListener(this.nextButton, this.nextSlide); this.addEventListener(this.previousButton, this.prevSlide); this.bullets = []; this.currentActiveNumber = 0; } Carousel.prototype.addEventListener = function addEventListener(component, action) { component.addEventListener('click', action.bind(this)); }; Carousel.prototype.getDirectionControls = function getDirectionControls() { var nextButton = void 0, previousButton = void 0; for (var _iterator2 = this.controls, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var button = _ref2; if (button.dataset.target === 'next') { nextButton = button; } if (button.dataset.target === 'previous') { button.setAttribute('disabled', true); previousButton = button; } } return { nextButton: nextButton, previousButton: previousButton }; }; Carousel.prototype.activate = function activate() { this.initStyles(); this.addCarouselProgress(); this.element.style.visibility = 'visible'; }; Carousel.prototype.addCarouselProgress = function addCarouselProgress() { var wrapper = new Div('progress-wrapper'); var progressWrapper = wrapper.render(); var list = document.createElement('ul'); for (var j = 0; j < this.modifiedSlides.length; j++) { var bullet = new BulletItem(this, j); list.appendChild(bullet.render()); this.bullets.push(bullet); } console.log(this.bullets); var prevControl = this.previousButton.cloneNode(true); var nextControl = this.nextButton.cloneNode(true); this.addEventListener(prevControl, this.prevSlide); this.addEventListener(nextControl, this.nextSlide); progressWrapper.appendChild(prevControl); progressWrapper.appendChild(list); progressWrapper.appendChild(nextControl); var progress = new Div('carousel-progress'); var carouselProgress = progress.render(); carouselProgress.appendChild(progressWrapper); this.element.appendChild(carouselProgress); }; Carousel.prototype.initStyles = function initStyles() { for (var i = 0; i < this.modifiedSlides.length; i++) { this.modifiedSlides[i].addNewClass('slide'); if (i === 1) { this.modifiedSlides[i].addNewClass('next'); } if (i > 0) { this.modifiedSlides[i].addNewClass('slide-right'); } if (i === 0) { this.modifiedSlides[i].addNewClass('active'); } } }; Carousel.prototype.nextSlide = function nextSlide() { if (this.currentActiveNumber === 0) { this.switchDisabled('previous', false); } if (this.currentActiveNumber !== this.modifiedSlides.length - 1) { this.switchActive(this.currentActiveNumber + 1); this.currentActiveNumber++; if (this.currentActiveNumber === this.modifiedSlides.length - 1) { this.switchDisabled('next', true); } } }; Carousel.prototype.prevSlide = function prevSlide() { if (this.currentActiveNumber + 1 === this.modifiedSlides.length) { this.switchDisabled('next', false); } if (this.currentActiveNumber !== 0) { this.switchActive(this.currentActiveNumber - 1); this.currentActiveNumber--; } if (this.currentActiveNumber === 0) { this.switchDisabled('previous', true); } }; Carousel.prototype.showSlide = function showSlide(n) { n = parseInt(n); this.switchActive(n); if (n === this.modifiedSlides.length - 1) { this.switchDisabled('next', true); } if (this.currentActiveNumber === this.modifiedSlides.length - 1 && n < this.modifiedSlides.length - 1) { this.switchDisabled('next', false); } if (n === 0) { this.switchDisabled('previous', true); } if (this.currentActiveNumber === 0 && n > 0) { this.switchDisabled('previous', false); } this.currentActiveNumber = n; }; Carousel.prototype.switchActive = function switchActive(targetNumber) { this.modifiedSlides[targetNumber].checkAndRemoveClass('slide-right'); this.modifiedSlides[targetNumber].checkAndRemoveClass('slide-left'); this.modifiedSlides[targetNumber].checkAndRemoveClass('next'); this.modifiedSlides[targetNumber].checkAndRemoveClass('previous'); this.modifiedSlides[targetNumber].addNewClass('active'); for (var s = 0; s < targetNumber; s++) { this.modifiedSlides[s].addNewClass('slide-left'); this.modifiedSlides[s].checkAndRemoveClass('slide-right'); this.modifiedSlides[s].checkAndRemoveClass('active'); this.modifiedSlides[s].checkAndRemoveClass('previous'); this.modifiedSlides[s].checkAndRemoveClass('next'); } for (var k = targetNumber + 1; k < this.modifiedSlides.length; k++) { this.modifiedSlides[k].addNewClass('slide-right'); this.modifiedSlides[k].checkAndRemoveClass('slide-left'); this.modifiedSlides[k].checkAndRemoveClass('active'); this.modifiedSlides[k].checkAndRemoveClass('previous'); this.modifiedSlides[k].checkAndRemoveClass('next'); } if (this.modifiedSlides[targetNumber - 1]) { this.modifiedSlides[targetNumber - 1].addNewClass('previous'); } if (this.modifiedSlides[targetNumber + 1]) { this.modifiedSlides[targetNumber + 1].addNewClass('next'); } for (var _iterator3 = this.bullets, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { var _ref3; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref3 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref3 = _i3.value; } var b = _ref3; b.deactivate(); } this.bullets[targetNumber].activate(); }; Carousel.prototype.switchDisabled = function switchDisabled(target, value) { for (var _iterator4 = this.controls, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { var _ref4; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref4 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref4 = _i4.value; } var c = _ref4; if (c.dataset.target === target) { c.disabled = value; } } }; return Carousel; }();
6acd2541ffbe02eea1ccbdccd4e2db9d27fa1bd5
[ "Markdown", "JavaScript" ]
3
Markdown
yuliapi/carousel-carousel
1588ee9c736524fb88d8f568d8f4ccf2fad01505
f61414790a1977abb28c982f484e3fc55470841d
refs/heads/master
<file_sep>var testString = "test"; exports['Travis test 1'] = function (test) { test.equal(testString, "test" , "Text should match"); test.done(); }; <file_sep># travis-test [![Build Status](https://secure.travis-ci.org/tjakobsson/travis-test.png)](http://travis-ci.org/tjakobsson/travis-test) <- Klicka på länk för byggtester ## integrationer * slack https://slack.com/ * github https://github.com/ * travis ci https://travis-ci.com/ github skickar commits till slack i #github, travis ci skickar ci-tester till #travis <file_sep>console.log("All is OK");
acfcbad5a88b7f2d17dfb78de57a3c39fb603308
[ "JavaScript", "Markdown" ]
3
JavaScript
tjakobsson/travis-test
3926469b17637ad46c906a69fe00ddd32549a805
cac8a3735be4b4a1875f3f916cf3640c3c86e3cd
refs/heads/master
<repo_name>Naixor/pageerror-monitor<file_sep>/pageerror-monitor/process.js var Promise = require('promise'); var cp = require('child_process'); var path = require('path'); var spawn = cp.spawn; function _process(url, settings) { var pageerror = spawn('phantomjs', [path.join(__dirname, 'pageerror.js'), url].concat(settings)); return new Promise(function (resolve, reject) { var stdout = ""; var stderr = ""; pageerror.stdout.on('data', function (data) { // console.log(data.toString()); stdout += data.toString(); }); pageerror.stderr.on('data', function (data) { // console.error(data.toString()); stderr += data.toString(); }); pageerror.on('close', function (code) { if (stdout) { resolve(stdout); } else { if (stderr) { reject(stderr); } else { if (code !== 0) { reject(new Error('Exit with Unexpected error, exit code:'+ code)); } else { resolve('无'); } } } }); }); } module.exports = _process; <file_sep>/pageerror-monitor/README.md # Page error monitor ## Install ```shell $ npm install -g pageerror-monitor ``` ## Useage > run ```shell pageerror -h ``` or ```shell pageerror --useage ``` You can also see `./examples/config.json` and `./examples/url.txt`. And then you can run ```shell pageerror -u {pathto url.txt} -c {pathto config.json} ``` ## Connect me > github: [@Naxior](https://github.com/Naixor) > email: <EMAIL>
949aed4d7dcbd65a3ab6a3546561a99fa4e72849
[ "JavaScript", "Markdown" ]
2
JavaScript
Naixor/pageerror-monitor
e9a23c347f264eb94dc79fa651b8e366008b054c
5ebc32acfae069161044bcd54111473eedcbc21a
refs/heads/master
<file_sep>package com.mindtree.ira.service; import java.util.List; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import com.mindtree.ira.dao.IRADAO; import com.mindtree.ira.model.ServiceRequest; @ManagedBean(name = "iraService") @ApplicationScoped public class IRAService { @ManagedProperty("#{iraDao}") private IRADAO iraDao; public List<ServiceRequest> createKitchenServiceRequest() { return iraDao.createKitchenServiceRequests(); } public List<ServiceRequest> createRetailServiceRequests() { return iraDao.createRetailServiceRequests(); } public void setIraDao(IRADAO iraDao) { this.iraDao = iraDao; } } <file_sep>package com.mindtree.ira.view; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import com.mindtree.ira.model.ServiceRequest; import com.mindtree.ira.service.IRAService; @ManagedBean @ViewScoped public class RefreshOrderView { private String kitchenOrderText = "Hello" ; private List<ServiceRequest> kitchenServiceRequests; private List<ServiceRequest> retailServiceRequests; @ManagedProperty("#{iraService}") private IRAService iraService; @PostConstruct public void init() { kitchenServiceRequests = new ArrayList<ServiceRequest>(); retailServiceRequests = new ArrayList<ServiceRequest>(); updateKitchenOrder(); updateRetailOrder(); } public void updateKitchenOrder(){ kitchenServiceRequests = iraService.createKitchenServiceRequest(); } public void updateRetailOrder(){ retailServiceRequests = iraService.createRetailServiceRequests(); } public String getKitchenOrderText() { return kitchenOrderText; } public void setKitchenOrderText(String kitchenOrderText) { this.kitchenOrderText = kitchenOrderText; } public List<ServiceRequest> getKitchenServiceRequests() { return kitchenServiceRequests; } public List<ServiceRequest> getRetailServiceRequests() { return retailServiceRequests; } public void setIraService(IRAService iraService) { this.iraService = iraService; } }
43cfd278307041146133bcc515263c4b13b6b83e
[ "Java" ]
2
Java
iramindtree/genie-support-system
6d56add94286682dd95c27f6c759ca793d140d88
532676cf039659d2a49230fd8869fcd65a92e652
refs/heads/master
<repo_name>atrauzzi/domain-tool-laravel<file_sep>/src/ModelAdapter.php <?php namespace Atrauzzi\DomainToolLaravel { use Atrauzzi\DomainTool\Model\Adapter\Contract as ModelAdapterContract; /** * Class ModelAdapter * * Allows Domain Tool to interface nicely with Laravel Eloquent models. * * @package Atrauzzi\DomainToolLaravel */ class ModelAdapter implements ModelAdapterContract { /** * Obtains a value from an instance. * * @param object $instance * @param string $attribute * @return mixed */ public function getAttribute($instance, $attribute) { return $instance->$attribute; } /** * Assigns a value to an instance. * * @param object $instance * @param string $attribute * @param mixed $value */ public function setAttribute($instance, $attribute, $value) { $instance->$attribute = $value; } /** * Obtains all attributes that are readable and writable. * * @param object $instance * @return string[] */ public function getFullAttributes($instance) { return array_intersect( $this->getReadableAttributes($instance), $this->getWritableAttributes($instance) ); } /** * Obtains all the attributes of the model that can be set. * * @param object $instance * @return string[] */ public function getWritableAttributes($instance) { return $instance->fillable; } /** * Obtains all the attributes of the model that can be read. * * @param object $instance * @return string[] */ public function getReadableAttributes($instance) { return $instance->visible; } } }<file_sep>/readme.md # Domain Tool Laravel Laravel specific bindings to make use of Domain Tool in your projects and packages.<file_sep>/src/ProfileLoader.php <?php namespace Atrauzzi\DomainToolLaravel { use Atrauzzi\DomainTool\ProfileLoader as ProfileLoaderContract; // use ReflectionClass; class ProfileLoader implements ProfileLoaderContract { /** @var string */ protected $configRoot = 'domain-tool'; /** * @param string $configRoot */ public function setConfigRoot($configRoot) { $this->configRoot = $configRoot; } // // // /** * Returns whether a type has a base config defined anywhere. * * @param string $type * @param null|string $profileName * @return boolean */ public function hasProfileForType($type, $profileName = null) { return $this->config(sprintf('type.%s', $type)) || $profileName && $this->config(sprintf('profiles.%s.type.%s', $profileName, $type)) ; } /** * @param string $type * @param null|string $profileName * @return array */ public function getProfile($type, $profileName = null) { return array_replace_recursive( $this->getGlobalProfile($profileName), $this->getProfileForType($type, $profileName) ); } // // // /** * Returns base config for a type. * * @param string $type * @param null|string $profileName * @return array */ protected function getProfileForType($type, $profileName = null) { $typeReflection = new ReflectionClass($type); if($parent = $typeReflection->getParentClass()) $parentProfile = $this->getProfileForType($parent->getName(), $profileName); else $parentProfile = []; $profile = array_replace_recursive( $parentProfile, $this->config(sprintf('type.%s', $type), []), $this->config(sprintf('profiles.%s.type.%s', $profileName, $type), []) ); return $profile; } /** * Obtains rules that apply to all types, optionally searching a named profile. * * @param null|string $profileName * @return array */ protected function getGlobalProfile($profileName = null) { $profile = array_replace_recursive( [ 'adapter' => 'Atrauzzi\DomainToolLaravel\ModelAdapter', 'snake_out' => true, 'snake_in' => true, 'include_type' => true, ], $this->config('all', []), $this->config(sprintf('profiles.%s.all', $profileName), []) ); return $profile; } /** * A very simple passthrough that applies our config root. * * @param string $key * @param mixed $default * @return mixed */ protected function config($key, $default = null) { return config(sprintf('%s.%s', $this->configRoot, $key), $default); } } }<file_sep>/src/ModelWithGetAdapter.php <?php namespace Atrauzzi\DomainToolLaravel { use Atrauzzi\DomainTool\Util; use Illuminate\Database\Eloquent\Model; use ReflectionMethod; use ReflectionClass; /** * Class ModelAdapter * * Allows Domain Tool to interface nicely with Laravel Eloquent models. * * @package Atrauzzi\DomainToolLaravel */ class ModelWithGetAdapter extends ModelAdapter { /** @var \ReflectionClass[] */ protected static $reflectionCache; /** @var array */ protected static $getterAttributeCache; /** * Obtains a value from an instance. * * @param object $instance * @param string $attribute * @return mixed */ public function getAttribute($instance, $attribute) { $getter = 'get' . ucfirst($attribute); return $instance->$getter(); } /** * Obtains all the attributes of the model that can be set. * * @param object $instance * @return string[] */ public function getWritableAttributes($instance) { if(!$instance instanceof Model) $instance = new $instance; return $instance->getFillable(); } /** * Assigns a value to an instance. * * Remember that the convention in Laravel is to `snake_case` attribtue names. * * @param object $instance * @param string $attribute * @param mixed $value */ public function setAttribute($instance, $attribute, $value) { $attribute = snake_case($attribute); $instance->$attribute = $value; } /** * Obtains all the attributes of the model that can be read. * * @param object $instanceOrClass * @return string[] */ public function getReadableAttributes($instanceOrClass) { $class = Util::getClass($instanceOrClass); if(empty(self::$getterAttributeCache[$class])) { $reflection = $this->getReflection($class); $attributes = []; foreach($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { $methodName = $method->getName(); if(substr($methodName, 0, 3) == 'get') $attributes[] = substr($methodName, 3); } self::$getterAttributeCache[$class] = $attributes; } return self::$getterAttributeCache[$class]; } // // // /** * Obtains and caches ReflectionClass instances for classes. * * @param string|object $class * @return \ReflectionClass */ protected function getReflection($class) { if(empty($reflectionCache[$class])) self::$reflectionCache[$class] = new ReflectionClass($class); return self::$reflectionCache[$class]; } } }<file_sep>/src/ServiceProvider.php <?php namespace Atrauzzi\DomainToolLaravel { use Illuminate\Support\ServiceProvider as Base; // use Atrauzzi\DomainTool\Config; class ServiceProvider extends Base { public function register() { $this->app->singleton('Atrauzzi\DomainTool\Config', function () { return new Config( [$this->app, 'make'], app('Atrauzzi\DomainToolLaravel\ProfileLoader') ); }); } public function boot() { $this->publishes([ __DIR__ . '/../config/domain-tool.php' => config_path('domain-tool.php') ], 'config'); } } }<file_sep>/config/domain-tool.php <?php return [ // Global profile settings, applies to all types, always (even when no profile is requested). 'all' => [ /* * Global default model adapter. * * Can be: * - Atrauzzi\DomainTool\Model\Adapter\AutoGetSet * - Atrauzzi\DomainTool\Model\Adapter\GetSet * - Atrauzzi\DomainTool\Laravel\ModelAdapter * - Any other, supplied by another integration library. * */ 'adapter' => 'Atrauzzi\DomainToolLaravel\ModelAdapter', /* * Outbound values should be in snake_case. */ 'snake_out' => true, /** * Inbound values will be in snake_case. */ 'snake_in' => true, /** * Include a type attribute when dumping. */ 'include_type' => true, ], // Default profiles, per type. 'type' => [ /* * Type-specific Profiles * * If several of your profiles contain similar instructions for a specific class, you * can avoid that duplication here. Keep in mind, when no profile is requested, default * does not get applied. * 'Path\To\Class' => [ ], */ ], /* * Sample profile structure * 'profiles' => [ 'sample-profile' => [ 'all' => [ ], 'type' => [ 'Path\To\Class' => [ // When absent/empty, defaults to AutoGetSet adapter with underscore output. 'adapter' => 'Path\To\AdapterImpl', // You can override the PHP fully qualified name that's generated if desired. // 'include_type' => 'flat_external_name', // Similar to L4's "fillable" array on models, but supports mapping. // When absent, all attributes can be set. 'in' => [ 'id', 'firstName', 'tele' => 'phone', ], // Similar to L4's "visible" array on models, but supports mapping. // When absent/empty, all attributes are displayed. 'out' => [ 'id', 'firstName', 'phone' => 'tele', ], ], ], ], ], */ ];
ca90797125a0bf74769a94cd01d749dbb56a0f92
[ "Markdown", "PHP" ]
6
PHP
atrauzzi/domain-tool-laravel
c940485bdcb39fdc287282e23ccbb9b840822a1a
065feb9ed8bfe780fe71175a981d90d012d006b2
refs/heads/master
<file_sep># getnada-mail-bot Um simples bot que gera email do getnada.com, feito por mim<br /> Set Webhook<br /><br /> Set a Webhook, envie /token + toekn para o bot -----> <a href="https://t.me/devtoolsrobot">@devtoolsrobot</a><br /><br /> <img src="https://www.yukynet.com/scr/img.png"> <file_sep><?php /* * Temp-Mail * @MailGramRobot * Feito Por <NAME> * yukynet.com * @yukynet */ // Only for NGINX + FastCGI // fastcgi_finish_request(); define('BOT_TOKEN', '<KEY>'); function teleRequest($method, $parameters) { foreach ($parameters as $key => &$val) { if (is_array($val)) { $val = json_encode($val); } } $ch = curl_init('https://api.telegram.org/bot'.BOT_TOKEN.'/'.$method); curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_close($ch); return $result; } function curl_get_contents($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); curl_close($ch); return $result; } function getMailDomains() { $mail_domains = curl_get_contents('https://getnada.com/api/v1/domains'); $mail_domains = json_decode($mail_domains, true); return $mail_domains; } function generateRandomString($length = 5) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'; $characters_length = mb_strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[mt_rand(0, $characters_length - 1)]; } return $randomString; } $update = file_get_contents('php://input'); if (!empty($update)) { $update = json_decode($update, true); if (isset($update['message'])) { $message = $update['message']; $chat_id = $message['chat']['id']; $first_name = $message['from']['first_name']; if (isset($message['text'])) { $text = mb_strtolower($message['text']); //comando de inicio if ($text == '/start') { teleRequest('sendMessage', ['chat_id' => $chat_id, 'text' => 'Olá 👋😉 '.$first_name."! Sou o MailGram", 'reply_markup' => ['keyboard' => [[['text' => 'NOVO EMAIL']]], 'resize_keyboard' => true]]); //cria um novo email } elseif ($text == 'novo email') { $mail_domains = getMailDomains(); $mail_address = generateRandomString(mt_rand(5, 6)).'@'.$mail_domains[array_rand($mail_domains)]; teleRequest('sendMessage', ['chat_id' => $chat_id, 'text' => 'E-Mail: '.$mail_address, 'reply_markup' => ['inline_keyboard' => [[['text' => 'Inbox', 'callback_data' => $mail_address]]]]]); } elseif (filter_var($text, FILTER_VALIDATE_EMAIL)) { if (preg_match('/^([a-zA-Z0-9\._]+[A-Za-z0-9_])@(.*?)$/u', $text, $mail)) { $mail_domains = getMailDomains(); if (in_array($mail[2], $mail_domains)) { $mail_address = $mail[1].'@'.$mail[2]; teleRequest('sendMessage', ['chat_id' => $chat_id, 'text' => 'E-Mail: '.$mail_address, 'reply_markup' => ['inline_keyboard' => [[['text' => 'Inbox', 'callback_data' => $mail_address]]]]]); } } } else { teleRequest('sendMessage', ['chat_id' => $chat_id, 'text' => 'Olá 👋😉 '.$first_name."! sou o MailGram.", 'reply_markup' => ['keyboard' => [[['text' => 'NOVO EMAIL']]], 'resize_keyboard' => true]]); } } } elseif (isset($update['callback_query'])) { $callback_query = $update['callback_query']; $callback_query_id = $callback_query['id']; $callback_data = $callback_query['data']; $chat_id = $callback_query['from']['id']; $inbox = curl_get_contents('https://getnada.com/api/v1/inboxes/'.$callback_data); $inbox = json_decode($inbox, true); $inbox = $inbox['msgs']; //inbox das mensagens if (!empty($inbox)) { teleRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id]); teleRequest('sendMessage', ['chat_id' => $chat_id, 'text' => 'Inbox of '.$callback_data.':']); foreach ($inbox as $message) { $message_content = curl_get_contents('https://getnada.com/api/v1/messages/'.$message['uid']); $message_content = json_decode($message_content, true); $message_text = 'From: '.$message['f']."\nAt: ".$message['rf']."\nContent:\n".$message_content['text']; teleRequest('sendMessage', ['chat_id' => $chat_id, 'text' => $message_text]); } } else { teleRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => '🚫 Não há Emails no: '.$callback_data]); } } } //fim, deixe os créditos
e308026704938ee5c1d7ff2cfe84124fca234698
[ "Markdown", "PHP" ]
2
Markdown
paulostationbr/getnada-mail-bot
b068771ab3783c070a1658cecd44a941b18c00a1
e49ce295c9e68e17278403dee3e9869ac054c440
refs/heads/master
<file_sep>[login] usr= pwd= [Warehouse] Warehouse_list=[] [SensitiveKey] keyWord_list=[return,class] [email] from_email=[] to_email=[]<file_sep># coding:utf-8 from selenium import webdriver import time import os import datetime import smtplib from email.mime.text import MIMEText import ConfigParser import zipfile from email.mime.application import MIMEApplication import email.mime.multipart import email.mime.text class conf_git(): def ini_list(self,value): w_len = len(value) str_o = w_len - 1 value_str = value.replace(value[0], '') value = value_str.replace(value[str_o], '') value_list = value.split(',') return value_list def _take_dict(self): cf = ConfigParser.ConfigParser() cf.read('github.ini') save_body={ "name":None, "pwd":<PASSWORD>, "Warehouse":None, "SensitiveKey":None, "from_email":None, "to_email":None } try: login_usr=cf.get("login","usr") login_pwd = cf.get("login", "pwd") from_email = cf.get("email", "from_email") from_email_list=self.ini_list(from_email) to_email = cf.get("email", "to_email") to_email_list = self.ini_list(to_email) # 读需要搜索的仓库转换list Warehouse = cf.get("Warehouse", "Warehouse_list") Warehouse_list=self.ini_list(Warehouse) # 需要搜索的敏感关键字 SensitiveKey = cf.get("SensitiveKey", "keyWord_list") SensitiveKey_list = self.ini_list(SensitiveKey) save_body['name']=login_usr save_body['pwd'] = <PASSWORD> save_body['Warehouse'] = Warehouse_list save_body['SensitiveKey'] = SensitiveKey_list save_body['from_email']=from_email_list save_body['to_email'] = to_email_list conf_dic=save_body except Exception as errorLog: print("读写错误,文件配置没有找到或没有匹配项") return False else: return conf_dic finally: pass class _serch_git(conf_git): def __init__(self): conf_dic=self._take_dict() self.Warehouse_list=conf_dic['Warehouse'] self.SensitiveKey_list = conf_dic['SensitiveKey'] self.name=conf_dic['name'] self.pwd = conf_dic['pwd'] self.from_email=conf_dic['from_email'] self.to_email = conf_dic['to_email'] def get_time(self): nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在 nowTime = str(nowTime) nowTime_str = nowTime.replace(' ', '') nowTime = nowTime_str.replace(':', '-') yymm = nowTime[0:10] hhmm = nowTime[10:] file_time=yymm + '-' + hhmm nowTime='reportIMG'+yymm + '-' + hhmm return nowTime,file_time def mkdir_file(self): nowTime = self.get_time()[0] for dir_f in self.Warehouse_list: for dir_key in self.SensitiveKey_list: if '/' in dir_f: dir_f=dir_f.replace('/','$') else: pass pr_files = nowTime + '/' + dir_f + '/' + dir_key os.makedirs(pr_files) return nowTime def _login_git_serch(self): file_master=self.mkdir_file() self.Warehouse_lists=self.Warehouse_list self.SensitiveKey_lists=self.SensitiveKey_list driver = webdriver.Firefox() driver.get('https://github.com/login') driver.maximize_window() driver.find_element_by_id('login_field').send_keys(self.name) driver.find_element_by_id('password').send_keys(<PASSWORD>) driver.find_element_by_name('commit').click() time.sleep(3) _current_file=os.path.split(os.path.realpath(__file__))[0] file = self.get_time()[1] for Warehouse in self.Warehouse_lists: git_url = 'https://github.com/' + Warehouse for SensitiveKey in self.SensitiveKey_lists: git_urls = git_url+ '/search?q=' + SensitiveKey + '&unscoped_q=' + SensitiveKey driver.get(git_urls) # time.sleep(1) if '/' in Warehouse: Warehouse_file=Warehouse.replace('/','$') else: Warehouse_file=Warehouse try: all_page_ele = driver.find_element_by_xpath('//*[@id="code_search_results"]/div[2]/div/em') all_page = all_page_ele.get_attribute('data-total-pages') # print(all_page) except: # print (unicode('只有一页数据:', 'utf-8')) # driver.save_screenshot(_current_file + '\\' +file_master+ '\\'+Warehouse_file + '\\'+SensitiveKey +'\\'+ file + '.png') driver.save_screenshot(_current_file + '\\' + file_master + '\\' + Warehouse_file + '\\' + SensitiveKey + '\\' + Warehouse_file+ SensitiveKey+ '1.png') # print (unicode('截图完成:', 'utf-8')) else: true_ele = str(all_page) # print(true_ele) true_ele_int = int(true_ele) # print(true_ele_int) for pages in range(1,true_ele_int+1): file = self.get_time()[1] driver.get('https://github.com/' + Warehouse + '/search?p=' + str(pages) + '&q=' + SensitiveKey + '&type=&utf8=%E2%9C%93') # driver.save_screenshot(_current_file + '\\' +file_master+ '\\'+Warehouse_file + '\\'+SensitiveKey +'\\'+ file + '.png') driver.save_screenshot( _current_file + '\\' + file_master + '\\' + Warehouse_file + '\\' + SensitiveKey + '\\' + Warehouse_file + SensitiveKey +str(pages)+ '.png') # print(_current_file + '\\' +file_master+ Warehouse_file + '\\'+SensitiveKey +'\\'+ file + '.png') # print a finally: pass driver.quit() print (unicode('指定仓库根据指定的关键字已截图完成', 'utf-8')) return file_master class sendEmail(_serch_git): def send_forUsr(self): file_name=self._login_git_serch() if "" in self.to_email: print (unicode('脚本执行完成:', 'utf-8')) else: print (unicode('正在打包发送邮件:', 'utf-8')) f = zipfile.ZipFile(file_name + '.zip', 'w', zipfile.ZIP_DEFLATED) startdir = file_name for dirpath, dirnames, filenames in os.walk(startdir): for filename in filenames: f.write(os.path.join(dirpath, filename)) time.sleep(3) # 发送邮件 self.mailserver = 'smtp.mxhichina.com' self.username_send = self.from_email[0] self.password = self.from_email[1] self.user_list = self.to_email # 主题 subject = 'Github敏感关键字自动化搜索测试报告[附件]' # 内容 content = '具体截图请查收附件' for usr in self.user_list: msg = email.mime.multipart.MIMEMultipart() msg['from'] = self.username_send msg['to'] = usr msg['subject'] = subject content = content txt = email.mime.text.MIMEText(content, 'plain', 'utf-8') msg.attach(txt) # 添加附件 part = MIMEApplication(open(file_name+'.zip', 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename=file_name+'.zip') msg.attach(part) time.sleep(3) smtp = smtplib.SMTP() smtp.connect(self.mailserver, '25') smtp.login(self.username_send, self.password) try: smtp.sendmail(self.username_send, usr, str(msg)) except: print (unicode('邮件未发送', 'utf-8')) else: print (unicode('邮件发送成功', 'utf-8')) finally: smtp.quit() if __name__ =="__main__": sendEmail().send_forUsr() else: pass
667f7b1b79aab8c1e721526a3fbf44e964e6ad97
[ "Python", "INI" ]
2
INI
zhucaixiangtest/OtherScripts
2787a3adcf91f59c92b0bafd0695519478f73ad4
408c20e93a974c5f8efb627c83bd8aae6b8201ef
refs/heads/master
<repo_name>philgung/TUI_SimulatorFlightCosts<file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/ControlTower.cs using System.Collections.Generic; using TUI.SimulatorFlights.Domain; namespace TUI.Domain.SimulatorFlights { public class ControlTower : IFlightsManager, IFlightsSimulator { private readonly IPersistenceService _persistenceService; public ControlTower(IPersistenceService persistenceService) { _persistenceService = persistenceService; } public double CalculateDistance(string flightName) { var flight = GetFlight(flightName); var distanceTraveled = flight.CalculateDistance(); _persistenceService.SaveReport(flightName, CalculType.CalculateDistance, distanceTraveled); return distanceTraveled; } public double CalculateFuelConsumption(string flightName) { var flight = GetFlight(flightName); var fuelConsumption = flight.CalculateFuelConsumption(); _persistenceService.SaveReport(flightName, CalculType.CalculateFuelConsumption, fuelConsumption); return fuelConsumption; } public IFlight GetFlight(string flightName) { return _persistenceService.GetFlight(flightName); } public void RegisterFlight(IFlight flight) { _persistenceService.SaveFlight(flight); } public ICollection<Report> GetReports() { return _persistenceService.GetReports(); } public ICollection<IFlight> GetFlights() { return _persistenceService.GetFlights(); } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/Tests/TUI_GeoCoordinateTests/GeoCoordinateTests.cs using FluentAssertions; using GeoCoordinatePortable; using Xunit; namespace TUI_GeoCoordinateTests { public class GeoCoordinateTests { [Fact] public void CalculateDistanceBetweenParisAirportAndLondonAirport() { // Arrange var latitudeAirportRoissy = 49.007; var longitudeAirportRoissy = 2.559790000000021; var roissyAirportGPSPosition = new GeoCoordinate(latitudeAirportRoissy, longitudeAirportRoissy); var latitudeAirportLondon = 51.5048; var longitudeAirportLondon = 0.052745500000014545; var londonAirportGPSPosition = new GeoCoordinate(latitudeAirportLondon, longitudeAirportLondon); var expectedDistance = 330.25267832631079; // Act var distanceKmCalculated = londonAirportGPSPosition.GetDistanceTo(roissyAirportGPSPosition) / 1000; // Assert distanceKmCalculated.Should().Be(expectedDistance); } } } <file_sep>/TUI_SimulatorFlightCosts/Infrastructure/TUI.SimulatorFlights.Infrastructure/FlightAdapter.cs using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Infrastructure.DTO; namespace TUI.SimulatorFlights.Infrastructure { public static class FlightAdapter { public static IFlight ToFlight(this FlightDTO flightDTO) { var flight = new Flight(flightDTO.flight_name); flight.SetFuelConsumptionPerDistance(flightDTO.fuel_consumption_per_distance); flight.SetFuelConsumptionTakeoffEffort(flightDTO.fuel_consumption_takeoff_effort); flight.RegisterDepartureAirport(flightDTO.departure_airport_name, flightDTO.departure_airport_latitude, flightDTO.departure_airport_longitude); flight.RegisterDestinationAirport(flightDTO.destination_airport_name, flightDTO.destination_airport_latitude, flightDTO.destination_airport_longitude); return flight; } } } <file_sep>/TUI_SimulatorFlightCosts/Infrastructure/TUI.SimulatorFlights.Infrastructure/DTO/ReportDTO.cs namespace TUI.SimulatorFlights.Infrastructure.DTO { public class ReportDTO { public string Flight_name { get; set; } public string CalculType { get; set; } public double Result { get; set; } public string CalculDate { get; set; } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/GPSPosition.cs namespace TUI.Domain.SimulatorFlights { public struct GPSPosition { public double Latitude { get; } public double Longitude { get; } public GPSPosition(double latitude, double longitude) { this.Latitude = latitude; this.Longitude = longitude; } } }<file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI_SimulatorFlightCosts.Web/Adapters/ReportModelAdapter.cs using TUI.SimulatorFlights.Domain; using TUI_SimulatorFlightCosts.Web.Models; namespace TUI_SimulatorFlightCosts.Web.Adapters { public static class ReportModelAdapter { public static ReportModel ToReportModel(this Report report) { return new ReportModel { FlightName = report.FlightName, CalculType = report.CalculType == CalculType.CalculateDistance ? "Distance Traveled" : "Consumption Fuel", CalculDate = report.CalculDate.ToShortDateString(), Result = report.CalculType == CalculType.CalculateDistance ? $"{report.Result.ToString("0.00000")} km" : $"{report.Result.ToString("0.00000")} L" }; } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/Flight.cs using TUI.SimulatorFlights.Domain.Extensions; namespace TUI.Domain.SimulatorFlights { public class Flight : IFlight { public Airport DepartureAirport { get; private set; } public Airport DestinationAirport { get; private set; } public string Name { get; private set; } public int FuelConsumptionPerDistance { get; private set; } public int FuelConsumptionTakeoffEffort { get; private set; } public Flight(string flightName) { this.Name = flightName; } public double CalculateDistance() { return DepartureAirport.GetDistanceTo(DestinationAirport); } public double CalculateFuelConsumption() { return (CalculateDistance() * FuelConsumptionPerDistance) + FuelConsumptionTakeoffEffort; } public void RegisterDepartureAirport(string airportName, double latitude, double longitude) { DepartureAirport = new Airport(airportName, new GPSPosition(latitude, longitude)); } public void RegisterDestinationAirport(string airportName, double latitude, double longitude) { DestinationAirport = new Airport(airportName, new GPSPosition(latitude, longitude)); } public void SetFuelConsumptionPerDistance(int fuelConsumptionPerDistance) { FuelConsumptionPerDistance = fuelConsumptionPerDistance; } public void SetFuelConsumptionTakeoffEffort(int fuelConsumptionTakeoffEffort) { FuelConsumptionTakeoffEffort = fuelConsumptionTakeoffEffort; } public void Rename(string flightName) { Name = flightName; } } } <file_sep>/TUI_SimulatorFlightCosts/Infrastructure/TUI.SimulatorFlights.Infrastructure/ReportAdapter.cs using System; using TUI.SimulatorFlights.Domain; using TUI.SimulatorFlights.Infrastructure.DTO; namespace TUI.SimulatorFlights.Infrastructure { public static class ReportAdapter { public static Report ToReport(this ReportDTO reportDTO) { return new Report { FlightName = reportDTO.Flight_name, CalculType = Enum.Parse<CalculType>(reportDTO.CalculType), Result = reportDTO.Result, CalculDate = DateTime.Parse(reportDTO.CalculDate) }; } } } <file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI_SimulatorFlightCosts.Web/Models/ReportModel.cs namespace TUI_SimulatorFlightCosts.Web.Models { public class ReportModel { public string FlightName { get; set; } public string CalculType { get; set; } public string Result { get; set; } public string CalculDate { get; set; } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/Report.cs using System; using System.Collections.Generic; using System.Text; namespace TUI.SimulatorFlights.Domain { public enum CalculType { CalculateDistance, CalculateFuelConsumption } public class Report { public string FlightName { get; set; } public CalculType CalculType { get; set; } public double Result { get; set; } public DateTime CalculDate { get; set; } } } <file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI_SimulatorFlightCosts.Web/Controllers/HomeController.cs using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System.Diagnostics; using System.Linq; using TUI.SimulatorFlights.Domain; using TUI_SimulatorFlightCosts.Application; using TUI_SimulatorFlightCosts.Web.Adapters; using TUI_SimulatorFlightCosts.Web.Models; using UI_SimulatorFlightCosts.Web.Models; namespace TUI_SimulatorFlightCosts.Web.Controllers { public class HomeController : Controller { private FlightSimulatorService _flightSimulatorService; public HomeController(IPersistenceService persistenceService, IConfiguration configuration) { persistenceService.InitializeService(ConfigurationExtensions.GetConnectionString(configuration, "DefaultConnection")); _flightSimulatorService = new FlightSimulatorService(persistenceService); } public IActionResult Index() { var flights = _flightSimulatorService.GetFlights(); return View(new HomeModel() { Flights = flights }); } public IActionResult Edit(string flightName) { if (!string.IsNullOrEmpty(flightName)) { var flight = _flightSimulatorService.GetFlight(flightName); if (flight != null) return View(flight.ToFlightModel()); } return View(); } [HttpPost] public IActionResult Edit(FlightModel flightModel) { _flightSimulatorService.Save(flightModel.ToFlight()); return View(); } public JsonResult CalculDistance(string flightName) { var distance = _flightSimulatorService.CalculateDistance(flightName); return Json(distance); } public JsonResult CalculConsumptionFuel(string flightName) { var consumptionFuel = _flightSimulatorService.CalculateFuelConsumption(flightName); return Json(consumptionFuel); } public IActionResult Report() { var reports = _flightSimulatorService.GetReports()?.Select(x => x.ToReportModel()); return View(reports); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/IFlightsSimulator.cs using System.Collections.Generic; using TUI.Domain.SimulatorFlights; namespace TUI.SimulatorFlights.Domain { public interface IFlightsSimulator { double CalculateDistance(string flightName); double CalculateFuelConsumption(string flightName); ICollection<Report> GetReports(); } } <file_sep>/TUI_SimulatorFlightCosts/TUI_SimulatorFlightCosts_AcceptanceTests/Calculate_Flight_Distance_And_Fuel_Needed_Steps.cs using FluentAssertions; using TechTalk.SpecFlow; using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Infrastructure; namespace TUI_SimulatorFlightCosts_AcceptanceTests { [Binding] public class Calculate_Flight_Distance_And_Fuel_NeededSteps { private Flight _currentFlight; private ControlTower _currentControlTower; private double _distanceKm, _fuelConsumption; public Calculate_Flight_Distance_And_Fuel_NeededSteps() { var persistenceService = new SQLLitePersistenceService(); persistenceService.InitializeService(@"Data Source=..\..\..\..\Sqlite\TUI.SimulatorFlights.sqlite;Version=3;"); _currentControlTower = new ControlTower(persistenceService); _currentFlight = new Flight("currentFlight"); } [Given(@"A flight which has a departure airport with GPS Position \((.*) - (.*), (.*)\)")] public void GivenAFlightWhichHasADepartureAirportWithGPSPositionLondon_(string airportName, double latitude, double longitude) { _currentFlight.RegisterDepartureAirport(airportName, latitude, longitude); } [Given(@"has a destination airport with GPS Position \((.*) - (.*), (.*)\)")] public void GivenHasADestinationAirportWithGPSPosition(string airportName, double latitude, double longitude) { _currentFlight.RegisterDestinationAirport(airportName, latitude, longitude); } [Given(@"the aircraft fuel consumption per distance/flight time \((.*) L/km\) \+ takeoff effort \((.*) L\)")] public void GivenTheAircraftFuelConsumptionPerDistanceFlightTimeLKmHTakeoffEffortLKmH(int fuelConsumptionPerDistancePerFlightTime, int fuelConsumptionTakeoffEffort) { _currentFlight.SetFuelConsumptionPerDistance(fuelConsumptionPerDistancePerFlightTime); _currentFlight.SetFuelConsumptionTakeoffEffort(fuelConsumptionTakeoffEffort); } [Given(@"is registered in control tower like '(.*)'")] public void GivenIsRegisteredInControlTowerLike(string flightName) { _currentFlight.Rename(flightName); _currentControlTower.RegisterFlight(_currentFlight); } [When(@"the simulator calculate travel distance for the flight '(.*)'")] public void WhenTheFlightTakesPlace(string flightName) { _distanceKm = _currentControlTower.CalculateDistance(flightName); } [When(@"the simulator calculate the fuel consumption for the flight '(.*)'")] public void WhenTheFuelConsumptionSimulatorCalculate(string flightName) { _fuelConsumption = _currentControlTower.CalculateFuelConsumption(flightName); } [Then(@"the travel distance was (.*) km")] public void ThenTheTravelDistanceWasKm(double distanceExpected) { _distanceKm.Should().Be(distanceExpected); } [Then(@"the total fuel consumption was (.*) L")] public void ThenTheTotalFuelConsumptionWasL(double fuelConsumptionExpected) { _fuelConsumption.Should().Be(fuelConsumptionExpected); } } } <file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI.SimulatorFlights.InitDBSqlite/Program.cs using System; using TUI.SimulatorFlights.Infrastructure; namespace TUI.SimulatorFlights.InitDBSqlite { class Program { static void Main(string[] args) { var service = new SQLLitePersistenceService(); Console.WriteLine("SQLite : Initialize table"); service.InitializeTables(); Console.WriteLine("SQLite : Tables were created."); } } } <file_sep>/TUI_SimulatorFlightCosts/Application/TUI_SimulatorFlightCosts.Application/FlightSimulatorService.cs using System.Collections.Generic; using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Domain; namespace TUI_SimulatorFlightCosts.Application { public class FlightSimulatorService { private readonly ControlTower _controlTower; public FlightSimulatorService(IPersistenceService persistenceService) { _controlTower = new ControlTower(persistenceService); } public ICollection<IFlight> GetFlights() { return _controlTower.GetFlights(); } public IFlight GetFlight(string flightName) { return _controlTower.GetFlight(flightName); } public void Save(IFlight flight) { _controlTower.RegisterFlight(flight); } public ICollection<Report> GetReports() { return _controlTower.GetReports(); } public double CalculateDistance(string flightName) { return _controlTower.CalculateDistance(flightName); } public double CalculateFuelConsumption(string flightName) { return _controlTower.CalculateFuelConsumption(flightName); } } }<file_sep>/TUI_SimulatorFlightCosts/Infrastructure/TUI.SimulatorFlights.Infrastructure/DTO/FlightDTO.cs using System; using System.Collections.Generic; using System.Text; namespace TUI.SimulatorFlights.Infrastructure.DTO { public class FlightDTO { public string flight_name { get; set; } public int fuel_consumption_per_distance { get; set; } public int fuel_consumption_takeoff_effort { get; set; } public string departure_airport_name { get; set; } public double departure_airport_latitude { get; set; } public double departure_airport_longitude { get; set; } public string destination_airport_name { get; set; } public double destination_airport_latitude { get; set; } public double destination_airport_longitude { get; set; } } } <file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI_SimulatorFlightCosts.Web/Models/FlightModel.cs using System.ComponentModel.DataAnnotations; namespace TUI_SimulatorFlightCosts.Web.Models { public class FlightModel { [Display(Name="Flight Name")] [Required] public string Name { get; set; } [Display(Name = "Fuel consumption per distance")] public int FuelConsumptionPerDistance { get; set; } [Display(Name = "Fuel consumption at takeoff effort")] public int FuelConsumptionTakeoffEffort { get; set; } [Display(Name = "Departure airport name")] public string DepartureAirportName { get; set; } [Display(Name = "Departure airport latitude")] public double DepartureAiportLatitude { get; set; } [Display(Name = "Departure airport longitude")] public double DepartureAirportLongitude { get; set; } [Display(Name = "Destination airport name")] public string DestinationAirportName { get; set; } [Display(Name = "Destination airport latitude")] public double DestinationAirportLatitude { get; set; } [Display(Name = "Destination airport longitude")] public double DestinationAirportLongitude { get; set; } } } <file_sep>/TUI_SimulatorFlightCosts/Application/Tests/TUI_SimulatorFlightCosts.App.Tests/FlightSimulatorServiceTests.cs using FluentAssertions; using Moq; using System; using System.Collections.Generic; using System.Linq; using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Domain; using TUI_SimulatorFlightCosts.Application; using Xunit; namespace TUI_SimulatorFlightCosts.App.Tests { public class FlightSimulatorServiceTests { Mock<IPersistenceService> _persistenceServiceMock; const string _flightName = "FlightTest"; FlightSimulatorService _flightSimulatorService; public FlightSimulatorServiceTests() { _persistenceServiceMock = new Mock<IPersistenceService>(); _flightSimulatorService = new FlightSimulatorService(_persistenceServiceMock.Object); } [Fact] public void GetFlights() { // Arrange _persistenceServiceMock.Setup(x => x.GetFlights()).Returns(new List<IFlight> { new Flight(_flightName) }); // Act var flights = _flightSimulatorService.GetFlights(); // Assert flights.Should().NotBeEmpty(); flights.Should().HaveCount(1); flights.First().Name.Should().Be(_flightName); } [Fact] public void GetFlightByName() { // Arrange _persistenceServiceMock.Setup(x => x.GetFlight(_flightName)).Returns(new Flight(_flightName)); // Act var flight = _flightSimulatorService.GetFlight(_flightName); // Assert flight.Name.Should().Be(_flightName); } [Fact] public void SaveFlight() { // Arrange // Act _flightSimulatorService.Save(new Flight(_flightName)); // Assert _persistenceServiceMock.Verify(x => x.SaveFlight(It.IsAny<IFlight>()), Times.Once); } [Fact] public void GetReports() { // Arrange _persistenceServiceMock.Setup(x => x.GetReports()).Returns(new List<Report> { new Report { FlightName = "test", CalculType = CalculType.CalculateDistance, Result = 633.445, CalculDate = new DateTime(2019, 04, 08) }, new Report { FlightName = "test2", CalculType = CalculType.CalculateFuelConsumption, Result = 699.001, CalculDate = new DateTime(2019, 04, 08) }}); // Act var reports = _flightSimulatorService.GetReports(); // Assert reports.Should().NotBeEmpty(); reports.Should().HaveCount(2); reports.First().CalculType.Should().Be(CalculType.CalculateDistance); reports.Last().CalculType.Should().Be(CalculType.CalculateFuelConsumption); } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/IPersistenceService.cs using System.Collections.Generic; using TUI.Domain.SimulatorFlights; namespace TUI.SimulatorFlights.Domain { public interface IPersistenceService { void InitializeService(string connectionString); void SaveFlight(IFlight flight); IFlight GetFlight(string flightName); ICollection<IFlight> GetFlights(); void SaveReport(string flightName, CalculType calculType, double result); ICollection<Report> GetReports(); } } <file_sep>/TUI_SimulatorFlightCosts/Domain/Tests/TUI_SimulatorFlightsDomainTests/FlightTests.cs using FluentAssertions; using TUI.Domain.SimulatorFlights; using Xunit; namespace TUI_SimulatorFlightCostsTests { public class FlightTests { const string _flightName = "Roissy <NAME> - London"; [Fact] public void CalculateDistance() { // Arrange var flight = new Flight(_flightName); flight.RegisterDepartureAirport("Roissy Charles de Gaulle", 49.007, 2.559790000000021); flight.RegisterDestinationAirport("London", 51.5048, 0.052745500000014545); // Act var distance = flight.CalculateDistance(); // Assert distance.Should().Be(330.25267832631079); } [Fact] public void CalculateFuelConsumption() { // Arrange var flight = new Flight(_flightName); flight.RegisterDepartureAirport("Roissy Charles de Gaulle", 49.007, 2.559790000000021); flight.RegisterDestinationAirport("London", 51.5048, 0.052745500000014545); flight.SetFuelConsumptionPerDistance(1000); flight.SetFuelConsumptionTakeoffEffort(2000); // Act var fuelConsumption = flight.CalculateFuelConsumption(); // Assert fuelConsumption.Should().Be(332252.67832631076); } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/Extensions/GeoCoordinateExtensions.cs using GeoCoordinatePortable; using TUI.Domain.SimulatorFlights; namespace TUI.SimulatorFlights.Domain.Extensions { public static class GeoCoordinateExtensions { public static double GetDistanceTo(this Airport departureAirport, Airport destinationAirport) { var departurePosition = new GeoCoordinate(departureAirport.GetLatitude(), departureAirport.GetLongitude()); var destinationPosition = new GeoCoordinate(destinationAirport.GetLatitude(), destinationAirport.GetLongitude()); return departurePosition.GetDistanceTo(destinationPosition) / 1000; } } } <file_sep>/TUI_SimulatorFlightCosts/Infrastructure/TUI.SimulatorFlights.Infrastructure/SQLLitePersistenceService.cs using Dapper; using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Domain; using TUI.SimulatorFlights.Infrastructure.DTO; namespace TUI.SimulatorFlights.Infrastructure { public class SQLLitePersistenceService : IPersistenceService { private string _connectionString; public IFlight GetFlight(string flightName) { using (var connection = new SQLiteConnection(_connectionString)) using (var command = connection.CreateCommand()) { connection.Open(); var flightDTO = connection.Query<FlightDTO>($"select * from flight where flight_name='{flightName}'").FirstOrDefault(); return flightDTO.ToFlight(); } } public void SaveFlight(IFlight flight) { using (var connection = new SQLiteConnection(_connectionString)) using (var command = connection.CreateCommand()) { connection.Open(); command.CommandText = "INSERT INTO flight (flight_name,fuel_consumption_per_distance,fuel_consumption_takeoff_effort," + "departure_airport_name, departure_airport_latitude, departure_airport_longitude," + "destination_airport_name, destination_airport_latitude, destination_airport_longitude" + $") VALUES ('{flight.Name}', {flight.FuelConsumptionPerDistance}, {flight.FuelConsumptionTakeoffEffort},'{flight.DepartureAirport.AirportName}',{flight.DepartureAirport.GetLatitude()}, {flight.DepartureAirport.GetLongitude()}, '{flight.DestinationAirport.AirportName}', {flight.DestinationAirport.GetLatitude()}, {flight.DestinationAirport.GetLongitude()})" + $"ON CONFLICT(flight_name) DO UPDATE SET fuel_consumption_per_distance = {flight.FuelConsumptionPerDistance},fuel_consumption_takeoff_effort={flight.FuelConsumptionTakeoffEffort}," + $"departure_airport_name='{flight.DepartureAirport.AirportName}',departure_airport_latitude={flight.DepartureAirport.GetLatitude()}, departure_airport_longitude={flight.DepartureAirport.GetLongitude()}," + $"destination_airport_name='{flight.DestinationAirport.AirportName}',destination_airport_latitude={flight.DepartureAirport.GetLatitude()}, destination_airport_longitude={flight.DestinationAirport.GetLongitude()};"; command.ExecuteNonQuery(); } } public void InitializeTables() { SQLiteConnection.CreateFile("TUI.SimulatorFlights.sqlite"); using (var connection = new SQLiteConnection(@"Data Source=TUI.SimulatorFlights.sqlite;Version=3;")) using (var command = connection.CreateCommand()) { connection.Open(); command.CommandText = "CREATE TABLE flight (flight_name VARCHAR(255) PRIMARY KEY, " + "fuel_consumption_per_distance INT," + "fuel_consumption_takeoff_effort INT," + "departure_airport_name VARCHAR(255)," + "departure_airport_latitude double," + "departure_airport_longitude double," + "destination_airport_name VARCHAR(255)," + "destination_airport_latitude double," + "destination_airport_longitude double)" ; command.ExecuteNonQuery(); command.CommandText = "CREATE TABLE report (flight_name VARCHAR(255), calculType VARCHAR(255), calculDate VARCHAR(255), result double)" ; command.ExecuteNonQuery(); } } public ICollection<IFlight> GetFlights() { using (var connection = new SQLiteConnection(_connectionString)) using (var command = connection.CreateCommand()) { connection.Open(); var flightDTOs = connection.Query<FlightDTO>("select * from flight"); return flightDTOs.Select(x => x.ToFlight()).ToList(); } } public void InitializeService(string connectionString) { _connectionString = connectionString; } public void SaveReport(string flightName, CalculType calculType, double result) { using (var connection = new SQLiteConnection(_connectionString)) using (var command = connection.CreateCommand()) { connection.Open(); command.CommandText = "INSERT INTO report (flight_name, calculType, calculDate, result)" + $" VALUES ('{flightName}', '{calculType.ToString()}', '{DateTime.Now.ToShortDateString()}', {result})"; command.ExecuteNonQuery(); } } public ICollection<Report> GetReports() { using (var connection = new SQLiteConnection(_connectionString)) using (var command = connection.CreateCommand()) { connection.Open(); var reportDTOs = connection.Query<ReportDTO>("select * from report"); return reportDTOs.Select(x => x.ToReport()).ToList(); } } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/Tests/TUI_SimulatorFlightsDomainTests/ControlTowerTests.cs using FluentAssertions; using Moq; using System.Collections.Generic; using System.Linq; using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Domain; using Xunit; namespace TUI_SimulatorFlightCostsTests { public class ControlTowerTests { const string flightName = "<NAME> - London"; ControlTower _controlTower; List<IFlight> _flights = new List<IFlight>(); Mock<IPersistenceService> _persistenceServiceMock; public ControlTowerTests() { _persistenceServiceMock = new Mock<IPersistenceService>(); _persistenceServiceMock.Setup(x => x.SaveFlight(It.IsAny<IFlight>())) .Callback((IFlight flight) => _flights.Add(flight)); _persistenceServiceMock.Setup(x => x.GetFlight(It.IsAny<string>())) .Returns((string flightName) => _flights.SingleOrDefault(x => x.Name == flightName)); _controlTower = new ControlTower(_persistenceServiceMock.Object); } [Fact] public void RegisterFlightAndRetriveIt() { // Arrange var firstFlight = new Flight(flightName); // Act _controlTower.RegisterFlight(firstFlight); var flightLoaded = _controlTower.GetFlight(flightName); // Assert flightLoaded.Should().Be(firstFlight); } [Fact] public void CalculateDistanceForAFlight() { // Arrange var flightMock = new Mock<IFlight>(); flightMock.SetupGet(x => x.Name).Returns(flightName); _controlTower.RegisterFlight(flightMock.Object); // Act _controlTower.CalculateDistance(flightName); // Assert flightMock.Verify(x => x.CalculateDistance(), Times.Once); } [Fact] public void CalculateFuelConsumption() { // Arrange var flightMock = new Mock<IFlight>(); flightMock.SetupGet(x => x.Name).Returns(flightName); _controlTower.RegisterFlight(flightMock.Object); // Act _controlTower.CalculateFuelConsumption(flightName); // Assert flightMock.Verify(x => x.CalculateFuelConsumption(), Times.Once); } [Fact] public void GetReports() { // Arrange // Act var reports = _controlTower.GetReports(); // Assert _persistenceServiceMock.Verify(x => x.GetReports(), Times.Once); } [Fact] public void GetFlights() { // Arrange // Act var flights = _controlTower.GetFlights(); // Assert _persistenceServiceMock.Verify(x => x.GetFlights(), Times.Once); } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/Airport.cs namespace TUI.Domain.SimulatorFlights { public class Airport { private GPSPosition _GPSPosition; public string AirportName { get; } public Airport(string airportName, GPSPosition gPSPosition) { this.AirportName = airportName; this._GPSPosition = gPSPosition; } public double GetLatitude() { return _GPSPosition.Latitude; } public double GetLongitude() { return _GPSPosition.Longitude; } } } <file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI_SimulatorFlightCosts.Web/Adapters/FlightModelAdapter.cs using TUI.Domain.SimulatorFlights; using TUI_SimulatorFlightCosts.Web.Models; namespace TUI_SimulatorFlightCosts.Web.Adapters { public static class FlightModelAdapter { public static IFlight ToFlight(this FlightModel flightModel) { var flight = new Flight(flightModel.Name); flight.SetFuelConsumptionPerDistance(flightModel.FuelConsumptionPerDistance); flight.SetFuelConsumptionTakeoffEffort(flightModel.FuelConsumptionTakeoffEffort); flight.RegisterDepartureAirport(flightModel.DepartureAirportName, flightModel.DepartureAiportLatitude, flightModel.DepartureAirportLongitude); flight.RegisterDestinationAirport(flightModel.DestinationAirportName, flightModel.DestinationAirportLatitude, flightModel.DestinationAirportLongitude); return flight; } public static FlightModel ToFlightModel(this IFlight flight) { return new FlightModel { Name = flight.Name, FuelConsumptionPerDistance = flight.FuelConsumptionPerDistance, FuelConsumptionTakeoffEffort = flight.FuelConsumptionTakeoffEffort, DepartureAirportName = flight.DepartureAirport.AirportName, DepartureAiportLatitude = flight.DepartureAirport.GetLatitude(), DepartureAirportLongitude = flight.DepartureAirport.GetLongitude(), DestinationAirportName = flight.DestinationAirport.AirportName, DestinationAirportLatitude = flight.DestinationAirport.GetLatitude(), DestinationAirportLongitude = flight.DestinationAirport.GetLongitude() }; } } } <file_sep>/TUI_SimulatorFlightCosts/TUI_SimulatorFlightCosts_AcceptanceTests/Register_A_New_Flight_Steps.cs using FluentAssertions; using TechTalk.SpecFlow; using TUI.Domain.SimulatorFlights; using TUI.SimulatorFlights.Infrastructure; namespace TUI_SimulatorFlightCosts_AcceptanceTests { [Binding] public class Register_A_New_FlightSteps { private ControlTower _currentControlTower; public Register_A_New_FlightSteps() { var persistenceService = new SQLLitePersistenceService(); persistenceService.InitializeService(@"Data Source=..\..\..\..\Sqlite\TUI.SimulatorFlights.sqlite;Version=3;"); _currentControlTower = new ControlTower(persistenceService); } [When(@"A user enters a new flight called '(.*)' on system")] public void WhenAUserEntersANewFlightCalledOnSystem(string flightName) { var flight = new Flight(flightName); flight.RegisterDepartureAirport("departure_airport", 0.0, 0.0); flight.RegisterDestinationAirport("destination_airport", 0.0, 0.0); _currentControlTower.RegisterFlight(flight); } [Then(@"The flight called '(.*)' can be retrived on system")] public void ThenTheFlightCalledCanBeRetrivedOnSystem(string flightName) { var flightFound = _currentControlTower.GetFlight(flightName); flightFound.Should().NotBeNull(); } } } <file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/IFlight.cs namespace TUI.Domain.SimulatorFlights { public interface IFlight { string Name { get;} int FuelConsumptionPerDistance { get; } int FuelConsumptionTakeoffEffort { get; } Airport DepartureAirport { get; } Airport DestinationAirport { get; } void RegisterDepartureAirport(string airportName, double latitude, double longitude); void RegisterDestinationAirport(string airportName, double latitude, double longitude); void Rename(string flightName); double CalculateDistance(); double CalculateFuelConsumption(); void SetFuelConsumptionPerDistance(int fuelConsumptionPerDistance); void SetFuelConsumptionTakeoffEffort(int fuelConsumptionTakeoffEffort); } }<file_sep>/TUI_SimulatorFlightCosts/Presentation/TUI_SimulatorFlightCosts.Web/Models/HomeModel.cs using System.Collections.Generic; using TUI.Domain.SimulatorFlights; namespace UI_SimulatorFlightCosts.Web.Models { public class HomeModel { public HomeModel() { } public ICollection<IFlight> Flights { get; set; } } }<file_sep>/TUI_SimulatorFlightCosts/Domain/TUI.SimulatorFlights.Domain/IFlightsManager.cs using System.Collections.Generic; using TUI.Domain.SimulatorFlights; namespace TUI.SimulatorFlights.Domain { public interface IFlightsManager { void RegisterFlight(IFlight flight); IFlight GetFlight(string flightName); ICollection<IFlight> GetFlights(); } }
c7616d9054fcdef772017bd05a785d7d326967db
[ "C#" ]
29
C#
philgung/TUI_SimulatorFlightCosts
b7c793d08eafa754d4e2af911ceb0e6701ac8543
455eff64ae9ce1f808e8f7c7e5981e87fa4b749c
refs/heads/master
<repo_name>Laravel-all/PizzaTaskApi<file_sep>/app/Services/Parameter.php <?php namespace App\Services; use App\Parameter as ParameterModel; class Parameter { public function getAll() { $parameters = ParameterModel::all(); return $parameters; } public function get(string $parameter) { return ParameterModel::where('name', $parameter)->get()->first(); } }<file_sep>/app/Http/Controllers/SizeController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Services\Size as SizeService; class SizeController extends Controller { public function __construct(SizeService $sizeService) { $this->_sizeService = $sizeService; } public function index() { return $this->_sizeService->getAll(); } } <file_sep>/app/Http/Controllers/Auth/LoginController.php <?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { /* |------------------------------------------------------------------- | Login Controller |------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ /* public function __construct(Guard $auth) { $this->auth = $auth; $this->middleware('guest', ['except' => 'getLogout']); } */ public function login(Request $request) { //$this->validateLogin($request); $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { $user = Auth::user(); // Get the currently authenticated user... $user->generateToken(); return response()->json([ 'data' => $user->toArray(), ]); } else{ //return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']); return response()->json([ 'error' => 'Unauthorized', ]); } } public function logout(Request $request) { $user = Auth::guard('api')->user(); if ($user) { $user->api_token = null; $user->save(); } return response()->json(['data' => 'User logged out.'], 200); } } /* <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { public function authenticate(Request $request) { $credentials = $request->only('user', 'password'); if (Auth::attempt($credentials)) { // Authentication passed... return redirect()->intended('dashboard'); } } } */<file_sep>/app/Services/Pizza.php <?php namespace App\Services; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Pizza as PizzaModel; class Pizza { public function getAll() { $pizzas = PizzaModel::all(); return $pizzas; } public function create(Request $request) { $pizza = new PizzaModel; $pizza->name = $request->name; $pizza->price = $request->price; $pizza->save(); } public function get($id){ return PizzaModel::where('id', $id)->get(); } public function update($request) { $pizza = PizzaModel::findOrFail($request->id); $pizza->name = $request->name; $pizza->save(); return $pizza; } public function delete($id) { $pizza = PizzaModel::destroy($id); return $pizza; } /** * Get a validator for a order. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { $rules=[ 'name' => 'required|string|max:100', 'price' => 'required|max:11|regex:/^-?[0-9]+(?:\.[0-9]{1,2})?$/' ]; $messages=[ 'name' => 'Name is required!', 'price' => 'Price is required!' ]; return Validator::make($data, $rules, $messages); } }<file_sep>/app/Services/Size.php <?php namespace App\Services; use App\Size as SizeModel; class Size { public function getAll() { $sizes = SizeModel::all(); return $sizes; } }<file_sep>/database/migrations/2020_05_23_202019_create_table_order_detail.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTableOrderDetail extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('table_order_detail', function (Blueprint $table) { $table->integer('order_id'); $table->integer('pizza_id'); $table->integer('size_id'); $table->integer('quantity'); $table->decimal('single_price'); $table->decimal('total_price'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('table_order_detail'); } } <file_sep>/app/Order.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Order extends Model { protected $fillable = [ 'datetime', 'ship_price', 'total' ]; function orderContact() { return $this->hasOne('App\OrderContact'); } function orderDetails() { return $this->hasMany('App\OrderDetail'); } } <file_sep>/database/seeds/PizzaTableSeeder.php <?php use Illuminate\Database\Seeder; use App\Pizza; class PizzaTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Let's truncate our existing records to start from scratch. Pizza::truncate(); //$faker = \Faker\Factory::create(); // And now, let's create a few articles in our database: Pizza::create([ 'name' => 'Pepperoni', 'price' => 17, ]); Pizza::create([ 'name' => 'Chesse', 'price' => 15, ]); Pizza::create([ 'name' => 'Tunna', 'price' => 21, ]); Pizza::create([ 'name' => 'Chicken', 'price' => 20, ]); Pizza::create([ 'name' => 'Four Cheese', 'price' => 23, ]); Pizza::create([ 'name' => 'Fugazzeta', 'price' => 22, ]); Pizza::create([ 'name' => 'Veggie', 'price' => 20, ]); Pizza::create([ 'name' => 'Neapolitan', 'price' => 18, ]); } } <file_sep>/app/Services/Order.php <?php namespace App\Services; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; use App\Order as OrderModel; use App\OrderDetail as OrderDetailModel; use App\OrderContact as OrderContactModel; use App\Services\Pizza as PizzaService; use App\Services\Size as SizeService; use App\Services\Parameter as ParameterService; class Order { function __construct(PizzaService $pizzaService, SizeService $sizeService, ParameterService $parameterService) { $this->pizza = $pizzaService->getAll(); $this->size = $sizeService->getAll(); $this->deliveryCost = (double)$parameterService->get("deliveryCost")->value; } /** * Get a validator for a order. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { $rules=[ 'order.orderContact.fullName' => 'required|string|max:100', 'order.orderContact.phoneNumber' => 'required|string|max:50', 'order.orderContact.fullAddress' => 'required|string|max:100', 'order.orderContact.zipCode' => 'required|string|max:50', 'order.orderDetail.*.idPizza' => 'required|numeric|gt:0', 'order.orderDetail.*.idSize' => 'required|numeric|gt:0', 'order.orderDetail.*.quantity' => 'required|numeric|gt:0' ]; $messages=[ 'order.orderContact.fullName' => 'Name is required!', 'order.orderContact.phoneNumber' => 'Name is required!', 'order.orderContact.fullAddress' => 'Address is required!', 'order.orderContact.zipCode' => 'Address is required!', 'order.orderDetail.*.idPizza' => 'Pizza is required!', 'order.orderDetail.*.idSize' => 'Size is required!', 'order.orderDetail.*.quantity' => 'Quantity is required!', ]; return Validator::make($data, $rules, $messages); } public function getAll() { return OrderModel::with('orderContact','orderDetails') ->orderBy('datetime', 'desc') ->take(50) ->get(); } public function get($id) { return OrderModel::with('orderContact','orderDetails') ->where('id', $id) ->get(); } /** * Create a new contact instance after a valid form. * * @param array $data * @return ContactModel */ public function create(array $request) { try{ DB::beginTransaction(); $order = new OrderModel; $order->datetime = date("Y-m-d-H:i:s"); $order->ship_price = $this->deliveryCost; $order->total = $this->calculateTotalPriceOrder($request); $order->save(); for ($i = 0; $i < count($request["order"]["orderDetail"]); $i++) { $itemElement = new OrderDetailModel; $itemElement->order_id= $order->id; $itemElement->pizza_id=$request["order"]["orderDetail"][$i]["idPizza"]; $itemElement->size_id=$request["order"]["orderDetail"][$i]["idSize"]; $itemElement->quantity=$request["order"]["orderDetail"][$i]["quantity"]; $price=$this->calculatePrice($itemElement->pizza_id, $itemElement->size_id); $totalPrice=$price * $itemElement->quantity; $itemElement->single_price=$price; $itemElement->total_price=$totalPrice; $itemElement->save(); } $orderContact = new OrderContactModel; $orderContact->order_id= $order->id; $orderContact->full_name = $request["order"]["orderContact"]["fullName"]; $orderContact->phone_number = $request["order"]["orderContact"]["phoneNumber"]; $orderContact->full_address = $request["order"]["orderContact"]["fullAddress"]; $orderContact->zip_code = $request["order"]["orderContact"]["zipCode"]; $orderContact->save(); DB::commit(); } catch(\Exception $ex) { DB::rollback(); throw $ex; } } function calculatePrice($pizzaId, $sizeId) { $pizzaPrice=$this->pizza->find($pizzaId)->price; $sizePrice=$this->size->find($sizeId)->price; return $pizzaPrice + $sizePrice; } function calculateTotalPriceOrder($request) { $totalPriceOrder=$this->deliveryCost; for ($i = 0; $i < count($request["order"]["orderDetail"]); $i++) { $pizza_id=$request["order"]["orderDetail"][$i]["idPizza"]; $size_id=$request["order"]["orderDetail"][$i]["idSize"]; $quantity=$request["order"]["orderDetail"][$i]["quantity"]; $price=$this->calculatePrice($pizza_id, $size_id); $subTotalPrice=$price * $quantity; $totalPriceOrder=$totalPriceOrder + $subTotalPrice; } return $totalPriceOrder; } }<file_sep>/database/seeds/SizeTableSeeder.php <?php use Illuminate\Database\Seeder; use App\Size; class SizeTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Size::create([ 'name' => 'Individual', 'price' => 0, ]); Size::create([ 'name' => 'Medium', 'price' => 2, ]); Size::create([ 'name' => 'Big', 'price' => 4, ]); } } <file_sep>/app/Http/Controllers/OrderController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Services\Order as OrderService; class OrderController extends Controller { /** * Create a new controller instance. * * @param Request $request * @return void */ public function __construct(OrderService $orderService) { $this->_orderService = $orderService; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return $this->_orderService->getAll(); } /** * Store a newly created resource in order. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function create(Request $request) { $v = $this->_orderService->validator($request->all()); if ($v->fails()) { return response()->json($v->errors(), 400); } $this->_orderService->create($request->all()); return response()->json("Order Created", 200); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return $this->_orderService->get($id); } } <file_sep>/app/Http/Controllers/PizzaController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Services\Pizza as PizzaService; use Illuminate\Http\Request; class PizzaController extends Controller { public function __construct(PizzaService $pizzaService) { $this->_pizzaService = $pizzaService; } public function index() { return $this->_pizzaService->getAll(); } /**Store a newly created resource in storage. * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $v = $this->_pizzaService->validator($request->all()); if ($v->fails()) { return response()->json($v->errors(), 400); } return $this->_pizzaService->create($request); } /*Display the specified resource. * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return $this->_pizzaService->get($id); } /*Update the specified resource in storage. * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { return $this->_pizzaService->update($request); } /*Remove the specified resource from storage. * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { return $this->_pizzaService->delete($id); } } <file_sep>/app/OrderDetail.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class OrderDetail extends Model { protected $fillable = [ 'order_id', 'pizza_id', 'size_id', 'quantity', 'single_price', 'total_price' ]; public function order() { return $this->belongsTo('App\Order'); } } <file_sep>/app/Http/Controllers/ParameterController.php <?php namespace App\Http\Controllers; use App\Services\Parameter as ParameterService; use App\Http\Controllers\Controller; class ParameterController extends Controller { public function __construct(ParameterService $parameterService) { $this->_parameterService = $parameterService; } public function index() { return $this->_parameterService->getAll(); } }
166889e2a82db90e2337efc11fc34a19e6c0f997
[ "PHP" ]
14
PHP
Laravel-all/PizzaTaskApi
6db8060f427ea34bdf336b256d2431afe08b5966
3815d47a77b9a6d6ed2b41494eec9e6edd20b5fc
refs/heads/master
<repo_name>dkua/django-lollllllllllllllll<file_sep>/abstract/tests.py from django.test import TestCase from django.db import IntegrityError from classic.models import * class IntegrityTest(TestCase): def testA(self): with self.assertRaises(AttributeError): A.objects.create() def testB(self): with self.assertRaises(IntegrityError): B.objects.create() def testC(self): with self.assertRaises(IntegrityError): C.objects.create() def testD(self): with self.assertRaises(IntegrityError): D.objects.create() def testE(self): with self.assertRaises(IntegrityError): E.objects.create() <file_sep>/tox.ini [tox] skipsdist = True envlist = py{27,34}-dj{14,15,16,17,18,19} [testenv] deps = dj14: django>=1.4, <1.5 dj15: django>=1.5, <1.6 dj16: django>=1.6, <1.7 dj17: django>=1.7, <1.8 dj18: django>=1.8, <1.9 dj19: django>=1.9, <1.10 commands = dj{17,18,19}: {envpython} {toxinidir}/manage.py migrate {envpython} {toxinidir}/manage.py test classic abstract <file_sep>/classic/models.py from __future__ import unicode_literals from django.db import models class A(models.Model): char_id = models.CharField(max_length=20, primary_key=True) class B(A): pass class C(B): pass class D(C): pass class E(D): pass <file_sep>/abstract/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='B', fields=[ ('char_id', models.CharField(primary_key=True, max_length=20, serialize=False)), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='C', fields=[ ('b_ptr', models.OneToOneField(primary_key=True, parent_link=True, to='abstract.B', serialize=False, auto_created=True)), ], options={ 'abstract': False, }, bases=('abstract.b',), ), migrations.CreateModel( name='D', fields=[ ('c_ptr', models.OneToOneField(primary_key=True, parent_link=True, to='abstract.C', serialize=False, auto_created=True)), ], options={ 'abstract': False, }, bases=('abstract.c',), ), migrations.CreateModel( name='E', fields=[ ('d_ptr', models.OneToOneField(primary_key=True, parent_link=True, to='abstract.D', serialize=False, auto_created=True)), ], options={ 'abstract': False, }, bases=('abstract.d',), ), ]
77c97566c51dc17906fa8e3125646019a4b47ef8
[ "Python", "INI" ]
4
Python
dkua/django-lollllllllllllllll
91fe35bc0c647f27cec980dc52a255270b90d483
4e85fe1bb6ea04aa6c0252f1d31f93a9245aec36
refs/heads/main
<file_sep>def addition(num1,num2): return num1 + num2 def subtraction(num1,num2): return num1 - num2 def multiplication(num1,num2): return num1 * num2 def division(num1,num2): return num1 / num2 def modulo(num1,num2): userNum = 0 userQ = num1 // num2 userNum = num2 * userQ return num1 - userNum <file_sep>import Calculations as C Quit = False newNum = True num1 = 0 num2 = 0 instructions = "Please press:\n 1: for addition \n 2: for subtraction \n 3: for multiplication \n 4: for division \n 5: for Modulo \n N: for new numbers \n Q: to quit" def calculation(userCalc): global Quit global newNum if userCalc == "1": print("Your number now is", end=" ") print(C.addition(num1,num2)) elif userCalc == "2": print("Your number now is", end=" ") print(C.subtraction(num1,num2)) elif userCalc == "3": print("Your number now is", end=" ") print(C.multiplication(num1, num2)) elif userCalc == "4": print("Your number now is", end=" ") print(C.division(num1, num2)) elif userCalc == "5": print("Modulo num1 is: ", end=" ") print(C.modulo(num1,num2)) elif userCalc == "Q": print("You have ended the program") Quit = True elif userCalc == "N": newNum = True else: print("Not a valid selection, please try again.") return print(instructions) while Quit == False: while newNum == True: try: num1 = int(input("Enter a number: ")) num2 = int(input("Enter another number: ")) newNum = False except: print("An Error has occurred, try again.") userCalc = input("What calculation would you like to preform: ") calculation(userCalc) print("Thank you for using Calculator")
ca68fe21f639a76b2291141891645236e1d018fe
[ "Python" ]
2
Python
scootermcgavin686/basicCalculator
ef05cc3c7226c6af75082f5105e0bffcd0f4a625
0239adc78d27b3197ebe9d9d21a438af2c5e334c
refs/heads/master
<repo_name>WesleyLiu0717/quorum-raft-experiment<file_sep>/bin/deploy.js const path = require("path"); const Web3 = require("web3"); const opt = require(path.join(__dirname, "../opt.json")); const web3 = new Web3(new Web3.providers.HttpProvider(`http://${opt.serv.hosts[0]}:${opt.serv.rpc_port}`)); web3.eth.personal.getAccounts().then(([addr]) => { web3.eth.personal.unlockAccount(addr, opt.signature.pass_phrase, 0, () => { new web3.eth.Contract(opt.smart_contract.abi) .deploy({ data: opt.smart_contract.bytecode }) .send({ from: addr, gas: "0x3d0900" }) .on("receipt", (receipt) => console.log(receipt)); }); }); <file_sep>/bin/index.js const path = require("path"); const Web3 = require("web3"); const key = require(path.join(__dirname, "../privateKeys.json")); const opt = require(path.join(__dirname, "../opt.json")); const app = { contract: { options: { gas: "0x493e0", }, test_creation: { doc_hash: "ee41cb27cd58", doc_SN: opt.smart_contract.document.id_beginning, receiver: opt.smart_contract.employee.id_beginning.toString(), }, test_logging: { doc_hash: "ee41cb27cd58", doc_SN: opt.smart_contract.document.id_beginning.toString(), doc_status: 1, }, }, iteration: { append_logs_per_round: 200, counter: 0, create_docs_per_round: 200, delay: 1000, // 1s killer_round: 600, nonce: 0, work_round: 10 * 60 * 60, // 10h }, }; const cli_opt = require("node-getopt") .create([ [ "a", "append-logs-per-round=ARG", `number of logs would be appended in each round (default: ${app.iteration.append_logs_per_round})`, ], [ "c", "create-docs-per-round=ARG", `number of documents would be created in each round (default: ${app.iteration.create_docs_per_round})`, ], ["h", "help", "show this help"], ["r", "killer-round=ARG", `number of rounds would be conducted (default: ${app.iteration.killer_round})`], ]) .bindHelp() .parseSystem(); cli_opt.options.a && (app.iteration.append_logs_per_round = parseInt(cli_opt.options.a)); cli_opt.options.c && (app.iteration.create_docs_per_round = parseInt(cli_opt.options.c)); cli_opt.options.r && (app.iteration.killer_round = parseInt(cli_opt.options.r)); const web3s = opt.serv.hosts.map( (host) => new Web3(new Web3.providers.WebsocketProvider(`ws://${host}:${opt.serv.ws_port}`)), ); app.contract.instance = new web3s[0].eth.Contract( opt.smart_contract.abi, opt.smart_contract.address, app.contract.options, ); const sendTransaction = (web3, data, nonce, private_key) => { web3.eth.accounts .signTransaction( { nonce: nonce, to: opt.smart_contract.address, gas: app.contract.options.gas, value: "0x0", chainId: "0xa", data: data, }, private_key, ) .then((tx) => web3.eth.sendSignedTransaction(tx.rawTransaction)); }; const interval = setInterval(() => { console.log(`Starting round ${app.iteration.counter + 1} / ${app.iteration.killer_round}...`); if (++app.iteration.counter === app.iteration.killer_round) { clearInterval(interval); } const round = app.iteration.counter % 86400; // 1 day const nonce = `0x${(app.iteration.nonce++).toString(16)}`; for (let i = 0; i < app.iteration.create_docs_per_round; i++) { sendTransaction( web3s[i % web3s.length], app.contract.instance.methods .create( web3s[0].utils.fromAscii(`${++app.contract.test_creation.doc_SN}`), web3s[0].utils.fromAscii(app.contract.test_creation.receiver), web3s[0].utils.fromAscii(`${i}`), web3s[0].utils.fromAscii(app.contract.test_creation.doc_hash), Date.now(), app.contract.test_logging.doc_status, ) .encodeABI(), nonce, key[i].private_key, ); } for (let i = 0, j = app.iteration.create_docs_per_round; i < app.iteration.append_logs_per_round; i++, j++) { sendTransaction( web3s[j % web3s.length], app.contract.instance.methods .log( web3s[0].utils.fromAscii(app.contract.test_logging.doc_SN), web3s[0].utils.fromAscii(app.contract.test_logging.doc_hash), Date.now(), app.contract.test_logging.doc_status, ) .encodeABI(), nonce, key[j].private_key, ); } }, app.iteration.delay);
cb7f2a0b5a667cc8fa6f8cd0523c233e1a0db066
[ "JavaScript" ]
2
JavaScript
WesleyLiu0717/quorum-raft-experiment
1c3112261bc84382be34f7d183dd9617c504abcf
1f605aac05392ab6d799d9aef4a1dc7f52227f07
refs/heads/master
<file_sep>import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import java.lang.AssertionError import kotlin.test.assertEquals internal class ParserTest { private fun test(query: String, expected: String?) { if (expected == null) { assertThrows<ParserException>("Expected <$query> to throw an exception") { Parser(query).parse() } } else { try { val output: String = Parser(query).parse() assertEquals(expected, output) } catch (e: ParserException) { throw AssertionError("Query <$query> threw an exception") } } } @Test fun parseSimpleSelectAll() { test("SELECT * FROM table", "db.table.find()") } @Test fun parseGivenExamples() { test("SELECT * FROM sales LIMIT 10", "db.sales.find().limit(10)") test("SELECT name, surname FROM collection", "db.collection.find({}, {name: 1, surname: 1})") test("SELECT * FROM collection OFFSET 5 LIMIT 10", "db.collection.find().skip(5).limit(10)") test("SELECT * FROM customers WHERE age > 22", "db.customers.find({age: {\$gt: 22}})") } @Test fun parseCaseInsensitive() { test("select * FROM table", "db.table.find()") test("sElEcT * FROM table", "db.table.find()") test("sElEcT * FroM table", "db.table.find()") test("sElEcT * FroM TablE", "db.TablE.find()") } @Test fun parseTableName() { test("SELECT * FROM t1", "db.t1.find()") test("SELECT * FROM 1", null) test("SELECT * FROM 1abc", null) test("SELECT * FROM _", "db._.find()") test("SELECT * FROM _t", "db._t.find()") test("SELECT * FROM _ab_", "db._ab_.find()") test("SELECT * FROM 'table'", "db.table.find()") test("SELECT * FROM '_ab_'", "db._ab_.find()") test("SELECT * FROM '1'", null) test("SELECT * FROM '1abc'", null) test("SELECT * FROM 'table", null) test("SELECT * FROM table'", null) test("SELECT a, b FROM 'table.a'", null) test("SELECT a, b FROM table.a", null) } @Test fun parseColumnNames() { test("SELECT col, abc FROM table", "db.table.find({}, {col: 1, abc: 1})") test("SELECT col , abc FROM table", "db.table.find({}, {col: 1, abc: 1})") test("SELECT col ,abc FROM table", "db.table.find({}, {col: 1, abc: 1})") test("SELECT col , abc FROM table", "db.table.find({}, {col: 1, abc: 1})") test("SELECT col ,, abc FROM table", null) test("SELECT col,,abc FROM table", null) test("SELECT col abc FROM table", null) test("SELECT col,,abc FROM table", null) test("SELECT c1, c2 FROM table", "db.table.find({}, {c1: 1, c2: 1})") test("SELECT c1 FROM table", "db.table.find({}, {c1: 1})") test("SELECT c1, c2, col FROM table", "db.table.find({}, {c1: 1, c2: 1, col: 1})") test("SELECT _, c1 FROM table", "db.table.find({}, {_: 1, c1: 1})") test("SELECT 1, c1 FROM table", null) test("SELECT c1, 2 FROM table", null) test("SELECT 1 , c2 FROM table", null) test("SELECT 1 FROM table", null) test("SELECT 1c FROM table", null) test("SELECT 1c FROM table", null) test("SELECT _c FROM table", "db.table.find({}, {_c: 1})") test("SELECT 'col', 'abc' FROM table", "db.table.find({}, {'col': 1, 'abc': 1})") test("SELECT col, 'abc' FROM table", "db.table.find({}, {col: 1, 'abc': 1})") test("SELECT 'abc ' FROM table", null) test("SELECT 'abc abc' FROM table", null) } @Test fun parseCompositeNames() { test("SELECT 'col.a', abc FROM table", "db.table.find({}, {'col.a': 1, abc: 1})") test("SELECT 'col.a' FROM table", "db.table.find({}, {'col.a': 1})") test("SELECT '_1._2' FROM table", "db.table.find({}, {'_1._2': 1})") test("SELECT '_1.2' FROM table", null) test("SELECT '1.a' FROM table", null) test("SELECT '1t.abc' FROM table", null) test("SELECT abc.abc FROM table", null) test("SELECT abc.abc, a FROM table", null) test("SELECT 'abc. abc' FROM table", null) test("SELECT 'abc . abc' FROM table", null) } @Test fun parseLimit() { test("SELECT * FROM table LIMIT 1", "db.table.find().limit(1)") test("SELECT * FROM table LIMIT 0", "db.table.find().limit(0)") test("SELECT * FROM table LIMIT 12340", "db.table.find().limit(12340)") test("SELECT * FROM table LIMIT a", null) test("SELECT * FROM table LIMIT '1'", null) test("SELECT * FROM table LIMIT _", null) test("SELECT * FROM table LIMIT _", null) test("SELECT * FROM table LIMIT -1", null) } @Test fun parseOffset() { test("SELECT * FROM table OFFSET 1", "db.table.find().skip(1)") test("SELECT * FROM table OFFSET 0", "db.table.find().skip(0)") test("SELECT * FROM table OFFSET 12340", "db.table.find().skip(12340)") test("SELECT * FROM table OFFSET a", null) test("SELECT * FROM table OFFSET '1'", null) test("SELECT * FROM table OFFSET _", null) test("SELECT * FROM table OFFSET _", null) test("SELECT * FROM table OFFSET -1", null) } @Test fun parseSingleIntegerWhereCondition() { test("SELECT * FROM table WHERE a = 1", "db.table.find({a: 1})") test("SELECT * FROM table WHERE a > 1", "db.table.find({a: {\$gt: 1}})") test("SELECT * FROM table WHERE a < 1", "db.table.find({a: {\$lt: 1}})") test("SELECT * FROM table WHERE a <> 1", "db.table.find({a: {\$ne: 1}})") test("SELECT * FROM table WHERE a=1", "db.table.find({a: 1})") test("SELECT * FROM table WHERE a<>1", "db.table.find({a: {\$ne: 1}})") test("SELECT * FROM table WHERE 'col' = 1", "db.table.find({'col': 1})") test("SELECT * FROM table WHERE 'col'=1", "db.table.find({'col': 1})") test("SELECT * FROM table WHERE 'col.a' = 1", "db.table.find({'col.a': 1})") test("SELECT * FROM table WHERE 'col.a'=1", "db.table.find({'col.a': 1})") } @Test fun parseSingleStringWhereCondition() { test("SELECT * FROM table WHERE a = '1'", "db.table.find({a: '1'})") test("SELECT * FROM table WHERE a = 'abc'", "db.table.find({a: 'abc'})") test("SELECT * FROM table WHERE a = '1 c'", "db.table.find({a: '1 c'})") test("SELECT * FROM table WHERE a = '\"'", "db.table.find({a: '\"'})") } @Test fun parseWhereConditionWithConjunction() { test("SELECT * FROM table WHERE a = 1 AND b = 2", "db.table.find({a: 1, b: 2})") test("SELECT * FROM table WHERE a = 1 And b = 2", "db.table.find({a: 1, b: 2})") test("SELECT * FROM table WHERE a = 1 AND b > 2", "db.table.find({a: 1, b: {\$gt: 2}})") test("SELECT * FROM table WHERE a <> 1 AND b > 2", "db.table.find({a: {\$ne: 1}, b: {\$gt: 2}})") test("SELECT * FROM table WHERE a=1 AND b=2 AND c=3", "db.table.find({a: 1, b: 2, c: 3})") } @Test fun parseWhereConditionWithDisjunction() { test("SELECT * FROM table WHERE a = 1 OR b = 2", "db.table.find([{a: 1}, {b: 2}])") test("SELECT * FROM table WHERE a = 1 oR b = 2", "db.table.find([{a: 1}, {b: 2}])") test("SELECT * FROM table WHERE a = 1 OR b > 2", "db.table.find([{a: 1}, {b: {\$gt: 2}}])") test("SELECT * FROM table WHERE a <> 1 OR b > 2", "db.table.find([{a: {\$ne: 1}}, {b: {\$gt: 2}}])") test("SELECT * FROM table WHERE a=1 OR b=2 OR c=3", "db.table.find([{a: 1}, {b: 2}, {c: 3}])") } @Test fun parseDuplicatedKeywords() { test("SELECT * FROM table WHERE a = 1 WHERE b = 2", null) test("SELECT * FROM table OFFSET 1 LIMIT 10 OFFSET 2", null) test("SELECT * FROM table LIMIT 4 WHERE x = 5 OFFSET 1 LIMIT 5", null) } @Test fun parseIncorrectLogicOperators() { test("SELECT * FROM table WHERE a = 1 ORb = 2", null) test("SELECT * FROM table WHERE a = 1 XOR b = 2", null) test("SELECT * FROM table WHERE a = 1AND b = 2", null) test("SELECT * FROM table WHERE a = 1ANDb = 2", null) test("SELECT * FROM table WHERE a = 1 AND b = 2 OR c = 3", null) test("SELECT * FROM table WHERE a = 1 OR b = 2 AND c = 3", null) } @Test fun parseWhitespaceFormatting() { test(" SELECT * FROM table ", "db.table.find()") test(" SELECT \n * FROM \n table ", "db.table.find()") test("SELECT * FROM table\n", "db.table.find()") } @Test fun parseIncorrectKeywords() { test("SELECT1 * FROM table", null) test("SELECT * FFROM table", null) test("SELECT * FROM table LIM 5", null) test("SELECT * FROM table LIMIT 5 OFF 5", null) test("SELECT * FROM table LIMIT 5 OFFSET 5 WHER a = 1", null) } @Test fun parseLongQueries() { test( "SELECT col1, col2 FROM t WHERE 'a.bc'>5 OR 'a' = 'x' OFFSET 10 LIMIT 5\n", "db.t.find([{'a.bc': {\$gt: 5}}, {'a': 'x'}], {col1: 1, col2: 1}).skip(10).limit(5)" ) test( "SELECT * FROM 'table1' LIMIT 5 WHERE 'a.bc' = 5 AND a <> 'abc cba' OFFSET 1\n", "db.table1.find({'a.bc': 5, a: {\$ne: 'abc cba'}}).skip(1).limit(5)" ) test( "SELECT 'a.bc', xyz, foo FROM 'table1' LIMIT 7 WHERE 'a.bc' < 5 OR xyz = 'bar'\n", "db.table1.find([{'a.bc': {\$lt: 5}}, {xyz: 'bar'}], {'a.bc': 1, xyz: 1, foo: 1}).limit(7)" ) } } <file_sep>fun main() { val query: String = readLine()!! val parser = Parser(query) print(parser.parse()) } <file_sep>const val WORD_REGEX = "[A-Za-z_]\\w*" const val SIMPLE_ID_REGEX = "($WORD_REGEX|'$WORD_REGEX')" const val COMPOSITE_ID_REGEX = "($WORD_REGEX|'$WORD_REGEX(\\.$WORD_REGEX)*')" class Parser(query: String) { private val query = query.trim() private var table: String? = null private val columns: MutableList<String> = mutableListOf() private var limit: String? = null private var offset: String? = null private val where: MutableList<String> = mutableListOf() private var whereSeparator: String = "" private var position: Int = 0 fun parse(): String { processToken("select\\s+") // it is possible to select everything or only specific fields if (lookahead("*")) { processToken("*\\s+") } else { do { val columnName: String = processToken(COMPOSITE_ID_REGEX) columns.add(columnName) val separator: String = processToken("\\s*,?\\s*") } while (separator.contains(',')) } // process table name processToken("from\\s+") table = processToken(SIMPLE_ID_REGEX).trim('\'') skipWhitespaces() // parse keywords offset / limit / where while (!isEnd()) { when { lookahead("offset") && offset == null -> { processToken("offset\\s+") offset = processToken("\\d+") skipWhitespaces() } lookahead("limit") && limit == null -> { processToken("limit\\s+") limit = processToken("\\d+") skipWhitespaces() } lookahead("where") && where.isEmpty() -> { processToken("where\\s+") // query can contain several conditions, but only one logical operator can be used while (true) { // scan column / field name which is compared to some value val columnName: String = processToken(COMPOSITE_ID_REGEX) // scan comparison operator val operator: String = processToken("\\s*(<>|[=<>])\\s*").trim() // scan value, to which field is compared val value: String = processToken("(\\d+|'.*')") where.add(encodeCondition(columnName, operator, value)) skipWhitespaces() // look at next logical operator, or break otherwise val logicalOperator: String = if (lookahead("and")) "and" else if (lookahead("or")) "or" else break // remember logical operator at first iteration if (whereSeparator == "") { whereSeparator = logicalOperator } else if (logicalOperator != whereSeparator) { throw ParserException("Incorrect logical operator") } processToken("$whereSeparator\\s+") } } else -> { throw ParserException("Invalid query") } } } val args: String = when { columns.isNotEmpty() -> "${selectCondition()}, ${projectCondition()}" where.isNotEmpty() -> selectCondition() else -> "" } return "db.$table.find($args)${if (offset != null) ".skip($offset)" else ""}${if (limit != null) ".limit($limit)" else ""}" } private fun selectCondition(): String = when (whereSeparator) { "or" -> "[${where.joinToString(", ") { "{$it}" }}]" else -> "{${where.joinToString(", ") { it }}}" } private fun encodeCondition(column: String, operator: String, value: String): String = when (operator) { "=" -> "$column: $value" "<>" -> "$column: {\$ne: $value}" ">" -> "$column: {\$gt: $value}" "<" -> "$column: {\$lt: $value}" else -> throw ParserException("Unknown operator") } private fun projectCondition(): String = when { columns.isEmpty() -> "{}" else -> "{${columns.joinToString(", ") { "$it: 1" }}}" } private fun processToken(pattern: String): String { val regex = Regex("^$pattern", RegexOption.IGNORE_CASE) val match: MatchResult = regex.find(query.substring(position)) ?: throw ParserException("failed to parse") position += match.range.last + 1 return match.value } private fun lookahead(pattern: String): Boolean = query.startsWith(pattern, position, true) private fun isEnd(): Boolean = query.length == position private fun skipWhitespaces() = when { !isEnd() -> processToken("\\s+") else -> null } } <file_sep># JetBrains Internship application problem solution ## SQL for MongoDB I developed a simple SQL-to-MongoDB query converter. Examples of supported queries: * `SELECT * FROM sales LIMIT 10` * `SELECT col1, col2 FROM t WHERE 'a.bc'>5 OR 'a' = 'x' OFFSET 10 LIMIT 5` * `SELECT * FROM 'table1' LIMIT 5 WHERE 'a.bc' = 5 AND a <> 'abc cba' OFFSET 1` * `SELECT 'a.bc', xyz, foo FROM 'table1' LIMIT 7 WHERE 'a.bc' < 5 OR xyz = 'bar'` * more examples in `test/ParserTest.kt` Parser produces the following MongoDB shell queries for upper examples: * `db.sales.find().limit(10)` * `db.t.find([{'a.bc': {$gt: 5}}, {'a': 'x'}], {col1: 1, col2: 1}).skip(10).limit(5)` * `db.table1.find({'a.bc': 5, a: {$ne: 'abc cba'}}).skip(1).limit(5)` * `db.table1.find([{'a.bc': {$lt: 5}}, {xyz: 'bar'}], {'a.bc': 1, xyz: 1, foo: 1}).limit(7)` ## Implementation details This parser uses straightforward approach based on different string operations. Algorithm sequentially scans the whole input, performing some regex matches and simple string operation on the fly. Such solution performed well for given simple task. <file_sep>class ParserException(msg: String = "Parser error") : Exception(msg)
9138439c9e450bd0717d56ef53c1b7a3ac4a5529
[ "Markdown", "Kotlin" ]
5
Kotlin
k1rill-fedoseev/jetbrains-internship-application
9dd964688b4f00a052540e66a075ae8eb16cb214
e848703e2e7431bd01f3aa25848ad2128208656d
refs/heads/master
<file_sep>/* * SSD1306.h * * Created on: 22.03.2020 * Author: danie */ #ifndef APPLICATION_USER_SSD1306_H_ #define APPLICATION_USER_SSD1306_H_ #ifndef __SSD1306_H__ #define __SSD1306_H__ #include <cstddef> #include "_ansi.h" #include "SSD1306_font.h" #include "../../Tasks&Callbacks/AllTasks.h" #include "main.h" #define STM32F7 #if defined(STM32F1) #include "stm32f1xx_hal.h" #elif defined(STM32F4) #include "stm32f4xx_hal.h" #elif defined(STM32L0) #include "stm32l0xx_hal.h" #elif defined(STM32L4) #include "stm32l4xx_hal.h" #elif defined(STM32F3) #include "stm32f3xx_hal.h" #elif defined(STM32H7) #include "stm32h7xx_hal.h" #elif defined(STM32F7) #include "stm32f7xx_hal.h" #else #error "define kind of STM" #endif #define SSD1306_USE_SPI /* vvv I2C config vvv */ #ifndef SSD1306_I2C_PORT #define SSD1306_I2C_PORT hi2c1 #endif #ifndef SSD1306_I2C_ADDR #define SSD1306_I2C_ADDR (0x3C << 1) #endif /* ^^^ I2C config ^^^ */ /* vvv SPI config vvv */ #ifndef SSD1306_SPI_PORT #define SSD1306_SPI_PORT hspi1 #endif #ifndef SSD1306_CS_Port #define SSD1306_CS_Port GPIOB #endif #ifndef SSD1306_CS_Pin #define SSD1306_CS_Pin GPIO_PIN_12 #endif #ifndef SSD1306_DC_Port #define SSD1306_DC_Port GPIOB #endif #ifndef SSD1306_DC_Pin #define SSD1306_DC_Pin GPIO_PIN_14 #endif #ifndef SSD1306_Reset_Port #define SSD1306_Reset_Port GPIOA #endif #ifndef SSD1306_Reset_Pin #define SSD1306_Reset_Pin GPIO_PIN_8 #endif /* ^^^ SPI config ^^^ */ #if defined(SSD1306_USE_I2C) extern I2C_HandleTypeDef SSD1306_I2C_PORT; #elif defined(SSD1306_USE_SPI) extern SPI_HandleTypeDef SSD1306_SPI_PORT; #else #error "You should define SSD1306_USE_SPI or SSD1306_USE_I2C macro!" #endif // SSD1306 OLED height in pixels #ifndef SSD1306_HEIGHT #define SSD1306_HEIGHT 64 #endif // SSD1306 width in pixels #ifndef SSD1306_WIDTH #define SSD1306_WIDTH 128 #endif // Enumeration for screen colors typedef enum { Black = 0x00, // Black color, no pixel White = 0x01 // Pixel is set. Color depends on OLED } SSD1306_COLOR; // Struct to store transformations class SSD1306 { public: SSD1306(); virtual ~SSD1306(); // Procedure definitions void ssd1306_Init(void); void ssd1306_Fill(SSD1306_COLOR color); void ssd1306_UpdateScreen(void); void ssd1306_DrawPixel(uint8_t x, uint8_t y, SSD1306_COLOR color); char ssd1306_WriteChar(char ch, FontDef Font, SSD1306_COLOR color); char ssd1306_WriteString(char* str, FontDef Font, SSD1306_COLOR color); void ssd1306_SetCursor(uint8_t x, uint8_t y); // Low-level procedures void ssd1306_Reset(void); void ssd1306_WriteCommand(uint8_t byte); void ssd1306_WriteData(uint8_t* buffer, size_t buff_size); void ssd1306_Process(); private: uint16_t currentX; uint16_t currentY; uint8_t inverted; uint8_t initialized; }; extern SSD1306 oledSSD; #endif /* APPLICATION_USER_SSD1306_H_ */ #endif // __SSD1306_H__ <file_sep>/* * PID.h * * Created on: 05.03.2020 * Author: Karolina */ #ifndef CLASSES_PID_H_ #define CLASSES_PID_H_ #include "main.h" #include <Tools.h> #include <Mathematics.h> class PID { public: PID(float kp = 0.0f, float ki = 0.0f, float kd = 0.0f); virtual ~PID(); void setKp(float kp); void setKi(float ki); void setKd(float kd); void setSP(float sp); float getCV(float pv); float getCV(float pv, float sp); void enableP(uint8_t enable = true); void enableI(uint8_t enable = true); void enableD(uint8_t enable = true); private: const float _dt = 0.002f; uint8_t proportional_enable, integral_enable, derivative_enable; float integral, proportional, derivative,output; float kp, ki, kd, dt; float set_point; float measured; float last_error; int32_t now_time; int32_t before_time; float calculate(); }; #endif /* CLASSES_PID_H_ */ <file_sep>/* * PID.cpp * * Created on: 05.03.2020 * Author: Karolina */ #include <PID.h> PID::PID(float kp, float ki, float kd) { this->kp = kp; if(kp == 0.0f){ proportional_enable = false; } else { proportional_enable = true; } this->ki = ki; if(ki == 0.0f){ integral_enable = false; } else { integral_enable = true; } this->kd = kd; if(kp == 0.0f){ derivative_enable = false; } else { derivative_enable = true; } this->dt = 0; now_time = tools.GetMicros(); before_time = tools.GetMicros(); integral = 0.0f; proportional = 0.0f; derivative = 0.0f; output = 0.0f; set_point = 0.0f; measured = 0.0f; last_error = 0.0f; } float PID::calculate(){ float error; float output = 0.0f; error = set_point - measured; if(proportional_enable){ proportional = kp * error; output += proportional; } now_time = tools.GetMicros(); dt = constrainf((now_time - before_time) * 1e-6F, (_dt/2), (_dt*2)); before_time = now_time; if(integral_enable){ integral += error * dt; integral = ki * integral; output += integral; } if(derivative_enable){ derivative = (error-last_error)/dt; derivative = kd*derivative; output += derivative; } last_error = error; return output; } void PID::setKp(float kp){ this->kp = kp; } void PID::setKi(float ki){ this->ki = ki; } void PID::setKd(float kd){ this->kd = kd; } void PID::setSP(float sp){ set_point = sp; } float PID::getCV(float pv){ measured = pv; return calculate(); } float PID::getCV(float pv, float sp){ measured = pv; set_point = sp; return calculate(); } void PID::enableP(uint8_t enable) { proportional_enable = enable; } void PID::enableI(uint8_t enable) { integral_enable = enable; } void PID::enableD(uint8_t enable) { derivative_enable = enable; } PID::~PID() { // TODO Auto-generated destructor stub } <file_sep>/* * SSD1306.cpp * * Created on: 22.03.2020 * Author: danie */ #include <OledSSD1306/SSD1306.h> #if defined(SSD1306_USE_I2C) void SSD1306::ssd1306_Reset(void) { /* for I2C - do nothing */ } // Send a byte to the command register void SSD1306::ssd1306_WriteCommand(uint8_t byte) { HAL_I2C_Mem_Write(&SSD1306_I2C_PORT, SSD1306_I2C_ADDR, 0x00, 1, &byte, 1, HAL_MAX_DELAY); } // Send data void SSD1306::ssd1306_WriteData(uint8_t* buffer, size_t buff_size) { HAL_I2C_Mem_Write(&SSD1306_I2C_PORT, SSD1306_I2C_ADDR, 0x40, 1, buffer, buff_size, HAL_MAX_DELAY); } #elif defined(SSD1306_USE_SPI) void SSD1306::ssd1306_Reset(void) { // CS = High (not selected) HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_SET); // Reset the OLED HAL_GPIO_WritePin(SSD1306_Reset_Port, SSD1306_Reset_Pin, GPIO_PIN_RESET); HAL_Delay(10); HAL_GPIO_WritePin(SSD1306_Reset_Port, SSD1306_Reset_Pin, GPIO_PIN_SET); HAL_Delay(10); } // Send a byte to the command register void SSD1306::ssd1306_WriteCommand(uint8_t byte) { HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_RESET); // select OLED HAL_GPIO_WritePin(SSD1306_DC_Port, SSD1306_DC_Pin, GPIO_PIN_RESET); // command HAL_SPI_Transmit(&SSD1306_SPI_PORT, (uint8_t *) &byte, 1, HAL_MAX_DELAY); HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_SET); // un-select OLED } // Send data void SSD1306::ssd1306_WriteData(uint8_t* buffer, size_t buff_size) { HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_RESET); // select OLED HAL_GPIO_WritePin(SSD1306_DC_Port, SSD1306_DC_Pin, GPIO_PIN_SET); // data HAL_SPI_Transmit(&SSD1306_SPI_PORT, buffer, buff_size, HAL_MAX_DELAY); HAL_GPIO_WritePin(SSD1306_CS_Port, SSD1306_CS_Pin, GPIO_PIN_SET); // un-select OLED } #else #error "You should define SSD1306_USE_SPI or SSD1306_USE_I2C macro" #endif // Screenbuffer static uint8_t SSD1306_Buffer[SSD1306_WIDTH * SSD1306_HEIGHT / 8]; SSD1306 oledSSD; void SSD1306::ssd1306_Init(void) { // Reset OLED ssd1306_Reset(); // Wait for the screen to boot HAL_Delay(100); // Init OLED ssd1306_WriteCommand(0xAE); //display off ssd1306_WriteCommand(0x20); //Set Memory Addressing Mode ssd1306_WriteCommand(0x00); // 00b,Horizontal Addressing Mode; 01b,Vertical Addressing Mode; // 10b,Page Addressing Mode (RESET); 11b,Invalid ssd1306_WriteCommand(0xB0); //Set Page Start Address for Page Addressing Mode,0-7 #ifdef SSD1306_MIRROR_VERT ssd1306_WriteCommand(0xC0); // Mirror vertically #else ssd1306_WriteCommand(0xC8); //Set COM Output Scan Direction #endif ssd1306_WriteCommand(0x00); //---set low column address ssd1306_WriteCommand(0x10); //---set high column address ssd1306_WriteCommand(0x40); //--set start line address - CHECK ssd1306_WriteCommand(0x81); //--set contrast control register - CHECK ssd1306_WriteCommand(0xFF); #ifdef SSD1306_MIRROR_HORIZ ssd1306_WriteCommand(0xA0); // Mirror horizontally #else ssd1306_WriteCommand(0xA1); //--set segment re-map 0 to 127 - CHECK #endif #ifdef SSD1306_INVERSE_COLOR ssd1306_WriteCommand(0xA7); //--set inverse color #else ssd1306_WriteCommand(0xA6); //--set normal color #endif ssd1306_WriteCommand(0xA8); //--set multiplex ratio(1 to 64) - CHECK #if (SSD1306_HEIGHT == 32) ssd1306_WriteCommand(0x1F); // #elif (SSD1306_HEIGHT == 64) ssd1306_WriteCommand(0x3F); // #else #error "Only 32 or 64 lines of height are supported!" #endif ssd1306_WriteCommand(0xA4); //0xa4,Output follows RAM content;0xa5,Output ignores RAM content ssd1306_WriteCommand(0xD3); //-set display offset - CHECK ssd1306_WriteCommand(0x00); //-not offset ssd1306_WriteCommand(0xD5); //--set display clock divide ratio/oscillator frequency ssd1306_WriteCommand(0xF0); //--set divide ratio ssd1306_WriteCommand(0xD9); //--set pre-charge period ssd1306_WriteCommand(0x22); // ssd1306_WriteCommand(0xDA); //--set com pins hardware configuration - CHECK #if (SSD1306_HEIGHT == 32) ssd1306_WriteCommand(0x02); #elif (SSD1306_HEIGHT == 64) ssd1306_WriteCommand(0x12); #else #error "Only 32 or 64 lines of height are supported!" #endif ssd1306_WriteCommand(0xDB); //--set vcomh ssd1306_WriteCommand(0x20); //0x20,0.77xVcc ssd1306_WriteCommand(0x8D); //--set DC-DC enable ssd1306_WriteCommand(0x14); // ssd1306_WriteCommand(0xAF); //--turn on SSD1306 panel // Clear screen ssd1306_Fill(Black); // Flush buffer to screen ssd1306_UpdateScreen(); // Set default values for screen object currentX = 0; currentY = 0; initialized = 1; } void SSD1306::ssd1306_Process(){ //text ssd1306_UpdateScreen(); osDelay(5); } // Fill the whole screen with the given color void SSD1306::ssd1306_Fill(SSD1306_COLOR color) { /* Set memory */ uint32_t i; for(i = 0; i < sizeof(SSD1306_Buffer); i++) { SSD1306_Buffer[i] = (color == Black) ? 0x00 : 0xFF; } } // Write the screenbuffer with changed to the screen void SSD1306::ssd1306_UpdateScreen(void) { uint8_t i; for(i = 0; i < 8; i++) { ssd1306_WriteCommand(0xB0 + i); ssd1306_WriteCommand(0x00); ssd1306_WriteCommand(0x10); ssd1306_WriteData(&SSD1306_Buffer[SSD1306_WIDTH*i],SSD1306_WIDTH); } } // Draw one pixel in the screenbuffer // X => X Coordinate // Y => Y Coordinate // color => Pixel color void SSD1306::ssd1306_DrawPixel(uint8_t x, uint8_t y, SSD1306_COLOR color) { if(x >= SSD1306_WIDTH || y >= SSD1306_HEIGHT) { // Don't write outside the buffer return; } // Check if pixel should be inverted if(inverted) { color = (SSD1306_COLOR)!color; } // Draw in the right color if(color == White) { SSD1306_Buffer[x + (y / 8) * SSD1306_WIDTH] |= 1 << (y % 8); } else { SSD1306_Buffer[x + (y / 8) * SSD1306_WIDTH] &= ~(1 << (y % 8)); } } // Draw 1 char to the screen buffer // ch => char om weg te schrijven // Font => Font waarmee we gaan schrijven // color => Black or White char SSD1306::ssd1306_WriteChar(char ch, FontDef Font, SSD1306_COLOR color) { uint32_t i, b, j; // Check if character is valid if (ch < 32 || ch > 126) return 0; // Check remaining space on current line if (SSD1306_WIDTH < (currentX + Font.FontWidth) || SSD1306_HEIGHT < (currentY + Font.FontHeight)) { // Not enough space on current line return 0; } // Use the font to write for(i = 0; i < Font.FontHeight; i++) { b = Font.data[(ch - 32) * Font.FontHeight + i]; for(j = 0; j < Font.FontWidth; j++) { if((b << j) & 0x8000) { ssd1306_DrawPixel(currentX + j, (currentY + i), (SSD1306_COLOR) color); } else { ssd1306_DrawPixel(currentX + j, (currentY + i), (SSD1306_COLOR)!color); } } } // The current space is now taken currentX += Font.FontWidth; // Return written char for validation return ch; } // Write full string to screenbuffer char SSD1306::ssd1306_WriteString(char* str, FontDef Font, SSD1306_COLOR color) { // Write until null-byte while (*str) { if (ssd1306_WriteChar(*str, Font, color) != *str) { // Char could not be written return *str; } // Next char str++; } // Everything ok return *str; } // Position the cursor void SSD1306::ssd1306_SetCursor(uint8_t x, uint8_t y) { currentX = x; currentY = y; } SSD1306::SSD1306() { // TODO Auto-generated constructor stub } SSD1306::~SSD1306() { // TODO Auto-generated destructor stub }
77fd1a8f73c2bf44471d19830c3aaa81a03af557
[ "C++" ]
4
C++
danielbr33/Carolo21
0dca6707079fb9d3ef5c35fbf8bfc8b5241091e4
da33eb34f7425b1445462d6fbfb2901bed56c803
refs/heads/master
<repo_name>capsuletechnology/RPGzinho<file_sep>/RPGzinho/RPGzinho/View/NovoPersonagem.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RPGzinho.View { public partial class NovoPersonagem : ContentPage { int slotPersonagem; public NovoPersonagem(int slot) { NavigationPage.SetHasNavigationBar(this, false); InitializeComponent(); slotPersonagem = slot; backLayout.BackgroundColor = Color.FromHex("#FFAB00"); } protected override bool OnBackButtonPressed() { return Model.Repositorio.SairAplicativo(this); } async void BackClicked(object sender, EventArgs e) { await Model.Repositorio.FadeButton(backButton); Application.Current.MainPage = new Inicio(); } void WarriorClicked(object sender, EventArgs e) { Line1.IsVisible = true; Line2.IsVisible = false; Line3.IsVisible = false; archerGrid.IsVisible = false; mageGrid.IsVisible = false; warriorGrid.IsVisible = true; } void ArcherClicked(object sender, EventArgs e) { Line2.IsVisible = true; Line1.IsVisible = false; Line3.IsVisible = false; mageGrid.IsVisible = false; warriorGrid.IsVisible = false; archerGrid.IsVisible = true; } void MageClicked(object sender, EventArgs e) { Line3.IsVisible = true; Line1.IsVisible = false; Line2.IsVisible = false; archerGrid.IsVisible = false; warriorGrid.IsVisible = false; mageGrid.IsVisible = true; } void warriorInfo(object sender, EventArgs e) { DisplayAlert("Classe Guerreiro", "- Vida: 125\n- Força: 15\n\n- Dano médio.\n- Defesa alta.", "OK"); } void archerInfo(object sender, EventArgs e) { DisplayAlert("Classe Arqueiro", "- Vida: 100\n- Força: 12\n\n- Dano alto.\n- Defesa média.", "OK"); } void mageInfo(object sender, EventArgs e) { DisplayAlert("Classe Mago", "- Vida: 85\n- Força: 8\n\n- Dano muito alto.\n- Defesa baixa.", "OK"); } async void ConfirmarWarrior(object sender, EventArgs e) { if (String.IsNullOrEmpty(Entry1.Text) || String.IsNullOrWhiteSpace(Entry1.Text)) { await DisplayAlert(null, "Digite um nome.", "OK"); return; } else { using (var dados = new DAO.PersonagemDAO()) { dados.Insert(Model.Repositorio.CriarPersonagem(Entry1.Text, "Guerreiro", slotPersonagem)); } await DisplayAlert(Entry1.Text + " - Guerreiro", "Personagem criado com sucesso!", "OK"); } } async void ConfirmarArcher(object sender, EventArgs e) { if (String.IsNullOrEmpty(Entry2.Text) || String.IsNullOrWhiteSpace(Entry2.Text)) { await DisplayAlert(null, "Digite um nome.", "OK"); return; } else { using (var dados = new DAO.PersonagemDAO()) { dados.Insert(Model.Repositorio.CriarPersonagem(Entry2.Text, "Arqueiro", slotPersonagem)); } await DisplayAlert(Entry2.Text + " - Arqueiro", "Personagem criado com sucesso!", "OK"); } } async void ConfirmarMage(object sender, EventArgs e) { if (String.IsNullOrEmpty(Entry3.Text) || String.IsNullOrWhiteSpace(Entry3.Text)) { await DisplayAlert(null, "Digite um nome.", "OK"); return; } else { using (var dados = new DAO.PersonagemDAO()) { dados.Insert(Model.Repositorio.CriarPersonagem(Entry3.Text, "Mago", slotPersonagem)); } await DisplayAlert(Entry3.Text + " - Mago", "Personagem criado com sucesso!", "OK"); } } } } <file_sep>/RPGzinho/RPGzinho/Model/Repositorio.cs using RPGzinho.Helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RPGzinho.Model { public class Repositorio { public async static Task Fade(Image imagem) { await imagem.FadeTo(.5); await imagem.FadeTo(1); } public async static Task FadeButton(Button button) { await button.FadeTo(.5); await button.FadeTo(1); } public static Personagem CriarPersonagem(string nome, string classe, int slot) { Personagem personagem = new Personagem(); if (classe.Equals("Guerreiro")) { personagem.Nome = nome; personagem.Classe = classe; personagem.Vida = 125; personagem.Forca = 15; personagem.Defesa = 0; personagem.Level = 1; personagem.Exp = 0; personagem.Slot = slot; } else if (classe.Equals("Arqueiro")) { personagem.Nome = nome; personagem.Classe = classe; personagem.Vida = 100; personagem.Forca = 12; personagem.Defesa = 0; personagem.Level = 1; personagem.Exp = 0; personagem.Slot = slot; } else if (classe.Equals("Mago")) { personagem.Nome = nome; personagem.Classe = classe; personagem.Vida = 85; personagem.Forca = 8; personagem.Defesa = 0; personagem.Level = 1; personagem.Exp = 0; personagem.Slot = slot; } return personagem; } // Impede de fechar o app sem confirmação caso o botão voltar do celular seja pressionado. // Usar no método 'protected override bool OnBackButtonPressed()' public static bool SairAplicativo(Page page) { Task<bool> question = page.DisplayAlert("SAIR DO APLICATIVO", "Deseja sair do aplicativo?", "Sim", "Não"); question.ContinueWith(task => { if (task.Result) { DependencyService.Get<ICloseApplication>().closeApplication(); } }); return true; } } } <file_sep>/RPGzinho/RPGzinho/DAO/PersonagemDAO.cs using RPGzinho.Model; using SQLiteNetExtensions.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPGzinho.DAO { public class PersonagemDAO : GenericDAO<Personagem> { public PersonagemDAO() { init(); } public List<Personagem> Listar() { return _conexao.Table<Personagem>().ToList(); } } } <file_sep>/RPGzinho/RPGzinho/Model/ArmaPrimaria.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPGzinho.Model { public class ArmaPrimaria : Item { public int Dano { get; set; } public int RestricaoLvl { get; set; } public string RestricaoClasse { get; set; } } } <file_sep>/RPGzinho/RPGzinho/DAO/GenericDAO.cs using RPGzinho.Services; using SQLite.Net.Interop; using SQLiteNetExtensions.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RPGzinho.DAO { public abstract class GenericDAO<T> : IDisposable { public SQLite.Net.SQLiteConnection _conexao { get; set; } public void init() { var config = DependencyService.Get<IConfig>(); _conexao = new SQLite.Net.SQLiteConnection(config.Plataforma, System.IO.Path.Combine(config.Diretorio, "banco1.db3")); _conexao.CreateTable<T>(); } public void Insert(T objeto) { _conexao.Insert(objeto); } public void Update(T objeto) { _conexao.Update(objeto); } public async Task Deletar(T objeto) { _conexao.Delete(objeto, recursive: true); } public void Delete(T objeto) { _conexao.Delete(objeto, recursive: true); } public void Dispose() { _conexao.Dispose(); } } } <file_sep>/RPGzinho/RPGzinho/View/Inventario.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RPGzinho.View { public partial class Inventario : ContentPage { public Inventario() { InitializeComponent(); } } } <file_sep>/RPGzinho/RPGzinho/View/Inicio.xaml.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RPGzinho.View { public partial class Inicio : ContentPage { ObservableCollection<Model.Personagem> ListaPersonagem; Model.Personagem personagem1; Model.Personagem personagem2; bool Character1 = false; bool Character2 = false; public Inicio() { NavigationPage.SetHasNavigationBar(this, false); GridMaster.IsVisible = false; InitializeComponent(); //if (FixFrame1) { Frame1Layout.Padding = new Thickness(0, 0, 0, 0); } //if (FixFrame2) { Frame2Layout.Padding = new Thickness(0, 0, 0, 0); } Frame1.BackgroundColor = Color.FromRgb(250, 250, 210); Frame2.BackgroundColor = Color.FromRgb(250, 250, 210); } protected override async void OnAppearing() { await Task.WhenAll( Logo.RotateYTo(360 * 10, 1000, Easing.CubicIn), Logo.FadeTo(1, 1000, Easing.CubicIn), Titulo.FadeTo(1, 1500, Easing.CubicIn) //SubGrid.FadeTo(1, 1500, Easing.CubicIn) ); Animation2(); } async void Animation2() { for (int i = 0; i < 10; i++) { await Logo.FadeTo(.7, 700); await Logo.FadeTo(1, 700); } } void Carregar() { GridMaster.IsVisible = false; using (var dados = new DAO.PersonagemDAO()) { ListaPersonagem = new ObservableCollection<Model.Personagem>(dados.Listar()); } foreach (var item in ListaPersonagem) { if (item.Slot == 1) { Character1 = true; personagem1 = item; } if (item.Slot == 2) { Character2 = true; personagem2 = item; } } if (Character1) { ImagemRow0.Source = "map.png"; LbNome1.Text = personagem1.Nome; LbClasse1.Text = personagem1.Classe; LbClasse1.IsVisible = true; x1.IsVisible = true; } else { LbClasse1.IsVisible = false; x1.IsVisible = false; ImagemRow0.Source = "letter.png"; LbNome1.Text = "Toque na carta para começar..."; } if (Character2) { ImagemRow1.Source = "map.png"; LbNome2.Text = personagem2.Nome; LbClasse2.Text = personagem2.Classe; LbClasse2.IsVisible = true; x2.IsVisible = true; } else { LbClasse2.IsVisible = false; x2.IsVisible = false; ImagemRow1.Source = "letter.png"; LbNome2.Text = "Toque na carta para começar..."; } GridMaster.IsVisible = true; } async void Image1Tapped(object sender, EventArgs e) { await Model.Repositorio.Fade(ImagemRow0); if (Character1) Application.Current.MainPage = new Principal(); else Application.Current.MainPage = new NovoPersonagem(1); } async void Image2Tapped(object sender, EventArgs e) { await Model.Repositorio.Fade(ImagemRow1); if (Character2) Application.Current.MainPage = new Principal(); else Application.Current.MainPage = new NovoPersonagem(2); } async void Excluir1Tapped(object sender, EventArgs e) { await Model.Repositorio.Fade(x1); Task<bool> question = DisplayAlert("DELETAR PERSONAGEM", "Tem certeza que deseja deletar esse personagem?", "Sim", "Não"); await question.ContinueWith(task => { if (task.Result) { using (var dados = new DAO.PersonagemDAO()) { foreach (var item in dados.Listar()) { if (item.Nome.Equals(LbNome1.Text)) { dados.Delete(item); } } } } }); return; } async void Excluir2Tapped(object sender, EventArgs e) { await Model.Repositorio.Fade(x2); Task<bool> question = DisplayAlert("DELETAR PERSONAGEM", "Tem certeza que deseja deletar esse personagem?", "Sim", "Não"); await question.ContinueWith(task => { if (task.Result) { using (var dados = new DAO.PersonagemDAO()) { foreach (var item in dados.Listar()) { if (item.Nome.Equals(LbNome2.Text)) { dados.Delete(item); } } } } }); return; } //async void TapImagem(object sender, EventArgs e) //{ // //await Model.Repositorio.Fade(Logo); // //await image.TranslateTo(-100, 0, 1000); // Move image left // //await image.TranslateTo(-100, -100, 1000); // Move image up // //await image.TranslateTo(100, 100, 2000); // Move image diagonally down and right // //await image.TranslateTo(0, 100, 1000); // Move image left // //await image.TranslateTo(0, 0, 1000); // Move image up // //await Task.Delay(1000); // //await image.TranslateTo(0, 200, 2000, Easing.BounceIn); // //await image.ScaleTo(2, 2000, Easing.CubicIn); // //await image.RotateTo(360, 2000, Easing.SinInOut); // //await image.ScaleTo(1, 2000, Easing.CubicOut); // //await image.TranslateTo(0, -200, 2000, Easing.BounceOut); // // 10 minute animation // //uint duration = 10 * 60 * 1000; // //await Task.WhenAll( // //image.RotateTo(307 * 360, duration), // //image.RotateXTo(251 * 360, duration), // //image.RotateYTo(199 * 360, duration) // //); // //ViewExtensions.CancelAnimations(image); //} protected override bool OnBackButtonPressed() { return Model.Repositorio.SairAplicativo(this); } } } <file_sep>/RPGzinho/RPGzinho/Model/Personagem.cs using SQLite.Net.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPGzinho.Model { [Table("Personagem")] public class Personagem { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Nome { get; set; } public string Classe { get; set; } public int Vida { get; set; } public int Forca { get; set; } public int Defesa { get; set; } public int Level { get; set; } public int Exp { get; set; } public int Slot { get; set; } } } <file_sep>/RPGzinho/RPGzinho.iOS/CloseApplication.cs using RPGzinho.iOS; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; [assembly: Xamarin.Forms.Dependency(typeof(CloseApplication))] namespace RPGzinho.iOS { public class CloseApplication : Helper.ICloseApplication { public void closeApplication() { Process.GetCurrentProcess().CloseMainWindow(); Process.GetCurrentProcess().Close(); } } } <file_sep>/RPGzinho/RPGzinho/View/Principal.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace RPGzinho.View { public partial class Principal : ContentPage { public Principal() { NavigationPage.SetHasNavigationBar(this, false); InitializeComponent(); } async void BackClicked(object sender, EventArgs e) { await Model.Repositorio.FadeButton(backButton); Application.Current.MainPage = new Inicio(); } } }
307db96f2795c9477367d9bc6f3c407e93e10796
[ "C#" ]
10
C#
capsuletechnology/RPGzinho
cbc822202342d10c623b48b0b61cb7f310fee935
43f605318ca4f047bfaa2e3d1cee9c878b249ed1
refs/heads/master
<repo_name>innodjet/Language-EN-FR...-<file_sep>/README.md # Language-EN-FR...- This project is to implement a Multilanguage page functionnality using PHP <file_sep>/index.php <?php /* include the lang array on the page depending on the language slected by the user. */ if (isset($_GET['lang']) && ($_GET['lang']=="En" || $_GET['lang']=="Fr") ) include($_GET['lang'].".php"); else /* This is to include the default lang on the pagethe first time the user comes on the page. */ include("En.php"); ?> <br/> <br/> <div class="well"> <a href="?lang=En">English</a> | <a href="?lang=Fr">French</a> </div> <br/> <br/> <div class="well"> <?php echo $lang["Hello"]."<br>"; echo $lang["My name is"]." <NAME>"."</br>"; echo $lang["I am a software Engineer"]."</br>"; ?> </div> <file_sep>/Fr.php <?php $lang = array ( "Hello"=>"Bonjour", "My name is"=>"Je me nomme", "I am a software Engineer"=>"Je suis Ingénieur Informatique" ); ?> <file_sep>/En.php <?php $lang = array ( "Hello"=>"Hello", "My name is"=>"My name is", "I am a software Engineer"=>"I am a software Engineer" ); ?>
07b8ca545d6783bfa8df1cd47f6adcf82077ed31
[ "Markdown", "PHP" ]
4
Markdown
innodjet/Language-EN-FR...-
9db3c29f63f7cc8b63e455a08d9ae07706e0fac1
12566ca91631d1c88ff773b68864058df82da5ec
refs/heads/main
<repo_name>NSS-Day-Cohort-42/chinook-skratz17<file_sep>/queries/invoice_totals.sql /* Provide a query that shows the Invoice Total, Customer name, Country and Sale Agent name for all invoices and customers. */ SELECT i.Total, c.FirstName as CustomerFirstName, c.LastName as CustomerLastName, i.BillingCountry, e.FirstName as EmployeeFirstName, e.LastName as EmployeeLastName FROM Invoice i JOIN Customer c ON i.CustomerId = c.CustomerId JOIN Employee e ON c.SupportRepId = e.EmployeeId;<file_sep>/queries/total_sales_2011.sql /* What are the respective total sales for each of those years? */ SELECT ROUND(SUM(Total), 2) as YearSales FROM Invoice WHERE InvoiceDate >= '2011-01-01' AND InvoiceDate <= '2011-12-31';<file_sep>/queries/total_sales_2009.sql /* What are the respective total sales for each of those years? */ SELECT ROUND(SUM(Total), 2) as YearSales FROM Invoice WHERE InvoiceDate >= '2009-01-01' AND InvoiceDate <= '2009-12-31';<file_sep>/queries/sales_agent_customer_count.sql /* Provide a query that shows the count of customers assigned to each sales agent. */ SELECT e.EmployeeId, e.FirstName || ' ' || e.LastName as FullName, COUNT(*) as CustomerCount FROM Employee e JOIN Customer c ON c.SupportRepId = e.EmployeeId GROUP BY e.EmployeeId;<file_sep>/queries/country_invoices.sql /* Provide a query that shows the # of invoices per country. */ SELECT InvoiceId, BillingCountry, COUNT(*) As CountryCount FROM Invoice GROUP BY BillingCountry;<file_sep>/queries/top_5_tracks.sql /* Provide a query that shows the top 5 most purchased tracks over all. */ SELECT t.Name, SUM(il.Quantity) as PurchaseCount FROM Track t JOIN InvoiceLine il ON il.TrackId = t.TrackId GROUP BY t.TrackId ORDER BY PurchaseCount DESC LIMIT 5;<file_sep>/queries/line_item_track.sql /* Provide a query that includes the purchased track name with each invoice line item. */ SELECT il.*, t.Name FROM InvoiceLine il JOIN Track t ON il.TrackId = t.TrackId; <file_sep>/queries/playlists_track_count.sql /* Provide a query that shows the total number of tracks in each playlist. The Playlist name should be include on the resulant table. */ SELECT p.PlaylistId, p.Name, Count(*) FROM Playlist p JOIN PlaylistTrack pt ON pt.PlaylistId = p.PlaylistId GROUP BY p.PlaylistId;<file_sep>/queries/top_agent.sql /* Which sales agent made the most in sales over all? */ SELECT FullName, MAX(TotalSales) FROM ( SELECT e.FirstName || ' ' || e.LastName as FullName, ROUND(SUM(i.Total), 2) as TotalSales FROM Employee e JOIN Customer c ON c.SupportRepId = e.EmployeeId JOIN Invoice i ON i.CustomerId = c.CustomerId GROUP BY e.EmployeeId );<file_sep>/queries/sales_per_country.sql /* Provide a query that shows the total sales per country. */ SELECT BillingCountry, ROUND(SUM(Total), 2) as TotalSales FROM Invoice GROUP BY BillingCountry;<file_sep>/queries/top_media_type.sql /* Provide a query that shows the most purchased Media Type. */ SELECT MediaTypeName, MAX(MediaTypeCount) as QuantitySold FROM ( SELECT m.Name as MediaTypeName, SUM(il.Quantity) as MediaTypeCount FROM MediaType m JOIN Track t ON t.MediaTypeId = m.MediaTypeId JOIN InvoiceLine il ON il.TrackId = t.TrackId GROUP BY m.MediaTypeId );<file_sep>/queries/total_invoices_2011.sql /* How many Invoices were there in 2009 and 2011? */ SELECT * FROM Invoice WHERE InvoiceDate >= '2011-01-01' AND InvoiceDate <= '2011-12-31';<file_sep>/queries/tracks_no_id.sql /* Provide a query that shows all the Tracks, but displays no IDs. The result should include the Album name, Media type and Genre. */ SELECT t.Name as TrackName, a.Title as AlbumName, m.Name as MediaTypeName, g.Name as GenreName FROM Track t JOIN Album a ON t.AlbumId = a.AlbumId JOIN MediaType m ON t.MediaTypeId = m.MediaTypeId JOIN Genre g ON t.GenreId = g.GenreId;<file_sep>/queries/top_2009_agent.sql /* Provide a query that shows total sales made by each sales agent. */ SELECT e.EmployeeId, e.FirstName || ' ' || e.LastName as EmployeeFullName, SUM(i.Total) as TotalSales FROM Employee e JOIN Customer c ON c.SupportRepId = e.EmployeeId JOIN Invoice i ON i.CustomerId = c.CustomerId WHERE Title = 'Sales Support Agent' AND i.InvoiceDate >= '2009-01-01' AND i.InvoiceDate <= '2009-12-31' GROUP BY e.EmployeeId ORDER BY TotalSales DESC LIMIT 1; /* Provide a query that shows total sales made by each sales agent (using max + subquery). */ SELECT EmployeeId, EmployeeFullName, MAX(TotalSales) FROM ( SELECT e.EmployeeId, e.FirstName || ' ' || e.LastName as EmployeeFullName, SUM(i.Total) as TotalSales FROM Employee e JOIN Customer c ON c.SupportRepId = e.EmployeeId JOIN Invoice i ON i.CustomerId = c.CustomerId WHERE Title = 'Sales Support Agent' AND i.InvoiceDate >= '2009-01-01' AND i.InvoiceDate <= '2009-12-31' GROUP BY e.EmployeeId );<file_sep>/queries/invoice_37_line_item_count.sql /* Looking at the InvoiceLine table, provide a query that COUNTs the number of line items for Invoice ID 37. */ SELECT COUNT(*) as Invoice37LineItems FROM Invoice i JOIN InvoiceLine il ON il.InvoiceId = i.InvoiceId WHERE i.InvoiceId = 37;<file_sep>/README.md # Chinook SQL questions. # ERD <img src="erd.png"><file_sep>/queries/invoices_line_item_count.sql /* Provide a query that shows all Invoices but includes the # of invoice line items. */ SELECT i.*, COUNT(*) as LineItemCount FROM Invoice i JOIN InvoiceLine il ON il.InvoiceId = i.InvoiceId GROUP BY i.InvoiceId;<file_sep>/queries/top_2013_track.sql /* Provide a query that shows the most purchased track of 2013. */ SELECT Name, MAX(PurchaseCount) FROM ( SELECT t.Name, SUM(il.Quantity) as PurchaseCount FROM Track t JOIN InvoiceLine il ON il.TrackId = t.TrackId JOIN Invoice i ON il.InvoiceId = i.InvoiceId WHERE i.InvoiceDate >= '2013-01-01' AND i.invoiceDate <= '2013-12-31' GROUP BY t.TrackId );<file_sep>/queries/total_invoices_2009.sql /* How many Invoices were there in 2009 and 2011? */ SELECT * FROM Invoice WHERE InvoiceDate >= '2009-01-01' AND InvoiceDate <= '2009-12-31';<file_sep>/queries/top_3_artists.sql /* Provide a query that shows the top 3 best selling artists. */ SELECT a.Name, SUM(il.Quantity) as PurchaseCount FROM Artist a JOIN Album al ON al.ArtistId = a.ArtistId JOIN Track t ON t.AlbumId = al.AlbumId JOIN InvoiceLine il ON il.TrackId = t.TrackId GROUP BY a.ArtistId ORDER BY PurchaseCount DESC LIMIT 3;<file_sep>/queries/line_items_per_invoice.sql /* Looking at the InvoiceLine table, provide a query that COUNTs the number of line items for each Invoice. */ SELECT InvoiceId, COUNT(*) as LineItemsCount FROM InvoiceLine GROUP BY InvoiceLine.InvoiceId;<file_sep>/queries/line_item_track_artist.sql /* Provide a query that includes the purchased track name AND artist name with each invoice line item. */ SELECT il.InvoiceLineId, t.Name as TrackName, ar.Name as ArtistName FROM InvoiceLine il JOIN Track t ON il.TrackId = t.TrackId JOIN Album al ON t.AlbumId = al.AlbumId JOIN Artist ar ON al.ArtistId = ar.ArtistId;<file_sep>/queries/top_country.sql /* Which country's customers spent the most? */ SELECT BillingCountry, MAX(TotalSales) FROM ( SELECT BillingCountry, ROUND(SUM(Total), 2) as TotalSales FROM Invoice GROUP BY BillingCountry );<file_sep>/queries/sales_agent_invoices.sql /* Provide a query that shows the invoices associated with each sales agent. The resultant table should include the Sales Agent's full name. */ SELECT e.FirstName, e.LastName, i.InvoiceId FROM Employee e JOIN Customer c ON e.EmployeeId = c.SupportRepId JOIN Invoice i ON i.CustomerId = c.CustomerId;<file_sep>/queries/sales_agent_total_sales.sql /* Provide a query that shows total sales made by each sales agent. */ SELECT e.EmployeeId, e.FirstName || ' ' || e.LastName as EmployeeFullName, ROUND(SUM(i.Total), 2) as TotalSales FROM Employee e JOIN Customer c ON c.SupportRepId = e.EmployeeId JOIN Invoice i ON i.CustomerId = c.CustomerId WHERE Title = 'Sales Support Agent' GROUP BY e.EmployeeId;
eba3669935192c2f7fff23a2aca719c87e5c0c1a
[ "Markdown", "SQL" ]
25
SQL
NSS-Day-Cohort-42/chinook-skratz17
0fde6e494c9b62fe367f3ee6f54476873754e2f6
9a1f78270e38ffbf54883a1575e5cf68aac5f133
refs/heads/master
<repo_name>katayude2/vm<file_sep>/vending_machine.rb # 使い方 # irbを起動 # require '/Users/tatsuyamatsuhashi/workspace/vending_machine/vending_machine.rb' # (↑のパスは、自動販売機ファイルが入っているパスを指定する) # 初期設定(自動販売機インスタンスを作成して、vmという変数に代入する) # vm = VendingMachine.new # 作成した自動販売機に500円を入れる # vm.insert(500) # 投入金額の合計を表示 # vm.total # 自動販売機内のジュース情報を表示 # vm.sale_info # 投入したお金を払い戻し # vm.refund # ジュースを買う # vm.purchase # 売り上げ金額を表示する # vm.sale_amount class VendingMachine MONEY = [10, 50, 100, 500, 1000].freeze def initialize @total = 0 @sale_amount = 0 end def insert(money) if MONEY.include?(money) # Calculator.sum(money) @total += money else money end end def total # Calculator.get_total @total end def reset @total = 0 end def sale_amount #Calculator.get_sale_amount @sale_amount end def add_sale_amount=(money) @sale_amount += money end # def refund # refunded_money = Calculator.get_total # Calculator.total_reset # puts "#{refunded_money}円の払い戻しです" # end def sale_info puts "買いますか?" Stock.get_drink_table.each do |drink| # if drink.stock > 0 && drink.price <= Calculator.get_total if drink.stock > 0 && drink.price <= @total puts "#{drink.name}, #{drink.price}円" end end puts "=======================" puts "売り切れごめんね" Stock.get_drink_table.each do |drink| if drink.stock == 0 puts "#{drink.name}, #{drink.price}円" end end # puts "=======================" # puts "お金が足りないよ" # Stock.get_drink_table.each do |drink| # if drink.price > Calculator.get_total # puts "#{drink.name}, #{drink.price}円" # end # end end # def purchase # drink = Choice.drink_choice # if drink.stock > 0 && drink.price <= Calculator.get_total # change = Calculator.get_total - drink.price # Calculator.total_reset # Stock.reduce(drink) # Calculator.add_sale_amount=(drink.price) # puts "#{drink.name}を買いました" # puts "#{change}円のお釣りです" # elsif drink.stock == 0 # puts "売り切れごめんね" # elsif drink.price > Calculator.get_total # puts "お金が足りないよ" # end # end # end # class Drink # attr_accessor :name, :price, :stock # def initialize(name, price) # @name = name # @price = price # @stock = 5 # end # end class Stock @coke = Drink.new("コーラ", 120) @red_bull = Drink.new("レッドブル", 200) @water = Drink.new("水", 100) @drink_table = [@@coke, @@red_bull, @@water] def self.get_drink_table @drink_table end def self.reduce(drink) @@coke.stock -= 1 if @@coke.name == drink.name @@red_bull.stock -= 1 if @@red_bull.name == drink.name @@water.stock -= 1 if @@water.name == drink.name end end # class Choice # def self.drink_choice # drinks = Stock.get_drink_table # puts "どれを買いますか" # puts "コーラ:1、レッドブル:2、水:3" # answer = gets.to_i # case answer # when 1 # drink = drinks[0] # when 2 # drink = drinks[1] # when 3 # drink = drinks[2] # else # puts "1,2,3を選んでください" # self.drink_choice # end # end end # drink = Drink.new # stock = Stock.new # choice = Choice.new
8243be69134edcdd87dfd9fb25774a2dece2f330
[ "Ruby" ]
1
Ruby
katayude2/vm
671ae0283c8b41ef143eed524c79a966be9486ae
22e62912c53eee198242927e9d5f261fe7fda068
refs/heads/master
<file_sep>import React, { Component } from 'react'; export default class Loading extends Component { constructor() { super(); this.state = { text: 'Loading', }; } /** * Gives an 'animation-effect' that will display Loading. -> Loading.. -> Loading... -> etc */ componentDidMount() { this.interval = window.setInterval(() => { const { text } = this.state; if (text === 'Loading...') { this.setState({ text: 'Loading' }); } else { this.setState({ text: `${text}.` }); } }, 200); } /** * Clear the interval when the component is destroyed */ componentWillUnmount() { window.clearInterval(this.interval); } render() { const { text } = this.state; return <div>{text}</div>; } } <file_sep># nav-bar Users are able to hover and click on links with a slider animation ## <strong>Key Features</strong> --- - Users are able to hover and click on links with a slider animation ## <strong>**SOME CONCERNS**</strong> - IT RESIZES CORRECTLY! BUT NEED TO FIGURE OUT HOW TO CORRECTLY ALIGN THE UNDERLINE ELEMENT WITH THE CITY NAMES - <strong>SOME THOUGHTS ON THE APPROACH</strong> - NEED TO RETRIEVE THE CURRENT POSITIONS OF THE CITY NAMES AND CALCULATE THE MARGINLEFT PROPERTY FOR THE UNDERLINE ELEMENT AND ACCUMULATE AND KEEP TRACK OF THE MARGINLEFT AND POSITION AS USERS TRY TO CLICK ON OTHER CITY NAMES (ASSUMING THEY ARE CLICKING FROM LEFT TO RIGHT/VICE VERSA/OR RANDOMLY) - MAY CALCULATE THROUGH COMPONENTDIDUPDATE (CHECK COMMENTS TO SEE WHY) --- ## <strong>How to use</strong> --- - Step 1. ```bash npm install ``` - Step 2. ```bash npm run build or npm run dev (to run in dev mode) ``` - Step 3. (skip this step if running in dev mode) Open index.html that is in the directory of: build/index.html - Step 4. Interact - Hover over city names to see the color of the links changing to blue - Click on various city names to see an underline animation ## <strong>Author</strong> <NAME> <file_sep>import React from 'react'; import NavBar from './components/NavBar/NavBar.jsx'; import './main.css'; import data from './data/navigation.json'; const App = () => ( <div className="app-container"> <NavBar destinations={data.cities} /> {/* IN ACTUAL PRODUCTION, YOU MAY INSERT A SWITCH COMPONENT TO INCLUDE ROUTES */} </div> ); export default App;
f1b222ee182121af7391bdf2031723b5f8698559
[ "JavaScript", "Markdown" ]
3
JavaScript
gerretkubota/nav-bar
cbcaf67d9a34523b91c2c9653dc47106b3cb5f3f
62ecd1bbe4523c7aae2036802454c57de0c25e49
refs/heads/master
<file_sep>var flickrApp = angular.module('flickrApp', [ 'ngRoute', 'flickrControllers', 'flickrServices', 'ui.bootstrap' ]); flickrApp .constant('CONFIG', { apiKey: '622326fd51e4ffecd5ae17a5771e4335' }); flickrApp.config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/photos', { templateUrl: 'partials/photo-list.html', controller: 'PhotoListCtrl' }). when('/photo/:photoId', { templateUrl: 'partials/photo-details.html', controller: 'PhotoDetailCtrl' }). when('/search/:keywords', { templateUrl: 'partials/photo-list.html', controller: 'SearchCtrl' }). otherwise({ redirectTo: '/photos' }); } ]);<file_sep>var flickrControllers = angular.module('flickrControllers', []); flickrControllers.controller('SearchCtrl', ['$scope', '$location', '$routeParams', 'Photo', function ($scope, $location, $routeParams, Photo) { $scope.search = function () { $location.path('/search/' + $scope.keywords); }; $scope.keywords = $routeParams.keywords; $scope.$watch('currentPage', function (newValue, oldValue) { if (newValue !== oldValue) { Photo.query({ text: $routeParams.keywords, page: newValue }, function (response) { $scope.photos = response.photos.photo; $scope.totalItems = response.photos.total; }); } }); if ($routeParams.keywords !== undefined) { Photo.query({ text: $routeParams.keywords }, function (response) { $scope.photos = response.photos.photo; $scope.totalItems = response.photos.total; }); } }]); flickrControllers.controller('PhotoListCtrl', ['$scope', '$modal', 'Photo', 'Person', function ($scope, $modal, Photo, Person) { $scope.showPosition = function (position) { $scope.lat = position.coords.latitude; $scope.lon = position.coords.longitude; $scope.currentPage = 1; $scope.$digest(); } $scope.getLocation = function () { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition($scope.showPosition); } } $scope.$watch('currentPage', function (newValue, oldValue) { if (newValue !== oldValue) { Photo.query({ lat: $scope.lat, lon: $scope.lon, page: newValue }, function (response) { $scope.photos = response.photos.photo; $scope.totalItems = response.photos.total; }); } }); $scope.showOwner = function (owner) { Person.query({ user_id: owner }, function (response) { $modal.open({ templateUrl: 'partials/modal.html', controller: 'ModalCtrl', resolve: { person: function () { return response.person; } } }); }); }; $scope.getLocation(); }]); flickrControllers.controller('PhotoDetailCtrl', ['$scope', '$routeParams', 'Photo', function ($scope, $routeParams, Photo) { Photo.query({ method: 'flickr.photos.getInfo', photo_id: $routeParams.photoId }, function (response) { $scope.photo = response.photo; console.log(response.photo); }); }]); flickrControllers.controller('ModalCtrl', function ($scope, $modalInstance, person) { $scope.person = person; $scope.close = function () { $modalInstance.dismiss('cancel'); }; });
b41a56a3a32740114104191bd159774f41c94ecc
[ "JavaScript" ]
2
JavaScript
lukaszgolder/angular-flickr
c463768993cb3768adc8875d9cf2396967a681b0
cc2660002fefb3d52aa94cba931d06f7a25ef967
refs/heads/master
<repo_name>spanich/djangoninja<file_sep>/apps/ninja/views.py from django.shortcuts import render def index(request): return render(request, 'ninja/index.html') def color(request, color): if color=='red': context={ 'name': 'Raphael', 'img': 'ninja/red.gif', } return render(request, 'ninja/color.html', context) elif color=='orange': orange={ 'name': 'Michelangelo', 'img': 'ninja/orange.jpg', } return render(request, 'ninja/color.html', orange) elif color=='purple': purple={ 'name': 'Donatello', 'img': 'ninja/purple.png', } return render(request, 'ninja/color.html', purple) elif color=='blue': blue={ 'name': 'Leonardo', 'img': 'ninja/blue.jpg', } return render(request, 'ninja/color.html', blue) else: megan={ 'name': '<NAME>', 'img': 'ninja/mf.jpg', } return render(request, 'ninja/color.html', megan)
e1acfc703413362953e545904f6157662633c8f5
[ "Python" ]
1
Python
spanich/djangoninja
a0ddd3bc0ede5fc8b4bbd4f109615effab9ff30f
bf28e7037a000641623baccb5e8b303bd013c359
refs/heads/master
<file_sep>#!/bin/bash cwdpath=`pwd` echo "current path $cwdpath" #clean rm -rf ~/.emacs rm -rf ~/emacs_plugins cp -rf $cwdpath/.emacs ~/ cp -rf $cwdpath/emacs_plugins ~/ <file_sep>#!/bin/bash #自动化配置emacs配置 #!会删除之前的配置 cwdpath=`pwd` echo "current path $cwdpath" #clean rm -rf ~/.emacs rm -rf ~/emacs_plugins ln -s $cwdpath/.emacs ~/ ln -s $cwdpath/emacs_plugins ~/
910de1ba23fa94762201fff864009d6577d558a3
[ "Shell" ]
2
Shell
dbian/emacs_config
ffa77a64583532b08816a476a8273a22c5c79207
37b9d031effa5eec77620d9400b40cc21afe21c9
refs/heads/master
<repo_name>i-van/sheet<file_sep>/public/javascripts/spreadsheet.js var Spreadsheet = function() { this.init.apply(this, arguments); } Spreadsheet.prototype = { init: function(id, cols, rows) { this._wrapper = $('#' + id).addClass('spreadsheet').hide(); this._cols = cols || 10; this._rows = rows || 25; this._instance = 0; this._initTable(); this._initInput(); this._initSelect(); for (var i = 0, n = this._cols; i < n; ++i) { this.setWidth(i, 100); } for (var j = 0, m = this._rows; j < m; ++j) { this.setHeight(j, 20); } }, _initSelect: function() { var that = this; this._table.delegate('td', 'click', function() { if (!!that.onSelect) { var cell = that._parseCell($(this)); that.onSelect.call(that, cell); } }); }, selectCell: function(cell, color) { var color = color || '#C8C8C8'; if (color == 'clear') { color = 'inherit'; } this._findCell(cell).css({'background-color': color}); }, _initInput: function() { this._input = $('<input />') .attr('type', 'text') .css({position: 'absolute', 'z-index': 100, display:'none'}) .appendTo(this._wrapper); var that = this; this._table.delegate('td', 'dblclick', function() { var e = $(this) , position = e.position(); that._input .css({left:position.left - 1 + 'px', top: position.top - 1 + 'px'}) .width(e.width()) .height(e.height()) .val(e.text()) .show() .focus(); that._activeCell = that._parseCell(e); }); this._input.blur(function() { var e = $(this).hide(); }); this._input.change(function() { if (!!that.onEdit) { that.onEdit.call(that, that._activeCell); } }); }, _initTable: function() { this._table = $('<table></table>') .attr('cellspacing', 0) .attr('cellpadding', 0) .appendTo(this._wrapper); var body = [] , n = this._rows , m = this._cols , id; for (var i = 0; i < n; ++i) { if (i == 0) { body.push('<tr>'); body.push('<th></th>'); for (var j = 0; j < m; ++j) { id = ['column', this._instance, j].join('-'); body.push('<th id="' + id + '"></th>'); } body.push('</tr>'); } body.push('<tr>'); id = ['row', this._instance, i].join('-'); body.push('<th id="' + id + '"></th>'); for (var j = 0; j < m; ++j) { id = ['cell', this._instance, i, j].join('-'); body.push('<td id="' + id + '"></td>'); } body.push('</tr>'); } this._table.html(body.join('')); this._findCell({row: 0, column: 0}).css({'border-width': '1px'}); for (var i = 1; i < n; ++i) { this._findCell({row: i, column: 0}).css({'border-width': '0 1px 1px 1px'}); } for (var i = 1; i < m; ++i) { this._findCell({row: 0, column: i}).css({'border-width': '1px 1px 1px 0'}); } }, setData: function(data) { var n = this._rows , m = this._cols; for (var i = 0; i < n; ++i) { for (var j = 0; j < m; ++j) { var cell = {row: i, column: j}; this.setCell(cell, data[i][j]); } } }, setWidth: function(column, width) { $('#' + ['column', this._instance, column].join('-')).width(width); return this; }, setHeight: function(row, height) { $('#' + ['row', this._instance, row].join('-')).height(height); return this; }, setCell: function(cell, data) { this._findCell(cell).text(data); return this; }, _findCell: function(cell) { return $('#' + ['cell', this._instance, cell.row, cell.column].join('-')); }, _parseCell: function(element) { var parts = element.attr('id').split('-'); return {row:parts[2], column:parts[3]}; }, show: function() { this._wrapper.show(); }, hide: function() { this._wrapper.hide(); } }; <file_sep>/models/sheet.js /** * sheet */ module.exports = ({ _cols: 10, _rows: 25, _storage: [], _default: '', set: function(cell, value) { this._storage[cell.row][cell.column] = value; }, get: function(cell) { return this._storage[cell.row][cell.column]; }, init: function() { var n = this._rows , m = this._cols , row; for (var i = 0; i < n; ++i) { row = []; for (var j = 0; j < m; ++j) { row.push(this._default); } this._storage.push(row); } return this; }, getStorage: function() { return this._storage; } }).init();<file_sep>/models/users.js /** * users */ module.exports = { _storage: [], add: function(user) { this._storage.push(user); }, remove: function(id) { for (var i = this._storage.length; i--;) { if (this._storage[i]['id'] == id) { this._storage.splice(i, 1); } } }, find: function(id) { for (var i = this._storage.length; i--;) { if (this._storage[i]['id'] == id) { return this._storage[i]; } } }, getStorage: function() { return this._storage; } };<file_sep>/app.js /** * module dependencies */ var express = require('express') , io = require('socket.io'); var app = module.exports = express.createServer() , socket = io.listen(app, {transports: ['websocket', 'xhr-polling', 'xhr-multipart']}); // configuration app.configure(function() { app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.compiler({src: __dirname + '/public', enable: ['sass']})); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function() { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function() { app.use(express.errorHandler()); }); // routes require('./config/routes')(app); // socket.io require('./controllers/socket.io')(socket); // run app.listen(3000); console.log("Express server listening on port %d", app.address().port); <file_sep>/config/routes.js /** * init routes */ var mainController = require('../controllers/main'); module.exports = function(app) { app.get('/', mainController.index); app.get('/dump', mainController.dump); };
8de9300343cf5db9aaa210fc0063cb518cb47b73
[ "JavaScript" ]
5
JavaScript
i-van/sheet
06c99110227296101bcfc6058678405b1818a30c
58eb89c27023d53908c37a4e636582d1509e8302
refs/heads/master
<repo_name>dongdong-2009/ASip<file_sep>/ASip/LanTool.h #ifndef LANTOOL #define LANTOOL #ifndef EXPORTING_DLL #define EXPORTING_DLL #endif struct TOOLDATA{ char call[8192]; /* member contains call details including individual parameters */ char summary[4096]; /* summary of jitter etc. for numbers of calls */ char error[1024]; /* contains error message */ } ; extern "C" __declspec(dllexport) void *WINAPI startSIPSessionint (char *argv[]); extern "C" __declspec(dllexport) void WINAPI StopSIPSIPSession(); extern "C" __declspec(dllexport) void WINAPI hangup(int n); extern "C" __declspec(dllexport) unsigned long WINAPI toolmain(LPVOID lrtpinet); extern "C" __declspec(dllexport) int WINAPI checkConnectivity(char *fqdn, int port); extern "C" __declspec(dllexport) int WINAPI startAudioCapture(char *fqdn, int port); /* to be implemented */ extern "C" __declspec(dllexport) struct TOOLDATA *WINAPI getStat(); struct TOOLDATA * (*callback) (); /* Please note return from the function "void *WINAPI startSIPSessionint (char *argv[])" should be casted type struct TOOLDATA (*callback) () which is basically getStat. This struction contains members as explained above. GetStat can be directly used. */ #endif<file_sep>/ASip/siprtp - Copy.cpp /* $Id: siprtp.c 3553 2011-05-05 06:14:19Z nanang $ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Copyright (C) ANPI LLC, USA // This file is for ANPI LLC Diagnosis tool // Since pjsip open source library is used in accorance the // licence for this or other files including binary library files // are as stated above paragraphs. #include "stdafx.h" extern "C" { struct { char call[8192]; char summary[4096]; } ToolData; static void print_call_log(int call_index); // Subbu static char *DLL_call_log(int call_index); // Subbu static const char *USAGE = " PURPOSE: \n" " This program establishes SIP INVITE session and media, and calculate \n" " the media quality (packet lost, jitter, rtt, etc.).\n" " USAGE:\n" " siprtp [options] URL \n" "\n" " Program options:\n" " --count=N, -c Set number of calls to create (default:1) \n" " --gap=N -g Set call gapping to N msec (default:0)\n" " --duration=SEC, -d Set maximum call duration (default:unlimited) \n" " --auto-quit, -q Quit when calls have been completed (default:no)\n" " --call-report -R Display report on call termination (default:yes)\n" "\n" " Address and ports options:\n" " --local-port=PORT,-p Set local SIP port (default: 5060)\n" " --rtp-port=PORT, -r Set start of RTP port (default: 4000)\n" " --ip-addr=IP, -i Set local IP address to use (otherwise it will\n" " try to determine local IP address from hostname)\n" "\n" ; /* Include all headers. */ #include <pjsip.h> #include <pjmedia.h> #include <pjmedia-codec.h> #include <pjsip_ua.h> #include <pjsip_simple.h> #include <pjlib-util.h> #include <pjlib.h> #include <stdlib.h> #if PJ_HAS_HIGH_RES_TIMER==0 #error "High resolution timer is needed for this sample" #endif #define THIS_FILE "ANPI Tools" #define MAX_CALLS 1024 #define RTP_START_PORT 4000 /* Codec descriptor: */ struct codec { unsigned pt; char* name; unsigned clock_rate; unsigned bit_rate; unsigned ptime; char* description; }; /* A bidirectional media stream created when the call is active. */ struct media_stream { /* Static: */ unsigned call_index; /* Call owner. */ unsigned media_index; /* Media index in call. */ pjmedia_transport *transport; /* To send/recv RTP/RTCP */ /* Active? */ pj_bool_t active; /* Non-zero if is in call. */ /* Current stream info: */ pjmedia_stream_info si; /* Current stream info. */ /* More info: */ unsigned clock_rate; /* clock rate */ unsigned samples_per_frame; /* samples per frame */ unsigned bytes_per_frame; /* frame size. */ /* RTP session: */ pjmedia_rtp_session out_sess; /* outgoing RTP session */ pjmedia_rtp_session in_sess; /* incoming RTP session */ /* RTCP stats: */ pjmedia_rtcp_session rtcp; /* incoming RTCP session. */ /* Thread: */ pj_bool_t thread_quit_flag; /* Stop media thread. */ pj_thread_t *thread; /* Media thread. */ }; /* This is a call structure that is created when the application starts * and only destroyed when the application quits. */ struct call { unsigned index; pjsip_inv_session *inv; unsigned media_count; struct media_stream media[1]; pj_time_val start_time; pj_time_val response_time; pj_time_val connect_time; pj_timer_entry d_timer; /**< Disconnect timer. */ }; /* Application's global variables */ static struct app { unsigned max_calls; unsigned call_gap; pj_bool_t call_report; unsigned uac_calls; unsigned duration; pj_bool_t auto_quit; unsigned thread_count; int sip_port; int rtp_start_port; pj_str_t local_addr; pj_str_t local_uri; pj_str_t local_contact; int app_log_level; int log_level; char *log_filename; char *report_filename; struct codec audio_codec; pj_str_t uri_to_call; pj_caching_pool cp; pj_pool_t *pool; pjsip_endpoint *sip_endpt; pj_bool_t thread_quit; pj_thread_t *sip_thread[1]; pjmedia_endpt *med_endpt; struct call call[MAX_CALLS]; } app; /* * Prototypes: */ /* Callback to be called when SDP negotiation is done in the call: */ static void call_on_media_update( pjsip_inv_session *inv, pj_status_t status); /* Callback to be called when invite session's state has changed: */ static void call_on_state_changed( pjsip_inv_session *inv, pjsip_event *e); /* Callback to be called when dialog has forked: */ static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e); /* Callback to be called to handle incoming requests outside dialogs: */ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ); /* Worker thread prototype */ static int sip_worker_thread(void *arg); /* Create SDP for call */ static pj_status_t create_sdp( pj_pool_t *pool, struct call *call, pjmedia_sdp_session **p_sdp); /* Hangup call */ static void hangup_call(unsigned index); /* Destroy the call's media */ static void destroy_call_media(unsigned call_index); /* Destroy media. */ static void destroy_media(); /* This callback is called by media transport on receipt of RTP packet. */ static void on_rx_rtp(void *user_data, void *pkt, pj_ssize_t size); /* This callback is called by media transport on receipt of RTCP packet. */ static void on_rx_rtcp(void *user_data, void *pkt, pj_ssize_t size); /* Display error */ static void app_perror(const char *sender, const char *title, pj_status_t status); /* Print call */ static void print_call(int call_index); /* This is a PJSIP module to be registered by application to handle * incoming requests outside any dialogs/transactions. The main purpose * here is to handle incoming INVITE request message, where we will * create a dialog and INVITE session for it. */ static pjsip_module mod_siprtp = { NULL, NULL, /* prev, next. */ { "mod-siprtpapp", 13 }, /* Name. */ -1, /* Id */ PJSIP_MOD_PRIORITY_APPLICATION, /* Priority */ NULL, /* load() */ NULL, /* start() */ NULL, /* stop() */ NULL, /* unload() */ &on_rx_request, /* on_rx_request() */ NULL, /* on_rx_response() */ NULL, /* on_tx_request. */ NULL, /* on_tx_response() */ NULL, /* on_tsx_state() */ }; /* Codec constants */ struct codec audio_codecs[] = { { 0, "PCMU", 8000, 64000, 20, "G.711 ULaw" }, { 3, "GSM", 8000, 13200, 20, "GSM" }, { 4, "G723", 8000, 6400, 30, "G.723.1" }, { 8, "PCMA", 8000, 64000, 20, "G.711 ALaw" }, { 18, "G729", 8000, 8000, 20, "G.729" }, }; /* * Init SIP stack */ static pj_status_t init_sip() { unsigned i; pj_status_t status; /* init PJLIB-UTIL: */ status = pjlib_util_init(); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Must create a pool factory before we can allocate any memory. */ pj_caching_pool_init(&app.cp, &pj_pool_factory_default_policy, 0); /* Create application pool for misc. */ app.pool = pj_pool_create(&app.cp.factory, "app", 1000, 1000, NULL); /* Create the endpoint: */ status = pjsip_endpt_create(&app.cp.factory, pj_gethostname()->ptr, &app.sip_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Add UDP transport. */ { pj_sockaddr_in addr; pjsip_host_port addrname; pjsip_transport *tp; pj_bzero(&addr, sizeof(addr)); addr.sin_family = pj_AF_INET(); addr.sin_addr.s_addr = 0; addr.sin_port = pj_htons((pj_uint16_t)app.sip_port); if (app.local_addr.slen) { addrname.host = app.local_addr; addrname.port = app.sip_port; status = pj_sockaddr_in_init(&addr, &app.local_addr, (pj_uint16_t)app.sip_port); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Unable to resolve IP interface", status); return status; } } status = pjsip_udp_transport_start( app.sip_endpt, &addr, (app.local_addr.slen ? &addrname:NULL), 1, &tp); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Unable to start UDP transport", status); return status; } PJ_LOG(3,(THIS_FILE, "SIP UDP listening on %.*s:%d", (int)tp->local_name.host.slen, tp->local_name.host.ptr, tp->local_name.port)); } /* * Init transaction layer. * This will create/initialize transaction hash tables etc. */ status = pjsip_tsx_layer_init_module(app.sip_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Initialize UA layer. */ status = pjsip_ua_init_module( app.sip_endpt, NULL ); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Initialize 100rel support */ status = pjsip_100rel_init_module(app.sip_endpt); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Init invite session module. */ { pjsip_inv_callback inv_cb; /* Init the callback for INVITE session: */ pj_bzero(&inv_cb, sizeof(inv_cb)); inv_cb.on_state_changed = &call_on_state_changed; inv_cb.on_new_session = &call_on_forked; inv_cb.on_media_update = &call_on_media_update; /* Initialize invite session module: */ status = pjsip_inv_usage_init(app.sip_endpt, &inv_cb); PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1); } /* Register our module to receive incoming requests. */ status = pjsip_endpt_register_module( app.sip_endpt, &mod_siprtp); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Init calls */ for (i=0; i<app.max_calls; ++i) app.call[i].index = i; /* Done */ return PJ_SUCCESS; } /* * Destroy SIP */ static void destroy_sip() { unsigned i; app.thread_quit = 1; for (i=0; i<app.thread_count; ++i) { if (app.sip_thread[i]) { pj_thread_join(app.sip_thread[i]); pj_thread_destroy(app.sip_thread[i]); app.sip_thread[i] = NULL; } } if (app.sip_endpt) { pjsip_endpt_destroy(app.sip_endpt); app.sip_endpt = NULL; } } /* * Init media stack. */ static pj_status_t init_media() { unsigned i, count; pj_uint16_t rtp_port; pj_status_t status; /* Initialize media endpoint so that at least error subsystem is properly * initialized. */ #if PJ_HAS_THREADS status = pjmedia_endpt_create(&app.cp.factory, NULL, 1, &app.med_endpt); #else status = pjmedia_endpt_create(&app.cp.factory, pjsip_endpt_get_ioqueue(app.sip_endpt), 0, &app.med_endpt); #endif PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Must register codecs to be supported */ #if defined(PJMEDIA_HAS_G711_CODEC) && PJMEDIA_HAS_G711_CODEC!=0 pjmedia_codec_g711_init(app.med_endpt); #endif /* RTP port counter */ rtp_port = (pj_uint16_t)(app.rtp_start_port & 0xFFFE); /* Init media transport for all calls. */ for (i=0, count=0; i<app.max_calls; ++i, ++count) { unsigned j; /* Create transport for each media in the call */ for (j=0; j<PJ_ARRAY_SIZE(app.call[0].media); ++j) { /* Repeat binding media socket to next port when fails to bind * to current port number. */ int retry; app.call[i].media[j].call_index = i; app.call[i].media[j].media_index = j; status = -1; for (retry=0; retry<100; ++retry,rtp_port+=2) { struct media_stream *m = &app.call[i].media[j]; status = pjmedia_transport_udp_create2(app.med_endpt, "siprtp", &app.local_addr, rtp_port, 0, &m->transport); if (status == PJ_SUCCESS) { rtp_port += 2; break; } } } if (status != PJ_SUCCESS) goto on_error; } /* Done */ return PJ_SUCCESS; on_error: destroy_media(); return status; } /* * Destroy media. */ static void destroy_media() { unsigned i; for (i=0; i<app.max_calls; ++i) { unsigned j; for (j=0; j<PJ_ARRAY_SIZE(app.call[0].media); ++j) { struct media_stream *m = &app.call[i].media[j]; if (m->transport) { pjmedia_transport_close(m->transport); m->transport = NULL; } } } if (app.med_endpt) { pjmedia_endpt_destroy(app.med_endpt); app.med_endpt = NULL; } } /* * Make outgoing call. */ static pj_status_t make_call(const pj_str_t *dst_uri) { unsigned i; struct call *call; pjsip_dialog *dlg; pjmedia_sdp_session *sdp; pjsip_tx_data *tdata; pj_status_t status; /* Find unused call slot */ for (i=0; i<app.max_calls; ++i) { if (app.call[i].inv == NULL) break; } if (i == app.max_calls) return PJ_ETOOMANY; call = &app.call[i]; /* Create UAC dialog */ status = pjsip_dlg_create_uac( pjsip_ua_instance(), &app.local_uri, /* local URI */ &app.local_contact, /* local Contact */ dst_uri, /* remote URI */ dst_uri, /* remote target */ &dlg); /* dialog */ if (status != PJ_SUCCESS) { ++app.uac_calls; return status; } /* Create SDP */ create_sdp( dlg->pool, call, &sdp); /* Create the INVITE session. */ status = pjsip_inv_create_uac( dlg, sdp, 0, &call->inv); if (status != PJ_SUCCESS) { pjsip_dlg_terminate(dlg); ++app.uac_calls; return status; } /* Attach call data to invite session */ call->inv->mod_data[mod_siprtp.id] = call; /* Mark start of call */ pj_gettimeofday(&call->start_time); /* Create initial INVITE request. * This INVITE request will contain a perfectly good request and * an SDP body as well. */ status = pjsip_inv_invite(call->inv, &tdata); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); /* Send initial INVITE request. * From now on, the invite session's state will be reported to us * via the invite session callbacks. */ status = pjsip_inv_send_msg(call->inv, tdata); PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); return PJ_SUCCESS; } /* * Receive incoming call */ static void process_incoming_call(pjsip_rx_data *rdata) { unsigned i, options; struct call *call; pjsip_dialog *dlg; pjmedia_sdp_session *sdp; pjsip_tx_data *tdata; pj_status_t status; /* Find free call slot */ for (i=0; i<app.max_calls; ++i) { if (app.call[i].inv == NULL) break; } if (i == app.max_calls) { const pj_str_t reason = pj_str("Too many calls"); pjsip_endpt_respond_stateless( app.sip_endpt, rdata, 500, &reason, NULL, NULL); return; } call = &app.call[i]; /* Verify that we can handle the request. */ options = 0; status = pjsip_inv_verify_request(rdata, &options, NULL, NULL, app.sip_endpt, &tdata); if (status != PJ_SUCCESS) { /* * No we can't handle the incoming INVITE request. */ if (tdata) { pjsip_response_addr res_addr; pjsip_get_response_addr(tdata->pool, rdata, &res_addr); pjsip_endpt_send_response(app.sip_endpt, &res_addr, tdata, NULL, NULL); } else { /* Respond with 500 (Internal Server Error) */ pjsip_endpt_respond_stateless(app.sip_endpt, rdata, 500, NULL, NULL, NULL); } return; } /* Create UAS dialog */ status = pjsip_dlg_create_uas( pjsip_ua_instance(), rdata, &app.local_contact, &dlg); if (status != PJ_SUCCESS) { const pj_str_t reason = pj_str("Unable to create dialog"); pjsip_endpt_respond_stateless( app.sip_endpt, rdata, 500, &reason, NULL, NULL); return; } /* Create SDP */ create_sdp( dlg->pool, call, &sdp); /* Create UAS invite session */ status = pjsip_inv_create_uas( dlg, rdata, sdp, 0, &call->inv); if (status != PJ_SUCCESS) { pjsip_dlg_create_response(dlg, rdata, 500, NULL, &tdata); pjsip_dlg_send_response(dlg, pjsip_rdata_get_tsx(rdata), tdata); return; } /* Attach call data to invite session */ call->inv->mod_data[mod_siprtp.id] = call; /* Mark start of call */ pj_gettimeofday(&call->start_time); /* Create 200 response .*/ status = pjsip_inv_initial_answer(call->inv, rdata, 200, NULL, NULL, &tdata); if (status != PJ_SUCCESS) { status = pjsip_inv_initial_answer(call->inv, rdata, PJSIP_SC_NOT_ACCEPTABLE, NULL, NULL, &tdata); if (status == PJ_SUCCESS) pjsip_inv_send_msg(call->inv, tdata); else pjsip_inv_terminate(call->inv, 500, PJ_FALSE); return; } /* Send the 200 response. */ status = pjsip_inv_send_msg(call->inv, tdata); PJ_ASSERT_ON_FAIL(status == PJ_SUCCESS, return); /* Done */ } /* Callback to be called when dialog has forked: */ static void call_on_forked(pjsip_inv_session *inv, pjsip_event *e) { PJ_UNUSED_ARG(inv); PJ_UNUSED_ARG(e); // PJ_TODO( HANDLE_FORKING ); } /* Callback to be called to handle incoming requests outside dialogs: */ static pj_bool_t on_rx_request( pjsip_rx_data *rdata ) { /* Ignore strandled ACKs (must not send respone */ if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) return PJ_FALSE; /* Respond (statelessly) any non-INVITE requests with 500 */ if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD) { pj_str_t reason = pj_str("Unsupported Operation"); pjsip_endpt_respond_stateless( app.sip_endpt, rdata, 500, &reason, NULL, NULL); return PJ_TRUE; } /* Handle incoming INVITE */ process_incoming_call(rdata); /* Done */ return PJ_TRUE; } /* Callback timer to disconnect call (limiting call duration) */ static void timer_disconnect_call( pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry) { struct call *call = (struct call *) entry->user_data; PJ_UNUSED_ARG(timer_heap); entry->id = 0; hangup_call(call->index); } /* Callback to be called when invite session's state has changed: */ static void call_on_state_changed( pjsip_inv_session *inv, pjsip_event *e) { struct call *call = (struct call *)inv->mod_data[mod_siprtp.id]; PJ_UNUSED_ARG(e); if (!call) return; if (inv->state == PJSIP_INV_STATE_DISCONNECTED) { pj_time_val null_time = {0, 0}; if (call->d_timer.id != 0) { pjsip_endpt_cancel_timer(app.sip_endpt, &call->d_timer); call->d_timer.id = 0; } PJ_LOG(3,(THIS_FILE, "Call #%d disconnected. Reason=%d (%.*s)", call->index + 1, inv->cause, (int)inv->cause_text.slen, inv->cause_text.ptr)); if (app.call_report) { PJ_LOG(3,(THIS_FILE, "Call #%d statistics:", call->index)); // print_call_log(call->index); // print_call(call->index); DLL_call_log(call->index); } call->inv = NULL; inv->mod_data[mod_siprtp.id] = NULL; destroy_call_media(call->index); call->start_time = null_time; call->response_time = null_time; call->connect_time = null_time; ++app.uac_calls; } else if (inv->state == PJSIP_INV_STATE_CONFIRMED) { pj_time_val t; pj_gettimeofday(&call->connect_time); if (call->response_time.sec == 0) call->response_time = call->connect_time; t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); PJ_LOG(3,(THIS_FILE, "Call #%d connected in %d ms", call->index +1 , PJ_TIME_VAL_MSEC(t))); if (app.duration != 0) { call->d_timer.id = 1; call->d_timer.user_data = call; call->d_timer.cb = &timer_disconnect_call; t.sec = app.duration; t.msec = 0; pjsip_endpt_schedule_timer(app.sip_endpt, &call->d_timer, &t); } } else if ( inv->state == PJSIP_INV_STATE_EARLY || inv->state == PJSIP_INV_STATE_CONNECTING) { if (call->response_time.sec == 0) pj_gettimeofday(&call->response_time); } } /* Utility */ static void app_perror(const char *sender, const char *title, pj_status_t status) { char errmsg[PJ_ERR_MSG_SIZE]; pj_strerror(status, errmsg, sizeof(errmsg)); PJ_LOG(3,(sender, "%s: %s [status=%d]", title, errmsg, status)); } /* Worker thread for SIP */ static int sip_worker_thread(void *arg) { PJ_UNUSED_ARG(arg); while (!app.thread_quit) { pj_time_val timeout = {0, 10}; pjsip_endpt_handle_events(app.sip_endpt, &timeout); } return 0; } /* Init application options */ static pj_status_t init_options(int argc, char *argv[], char* Name) { static char ip_addr[32]; static char local_uri[64]; enum { OPT_START, OPT_APP_LOG_LEVEL, OPT_LOG_FILE, OPT_A_PT, OPT_A_NAME, OPT_A_CLOCK, OPT_A_BITRATE, OPT_A_PTIME, OPT_REPORT_FILE }; struct pj_getopt_option long_options[] = { { "count", 1, 0, 'c' }, { "gap", 1, 0, 'g' }, { "call-report", 0, 0, 'R' }, { "duration", 1, 0, 'd' }, { "auto-quit", 0, 0, 'q' }, { "local-port", 1, 0, 'p' }, { "rtp-port", 1, 0, 'r' }, { "ip-addr", 1, 0, 'i' }, { "log-level", 1, 0, 'l' }, { "app-log-level", 1, 0, OPT_APP_LOG_LEVEL }, { "log-file", 1, 0, OPT_LOG_FILE }, { "report-file", 1, 0, OPT_REPORT_FILE }, /* Don't support this anymore, see comments in USAGE above. { "a-pt", 1, 0, OPT_A_PT }, { "a-name", 1, 0, OPT_A_NAME }, { "a-clock", 1, 0, OPT_A_CLOCK }, { "a-bitrate", 1, 0, OPT_A_BITRATE }, { "a-ptime", 1, 0, OPT_A_PTIME }, */ { NULL, 0, 0, 0 }, }; int c; int option_index; /* Get local IP address for the default IP address */ { const pj_str_t *hostname; pj_sockaddr_in tmp_addr; char *addr; hostname = pj_gethostname(); pj_sockaddr_in_init(&tmp_addr, hostname, 0); addr = pj_inet_ntoa(tmp_addr.sin_addr); pj_ansi_strcpy(ip_addr, addr); } /* Init defaults */ app.max_calls = 1; app.thread_count = 1; app.sip_port = 5060; app.rtp_start_port = RTP_START_PORT; app.local_addr = pj_str(ip_addr); app.log_level = 5; app.app_log_level = 3; app.log_filename = NULL; /* Default codecs: */ app.audio_codec = audio_codecs[0]; /* Parse options */ pj_optind = 0; while((c=pj_getopt_long(argc,argv, "c:d:p:r:i:l:g:qR", long_options, &option_index))!=-1) { switch (c) { case 'c': app.max_calls = atoi(pj_optarg); if (app.max_calls < 0 || app.max_calls > MAX_CALLS) { PJ_LOG(3,(THIS_FILE, "Invalid max calls value %s", pj_optarg)); return 1; } break; case 'g': app.call_gap = atoi(pj_optarg); break; case 'R': app.call_report = PJ_TRUE; break; case 'd': app.duration = atoi(pj_optarg); break; case 'q': app.auto_quit = 1; break; case 'p': app.sip_port = atoi(pj_optarg); break; case 'r': app.rtp_start_port = atoi(pj_optarg); break; case 'i': app.local_addr = pj_str(pj_optarg); break; case 'l': app.log_level = atoi(pj_optarg); break; /* case OPT_APP_LOG_LEVEL: app.app_log_level = atoi(pj_optarg); break; case OPT_LOG_FILE: app.log_filename = pj_optarg; break; case OPT_A_PT: app.audio_codec.pt = atoi(pj_optarg); break; case OPT_A_NAME: app.audio_codec.name = pj_optarg; break; case OPT_A_CLOCK: app.audio_codec.clock_rate = atoi(pj_optarg); break; case OPT_A_BITRATE: app.audio_codec.bit_rate = atoi(pj_optarg); break; case OPT_A_PTIME: app.audio_codec.ptime = atoi(pj_optarg); break; case OPT_REPORT_FILE: app.report_filename = pj_optarg; break; */ default: puts(USAGE); return 1; } } /* Check if URL is specified */ if (pj_optind < argc) app.uri_to_call = pj_str(argv[pj_optind]); /* Build local URI and contact */ pj_ansi_sprintf( local_uri, "sip:%s@%s:%d", Name, app.local_addr.ptr, app.sip_port); app.local_uri = pj_str(local_uri); app.local_contact = app.local_uri; return PJ_SUCCESS; } /***************************************************************************** * MEDIA STUFFS */ /* * Create SDP session for a call. */ static pj_status_t create_sdp( pj_pool_t *pool, struct call *call, pjmedia_sdp_session **p_sdp) { pj_time_val tv; pjmedia_sdp_session *sdp; pjmedia_sdp_media *m; pjmedia_sdp_attr *attr; pjmedia_transport_info tpinfo; struct media_stream *audio = &call->media[0]; PJ_ASSERT_RETURN(pool && p_sdp, PJ_EINVAL); /* Get transport info */ pjmedia_transport_info_init(&tpinfo); pjmedia_transport_get_info(audio->transport, &tpinfo); /* Create and initialize basic SDP session */ sdp = (pjmedia_sdp_session *) pj_pool_zalloc (pool, sizeof(pjmedia_sdp_session)); pj_gettimeofday(&tv); sdp->origin.user = pj_str("pjsip-siprtp"); sdp->origin.version = sdp->origin.id = tv.sec + 2208988800UL; sdp->origin.net_type = pj_str("IN"); sdp->origin.addr_type = pj_str("IP4"); sdp->origin.addr = *pj_gethostname(); sdp->name = pj_str("pjsip"); /* Since we only support one media stream at present, put the * SDP connection line in the session level. */ sdp->conn = (pjmedia_sdp_conn *) pj_pool_zalloc (pool, sizeof(pjmedia_sdp_conn)); sdp->conn->net_type = pj_str("IN"); sdp->conn->addr_type = pj_str("IP4"); sdp->conn->addr = app.local_addr; /* SDP time and attributes. */ sdp->time.start = sdp->time.stop = 0; sdp->attr_count = 0; /* Create media stream 0: */ sdp->media_count = 1; m = (pjmedia_sdp_media *) pj_pool_zalloc (pool, sizeof(pjmedia_sdp_media)); sdp->media[0] = m; /* Standard media info: */ m->desc.media = pj_str("audio"); m->desc.port = pj_ntohs(tpinfo.sock_info.rtp_addr_name.ipv4.sin_port); m->desc.port_count = 1; m->desc.transport = pj_str("RTP/AVP"); /* Add format and rtpmap for each codec. */ m->desc.fmt_count = 1; m->attr_count = 0; { pjmedia_sdp_rtpmap rtpmap; pjmedia_sdp_attr *attr; char ptstr[10]; sprintf(ptstr, "%d", app.audio_codec.pt); pj_strdup2(pool, &m->desc.fmt[0], ptstr); rtpmap.pt = m->desc.fmt[0]; rtpmap.clock_rate = app.audio_codec.clock_rate; rtpmap.enc_name = pj_str(app.audio_codec.name); rtpmap.param.slen = 0; pjmedia_sdp_rtpmap_to_attr(pool, &rtpmap, &attr); m->attr[m->attr_count++] = attr; } /* Add sendrecv attribute. */ attr = (pjmedia_sdp_attr *) pj_pool_zalloc(pool, sizeof(pjmedia_sdp_attr)); attr->name = pj_str("sendrecv"); m->attr[m->attr_count++] = attr; #if 1 /* * Add support telephony event */ m->desc.fmt[m->desc.fmt_count++] = pj_str("121"); /* Add rtpmap. */ attr = (pjmedia_sdp_attr *)pj_pool_zalloc(pool, sizeof(pjmedia_sdp_attr)); attr->name = pj_str("rtpmap"); attr->value = pj_str("121 telephone-event/8000"); m->attr[m->attr_count++] = attr; /* Add fmtp */ attr = (pjmedia_sdp_attr *) pj_pool_zalloc(pool, sizeof(pjmedia_sdp_attr)); attr->name = pj_str("fmtp"); attr->value = pj_str("121 0-15"); m->attr[m->attr_count++] = attr; #endif /* Done */ *p_sdp = sdp; return PJ_SUCCESS; } #if defined(PJ_WIN32) && PJ_WIN32 != 0 #include <windows.h> static void boost_priority(void) { SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); } #elif defined(PJ_LINUX) && PJ_LINUX != 0 #include <pthread.h> static void boost_priority(void) { #define POLICY SCHED_FIFO struct sched_param tp; int max_prio; int policy; int rc; if (sched_get_priority_min(POLICY) < sched_get_priority_max(POLICY)) max_prio = sched_get_priority_max(POLICY)-1; else max_prio = sched_get_priority_max(POLICY)+1; /* * Adjust process scheduling algorithm and priority */ rc = sched_getparam(0, &tp); if (rc != 0) { app_perror( THIS_FILE, "sched_getparam error", PJ_RETURN_OS_ERROR(rc)); return; } tp.__sched_priority = max_prio; rc = sched_setscheduler(0, POLICY, &tp); if (rc != 0) { app_perror( THIS_FILE, "sched_setscheduler error", PJ_RETURN_OS_ERROR(rc)); } PJ_LOG(4, (THIS_FILE, "New process policy=%d, priority=%d", policy, tp.__sched_priority)); /* * Adjust thread scheduling algorithm and priority */ rc = pthread_getschedparam(pthread_self(), &policy, &tp); if (rc != 0) { app_perror( THIS_FILE, "pthread_getschedparam error", PJ_RETURN_OS_ERROR(rc)); return; } PJ_LOG(4, (THIS_FILE, "Old thread policy=%d, priority=%d", policy, tp.__sched_priority)); policy = POLICY; tp.__sched_priority = max_prio; rc = pthread_setschedparam(pthread_self(), policy, &tp); if (rc != 0) { app_perror( THIS_FILE, "pthread_setschedparam error", PJ_RETURN_OS_ERROR(rc)); return; } PJ_LOG(4, (THIS_FILE, "New thread policy=%d, priority=%d", policy, tp.__sched_priority)); } #else # define boost_priority() #endif /* * This callback is called by media transport on receipt of RTP packet. */ static void on_rx_rtp(void *user_data, void *pkt, pj_ssize_t size) { struct media_stream *strm; pj_status_t status; const pjmedia_rtp_hdr *hdr; const void *payload; unsigned payload_len; strm = ( struct media_stream *) user_data; /* Discard packet if media is inactive */ if (!strm->active) return; /* Check for errors */ if (size < 0) { app_perror(THIS_FILE, "RTP recv() error", -size); return; } /* Decode RTP packet. */ status = pjmedia_rtp_decode_rtp(&strm->in_sess, pkt, size, &hdr, &payload, &payload_len); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "RTP decode error", status); return; } //PJ_LOG(4,(THIS_FILE, "Rx seq=%d", pj_ntohs(hdr->seq))); /* Update the RTCP session. */ pjmedia_rtcp_rx_rtp(&strm->rtcp, pj_ntohs(hdr->seq), pj_ntohl(hdr->ts), payload_len); /* Update RTP session */ pjmedia_rtp_session_update(&strm->in_sess, hdr, NULL); } /* * This callback is called by media transport on receipt of RTCP packet. */ static void on_rx_rtcp(void *user_data, void *pkt, pj_ssize_t size) { struct media_stream *strm; strm = ( struct media_stream *)user_data; /* Discard packet if media is inactive */ if (!strm->active) return; /* Check for errors */ if (size < 0) { app_perror(THIS_FILE, "Error receiving RTCP packet", -size); return; } /* Update RTCP session */ pjmedia_rtcp_rx_rtcp(&strm->rtcp, pkt, size); } /* * Media thread * * This is the thread to send and receive both RTP and RTCP packets. */ static int media_thread(void *arg) { enum { RTCP_INTERVAL = 5000, RTCP_RAND = 2000 }; struct media_stream *strm = (struct media_stream *) arg; char packet[1500]; unsigned msec_interval; pj_timestamp freq, next_rtp, next_rtcp; /* Boost thread priority if necessary */ boost_priority(); /* Let things settle */ pj_thread_sleep(100); msec_interval = strm->samples_per_frame * 1000 / strm->clock_rate; pj_get_timestamp_freq(&freq); pj_get_timestamp(&next_rtp); next_rtp.u64 += (freq.u64 * msec_interval / 1000); next_rtcp = next_rtp; next_rtcp.u64 += (freq.u64 * (RTCP_INTERVAL+(pj_rand()%RTCP_RAND)) / 1000); while (!strm->thread_quit_flag) { pj_timestamp now, lesser; pj_time_val timeout; pj_bool_t send_rtp, send_rtcp; send_rtp = send_rtcp = PJ_FALSE; /* Determine how long to sleep */ if (next_rtp.u64 < next_rtcp.u64) { lesser = next_rtp; send_rtp = PJ_TRUE; } else { lesser = next_rtcp; send_rtcp = PJ_TRUE; } pj_get_timestamp(&now); if (lesser.u64 <= now.u64) { timeout.sec = timeout.msec = 0; //printf("immediate "); fflush(stdout); } else { pj_uint64_t tick_delay; tick_delay = lesser.u64 - now.u64; timeout.sec = 0; timeout.msec = (pj_uint32_t)(tick_delay * 1000 / freq.u64); pj_time_val_normalize(&timeout); //printf("%d:%03d ", timeout.sec, timeout.msec); fflush(stdout); } /* Wait for next interval */ //if (timeout.sec!=0 && timeout.msec!=0) { pj_thread_sleep(PJ_TIME_VAL_MSEC(timeout)); if (strm->thread_quit_flag) break; //} pj_get_timestamp(&now); if (send_rtp || next_rtp.u64 <= now.u64) { /* * Time to send RTP packet. */ pj_status_t status; const void *p_hdr; const pjmedia_rtp_hdr *hdr; pj_ssize_t size; int hdrlen; /* Format RTP header */ status = pjmedia_rtp_encode_rtp( &strm->out_sess, strm->si.tx_pt, 0, /* marker bit */ strm->bytes_per_frame, strm->samples_per_frame, &p_hdr, &hdrlen); if (status == PJ_SUCCESS) { //PJ_LOG(4,(THIS_FILE, "\t\tTx seq=%d", pj_ntohs(hdr->seq))); hdr = (const pjmedia_rtp_hdr*) p_hdr; /* Copy RTP header to packet */ pj_memcpy(packet, hdr, hdrlen); /* Zero the payload */ pj_bzero(packet+hdrlen, strm->bytes_per_frame); /* Send RTP packet */ size = hdrlen + strm->bytes_per_frame; status = pjmedia_transport_send_rtp(strm->transport, packet, size); if (status != PJ_SUCCESS) app_perror(THIS_FILE, "Error sending RTP packet", status); } else { pj_assert(!"RTP encode() error"); } /* Update RTCP SR */ pjmedia_rtcp_tx_rtp( &strm->rtcp, (pj_uint16_t)strm->bytes_per_frame); /* Schedule next send */ next_rtp.u64 += (msec_interval * freq.u64 / 1000); } if (send_rtcp || next_rtcp.u64 <= now.u64) { /* * Time to send RTCP packet. */ void *rtcp_pkt; int rtcp_len; pj_ssize_t size; pj_status_t status; /* Build RTCP packet */ pjmedia_rtcp_build_rtcp(&strm->rtcp, &rtcp_pkt, &rtcp_len); /* Send packet */ size = rtcp_len; status = pjmedia_transport_send_rtcp(strm->transport, rtcp_pkt, size); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Error sending RTCP packet", status); } /* Schedule next send */ next_rtcp.u64 += (freq.u64 * (RTCP_INTERVAL+(pj_rand()%RTCP_RAND)) / 1000); } } return 0; } /* Callback to be called when SDP negotiation is done in the call: */ static void call_on_media_update( pjsip_inv_session *inv, pj_status_t status) { struct call *call; pj_pool_t *pool; struct media_stream *audio; const pjmedia_sdp_session *local_sdp, *remote_sdp; struct codec *codec_desc = NULL; unsigned i; call = (struct call *) inv->mod_data[mod_siprtp.id]; pool = inv->dlg->pool; audio = &call->media[0]; /* If this is a mid-call media update, then destroy existing media */ if (audio->thread != NULL) destroy_call_media(call->index); /* Do nothing if media negotiation has failed */ if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "SDP negotiation failed", status); return; } /* Capture stream definition from the SDP */ pjmedia_sdp_neg_get_active_local(inv->neg, &local_sdp); pjmedia_sdp_neg_get_active_remote(inv->neg, &remote_sdp); status = pjmedia_stream_info_from_sdp(&audio->si, inv->pool, app.med_endpt, local_sdp, remote_sdp, 0); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Error creating stream info from SDP", status); return; } /* Get the remainder of codec information from codec descriptor */ if (audio->si.fmt.pt == app.audio_codec.pt) codec_desc = &app.audio_codec; else { /* Find the codec description in codec array */ for (i=0; i<PJ_ARRAY_SIZE(audio_codecs); ++i) { if (audio_codecs[i].pt == audio->si.fmt.pt) { codec_desc = &audio_codecs[i]; break; } } if (codec_desc == NULL) { PJ_LOG(3, (THIS_FILE, "Error: Invalid codec payload type")); return; } } audio->clock_rate = audio->si.fmt.clock_rate; audio->samples_per_frame = audio->clock_rate * codec_desc->ptime / 1000; audio->bytes_per_frame = codec_desc->bit_rate * codec_desc->ptime / 1000 / 8; pjmedia_rtp_session_init(&audio->out_sess, audio->si.tx_pt, pj_rand()); pjmedia_rtp_session_init(&audio->in_sess, audio->si.fmt.pt, 0); pjmedia_rtcp_init(&audio->rtcp, "rtcp", audio->clock_rate, audio->samples_per_frame, 0); /* Attach media to transport */ status = pjmedia_transport_attach(audio->transport, audio, &audio->si.rem_addr, &audio->si.rem_rtcp, sizeof(pj_sockaddr_in), &on_rx_rtp, &on_rx_rtcp); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Error on pjmedia_transport_attach()", status); return; } /* Start media thread. */ audio->thread_quit_flag = 0; #if PJ_HAS_THREADS status = pj_thread_create( inv->pool, "media", &media_thread, audio, 0, 0, &audio->thread); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Error creating media thread", status); return; } #endif /* Set the media as active */ audio->active = PJ_TRUE; } /* Destroy call's media */ static void destroy_call_media(unsigned call_index) { struct media_stream *audio = &app.call[call_index].media[0]; if (audio) { audio->active = PJ_FALSE; if (audio->thread) { audio->thread_quit_flag = 1; pj_thread_join(audio->thread); pj_thread_destroy(audio->thread); audio->thread = NULL; audio->thread_quit_flag = 0; } pjmedia_transport_detach(audio->transport, audio); } } /***************************************************************************** * USER INTERFACE STUFFS */ static void call_get_duration(int call_index, pj_time_val *dur) { struct call *call = &app.call[call_index]; pjsip_inv_session *inv; dur->sec = dur->msec = 0; if (!call) return; inv = call->inv; if (!inv) return; if (inv->state >= PJSIP_INV_STATE_CONFIRMED && call->connect_time.sec) { pj_gettimeofday(dur); PJ_TIME_VAL_SUB((*dur), call->connect_time); } } static const char *good_number(char *buf, pj_int32_t val) { if (val < 1000) { pj_ansi_sprintf(buf, "%d", val); } else if (val < 1000000) { pj_ansi_sprintf(buf, "%d.%02dK", val / 1000, (val % 1000) / 100); } else { pj_ansi_sprintf(buf, "%d.%02dM", val / 1000000, (val % 1000000) / 10000); } return buf; } static void print_avg_stat(void) { #define MIN_(var,val) if ((int)val < (int)var) var = val #define MAX_(var,val) if ((int)val > (int)var) var = val #define AVG_(var,val) var = ( ((var * count) + val) / (count+1) ) #define BIGVAL 0x7FFFFFFFL struct stat_entry { int min, avg, max; }; struct stat_entry call_dur, call_pdd; pjmedia_rtcp_stat min_stat, avg_stat, max_stat; char srx_min[16], srx_avg[16], srx_max[16]; char brx_min[16], brx_avg[16], brx_max[16]; char stx_min[16], stx_avg[16], stx_max[16]; char btx_min[16], btx_avg[16], btx_max[16]; unsigned i, count; pj_bzero(&call_dur, sizeof(call_dur)); call_dur.min = BIGVAL; pj_bzero(&call_pdd, sizeof(call_pdd)); call_pdd.min = BIGVAL; pj_bzero(&min_stat, sizeof(min_stat)); min_stat.rx.pkt = min_stat.tx.pkt = BIGVAL; min_stat.rx.bytes = min_stat.tx.bytes = BIGVAL; min_stat.rx.loss = min_stat.tx.loss = BIGVAL; min_stat.rx.dup = min_stat.tx.dup = BIGVAL; min_stat.rx.reorder = min_stat.tx.reorder = BIGVAL; min_stat.rx.jitter.min = min_stat.tx.jitter.min = BIGVAL; min_stat.rtt.min = BIGVAL; pj_bzero(&avg_stat, sizeof(avg_stat)); pj_bzero(&max_stat, sizeof(max_stat)); for (i=0, count=0; i<app.max_calls; ++i) { struct call *call = &app.call[i]; struct media_stream *audio = &call->media[0]; pj_time_val dur; unsigned msec_dur; if (call->inv == NULL || call->inv->state < PJSIP_INV_STATE_CONFIRMED || call->connect_time.sec == 0) { continue; } /* Duration */ call_get_duration(i, &dur); msec_dur = PJ_TIME_VAL_MSEC(dur); MIN_(call_dur.min, msec_dur); MAX_(call_dur.max, msec_dur); AVG_(call_dur.avg, msec_dur); /* Connect delay */ if (call->connect_time.sec) { pj_time_val t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); msec_dur = PJ_TIME_VAL_MSEC(t); } else { msec_dur = 10; } MIN_(call_pdd.min, msec_dur); MAX_(call_pdd.max, msec_dur); AVG_(call_pdd.avg, msec_dur); /* RX Statistisc: */ /* Packets */ MIN_(min_stat.rx.pkt, audio->rtcp.stat.rx.pkt); MAX_(max_stat.rx.pkt, audio->rtcp.stat.rx.pkt); AVG_(avg_stat.rx.pkt, audio->rtcp.stat.rx.pkt); /* Bytes */ MIN_(min_stat.rx.bytes, audio->rtcp.stat.rx.bytes); MAX_(max_stat.rx.bytes, audio->rtcp.stat.rx.bytes); AVG_(avg_stat.rx.bytes, audio->rtcp.stat.rx.bytes); /* Packet loss */ MIN_(min_stat.rx.loss, audio->rtcp.stat.rx.loss); MAX_(max_stat.rx.loss, audio->rtcp.stat.rx.loss); AVG_(avg_stat.rx.loss, audio->rtcp.stat.rx.loss); /* Packet dup */ MIN_(min_stat.rx.dup, audio->rtcp.stat.rx.dup); MAX_(max_stat.rx.dup, audio->rtcp.stat.rx.dup); AVG_(avg_stat.rx.dup, audio->rtcp.stat.rx.dup); /* Packet reorder */ MIN_(min_stat.rx.reorder, audio->rtcp.stat.rx.reorder); MAX_(max_stat.rx.reorder, audio->rtcp.stat.rx.reorder); AVG_(avg_stat.rx.reorder, audio->rtcp.stat.rx.reorder); /* Jitter */ MIN_(min_stat.rx.jitter.min, audio->rtcp.stat.rx.jitter.min); MAX_(max_stat.rx.jitter.max, audio->rtcp.stat.rx.jitter.max); AVG_(avg_stat.rx.jitter.mean, audio->rtcp.stat.rx.jitter.mean); /* TX Statistisc: */ /* Packets */ MIN_(min_stat.tx.pkt, audio->rtcp.stat.tx.pkt); MAX_(max_stat.tx.pkt, audio->rtcp.stat.tx.pkt); AVG_(avg_stat.tx.pkt, audio->rtcp.stat.tx.pkt); /* Bytes */ MIN_(min_stat.tx.bytes, audio->rtcp.stat.tx.bytes); MAX_(max_stat.tx.bytes, audio->rtcp.stat.tx.bytes); AVG_(avg_stat.tx.bytes, audio->rtcp.stat.tx.bytes); /* Packet loss */ MIN_(min_stat.tx.loss, audio->rtcp.stat.tx.loss); MAX_(max_stat.tx.loss, audio->rtcp.stat.tx.loss); AVG_(avg_stat.tx.loss, audio->rtcp.stat.tx.loss); /* Packet dup */ MIN_(min_stat.tx.dup, audio->rtcp.stat.tx.dup); MAX_(max_stat.tx.dup, audio->rtcp.stat.tx.dup); AVG_(avg_stat.tx.dup, audio->rtcp.stat.tx.dup); /* Packet reorder */ MIN_(min_stat.tx.reorder, audio->rtcp.stat.tx.reorder); MAX_(max_stat.tx.reorder, audio->rtcp.stat.tx.reorder); AVG_(avg_stat.tx.reorder, audio->rtcp.stat.tx.reorder); /* Jitter */ MIN_(min_stat.tx.jitter.min, audio->rtcp.stat.tx.jitter.min); MAX_(max_stat.tx.jitter.max, audio->rtcp.stat.tx.jitter.max); AVG_(avg_stat.tx.jitter.mean, audio->rtcp.stat.tx.jitter.mean); /* RTT */ MIN_(min_stat.rtt.min, audio->rtcp.stat.rtt.min); MAX_(max_stat.rtt.max, audio->rtcp.stat.rtt.max); AVG_(avg_stat.rtt.mean, audio->rtcp.stat.rtt.mean); ++count; } if (count == 0) { puts("No active calls"); return; } printf("Total %d call(s) active.\n" " Average Statistics\n" " min avg max \n" " -----------------------\n" " call duration: %7d %7d %7d %s\n" " connect delay: %7d %7d %7d %s\n" " RX stat:\n" " packets: %7s %7s %7s %s\n" " payload: %7s %7s %7s %s\n" " loss: %7d %7d %7d %s\n" " percent loss: %7.3f %7.3f %7.3f %s\n" " dup: %7d %7d %7d %s\n" " reorder: %7d %7d %7d %s\n" " jitter: %7.3f %7.3f %7.3f %s\n" " TX stat:\n" " packets: %7s %7s %7s %s\n" " payload: %7s %7s %7s %s\n" " loss: %7d %7d %7d %s\n" " percent loss: %7.3f %7.3f %7.3f %s\n" " dup: %7d %7d %7d %s\n" " reorder: %7d %7d %7d %s\n" " jitter: %7.3f %7.3f %7.3f %s\n" " RTT : %7.3f %7.3f %7.3f %s\n" , count, call_dur.min/1000, call_dur.avg/1000, call_dur.max/1000, "seconds", call_pdd.min, call_pdd.avg, call_pdd.max, "ms", /* rx */ good_number(srx_min, min_stat.rx.pkt), good_number(srx_avg, avg_stat.rx.pkt), good_number(srx_max, max_stat.rx.pkt), "packets", good_number(brx_min, min_stat.rx.bytes), good_number(brx_avg, avg_stat.rx.bytes), good_number(brx_max, max_stat.rx.bytes), "bytes", min_stat.rx.loss, avg_stat.rx.loss, max_stat.rx.loss, "packets", min_stat.rx.loss*100.0/(min_stat.rx.pkt+min_stat.rx.loss), avg_stat.rx.loss*100.0/(avg_stat.rx.pkt+avg_stat.rx.loss), max_stat.rx.loss*100.0/(max_stat.rx.pkt+max_stat.rx.loss), "%", min_stat.rx.dup, avg_stat.rx.dup, max_stat.rx.dup, "packets", min_stat.rx.reorder, avg_stat.rx.reorder, max_stat.rx.reorder, "packets", min_stat.rx.jitter.min/1000.0, avg_stat.rx.jitter.mean/1000.0, max_stat.rx.jitter.max/1000.0, "ms", /* tx */ good_number(stx_min, min_stat.tx.pkt), good_number(stx_avg, avg_stat.tx.pkt), good_number(stx_max, max_stat.tx.pkt), "packets", good_number(btx_min, min_stat.tx.bytes), good_number(btx_avg, avg_stat.tx.bytes), good_number(btx_max, max_stat.tx.bytes), "bytes", min_stat.tx.loss, avg_stat.tx.loss, max_stat.tx.loss, "packets", min_stat.tx.loss*100.0/(min_stat.tx.pkt+min_stat.tx.loss), avg_stat.tx.loss*100.0/(avg_stat.tx.pkt+avg_stat.tx.loss), max_stat.tx.loss*100.0/(max_stat.tx.pkt+max_stat.tx.loss), "%", min_stat.tx.dup, avg_stat.tx.dup, max_stat.tx.dup, "packets", min_stat.tx.reorder, avg_stat.tx.reorder, max_stat.tx.reorder, "packets", min_stat.tx.jitter.min/1000.0, avg_stat.tx.jitter.mean/1000.0, max_stat.tx.jitter.max/1000.0, "ms", /* rtt */ min_stat.rtt.min/1000.0, avg_stat.rtt.mean/1000.0, max_stat.rtt.max/1000.0, "ms" ); } /*Subbu BEGIN */ static void print_call(int call_index) { struct call *call = &app.call[call_index]; int len; pjsip_inv_session *inv = call->inv; pjsip_dialog *dlg = inv->dlg; struct media_stream *audio = &call->media[0]; char userinfo[128]; char duration[80], last_update[80]; char bps[16], ipbps[16], packets[16], bytes[16], ipbytes[16]; unsigned decor; pj_time_val now; decor = pj_log_get_decor(); pj_log_set_decor(PJ_LOG_HAS_NEWLINE); pj_gettimeofday(&now); if (app.report_filename) puts(app.report_filename); /* Print duration */ if (inv->state >= PJSIP_INV_STATE_CONFIRMED && call->connect_time.sec) { PJ_TIME_VAL_SUB(now, call->connect_time); sprintf(duration, " [duration: %02ld:%02ld:%02ld]", now.sec / 3600, (now.sec % 3600) / 60, (now.sec % 60) ); } else { duration[0] = '\0'; } /* Call number and state */ PJ_LOG(3, (THIS_FILE, "Call #%d: To Anpi Diagnostics %s%s", (call_index +1) , pjsip_inv_state_name(inv->state), duration)); /* Call identification */ len = pjsip_hdr_print_on(dlg->remote.info, userinfo, sizeof(userinfo)); if (len < 0) pj_ansi_strcpy(userinfo, "<--uri too long-->"); else userinfo[len] = '\0'; PJ_LOG(3, (THIS_FILE, " %s", userinfo)); if (call->inv == NULL || call->inv->state < PJSIP_INV_STATE_CONFIRMED || call->connect_time.sec == 0) { pj_log_set_decor(decor); return; } /* Signaling quality */ { char pdd[64], connectdelay[64]; pj_time_val t; if (call->response_time.sec) { t = call->response_time; PJ_TIME_VAL_SUB(t, call->start_time); sprintf(pdd, "got 1st response in %ld ms", PJ_TIME_VAL_MSEC(t)); } else { pdd[0] = '\0'; } if (call->connect_time.sec) { t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); sprintf(connectdelay, ", connected after: %ld ms", PJ_TIME_VAL_MSEC(t)); } else { connectdelay[0] = '\0'; } PJ_LOG(3, (THIS_FILE, " Signaling quality: %s%s", pdd, connectdelay)); } PJ_LOG(3, (THIS_FILE, " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)", (int)audio->si.fmt.encoding_name.slen, audio->si.fmt.encoding_name.ptr, audio->clock_rate, audio->samples_per_frame * 1000 / audio->clock_rate, good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame))); if (audio->rtcp.stat.rx.update_cnt == 0) strcpy(last_update, "never"); else { pj_gettimeofday(&now); PJ_TIME_VAL_SUB(now, audio->rtcp.stat.rx.update); sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", now.sec / 3600, (now.sec % 3600) / 60, now.sec % 60, now.msec); } PJ_LOG(3, (THIS_FILE, " RX stat last update: %s\n" " total %s packets %sB received (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.rx.pkt), good_number(bytes, audio->rtcp.stat.rx.bytes), good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), "", audio->rtcp.stat.rx.loss, audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.dup, audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.reorder, audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), "", audio->rtcp.stat.rx.loss_period.min / 1000.0, audio->rtcp.stat.rx.loss_period.mean / 1000.0, audio->rtcp.stat.rx.loss_period.max / 1000.0, audio->rtcp.stat.rx.loss_period.last / 1000.0, "", audio->rtcp.stat.rx.jitter.min / 1000.0, audio->rtcp.stat.rx.jitter.mean / 1000.0, audio->rtcp.stat.rx.jitter.max / 1000.0, audio->rtcp.stat.rx.jitter.last / 1000.0, "" )); if (audio->rtcp.stat.tx.update_cnt == 0) strcpy(last_update, "never"); else { pj_gettimeofday(&now); PJ_TIME_VAL_SUB(now, audio->rtcp.stat.tx.update); sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", now.sec / 3600, (now.sec % 3600) / 60, now.sec % 60, now.msec); } PJ_LOG(3, (THIS_FILE, " TX stat last update: %s\n" " total %s packets %sB sent (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.tx.pkt), good_number(bytes, audio->rtcp.stat.tx.bytes), good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), "", audio->rtcp.stat.tx.loss, audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.dup, audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.reorder, audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), "", audio->rtcp.stat.tx.loss_period.min / 1000.0, audio->rtcp.stat.tx.loss_period.mean / 1000.0, audio->rtcp.stat.tx.loss_period.max / 1000.0, audio->rtcp.stat.tx.loss_period.last / 1000.0, "", audio->rtcp.stat.tx.jitter.min / 1000.0, audio->rtcp.stat.tx.jitter.mean / 1000.0, audio->rtcp.stat.tx.jitter.max / 1000.0, audio->rtcp.stat.tx.jitter.last / 1000.0, "" )); PJ_LOG(3, (THIS_FILE, " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", audio->rtcp.stat.rtt.min / 1000.0, audio->rtcp.stat.rtt.mean / 1000.0, audio->rtcp.stat.rtt.max / 1000.0, audio->rtcp.stat.rtt.last / 1000.0, "" )); pj_log_set_decor(decor); } /* Subu END */ /* #include "siprtp_report.c" /* excluded by Subbu */ static void list_calls() { unsigned i; puts("List all calls:"); for (i=0; i<app.max_calls; ++i) { if (!app.call[i].inv) continue; DLL_call_log(i); } } static void hangup_call(unsigned index) { pjsip_tx_data *tdata; pj_status_t status; if (app.call[index].inv == NULL) return; status = pjsip_inv_end_session(app.call[index].inv, 603, NULL, &tdata); if (status==PJ_SUCCESS && tdata!=NULL) pjsip_inv_send_msg(app.call[index].inv, tdata); } static void hangup_all_calls() { unsigned i; for (i=0; i<app.max_calls; ++i) { if (!app.call[i].inv) continue; hangup_call(i); pj_thread_sleep(app.call_gap); } /* Wait until all calls are terminated */ for (i=0; i<app.max_calls; ++i) { while (app.call[i].inv) pj_thread_sleep(10); } } static pj_bool_t simple_input(const char *title, char *buf, pj_size_t len) { char *p; printf("%s (empty to cancel): ", title); fflush(stdout); if (fgets(buf, len, stdin) == NULL) return PJ_FALSE; /* Remove trailing newlines. */ for (p=buf; ; ++p) { if (*p=='\r' || *p=='\n') *p='\0'; else if (!*p) break; } if (!*buf) return PJ_FALSE; return PJ_TRUE; } static const char *MENU = "\n" "Enter menu character:\n" " s Summary\n" " l List all calls\n" " h Hangup a call\n" " H Hangup all calls\n" " q Quit\n" "\n"; /* Main screen menu */ static void console_main() { char input1[10]; unsigned i; int index; bool program_end = false; printf("%s", MENU); for (;;) { for(index = 0; index < app.max_calls; index++) if (app.call[index].inv != NULL) program_end = false; else program_end = true; if(program_end) return; printf(">>> "); fflush(stdout); if (fgets(input1, sizeof(input1), stdin) == NULL) { puts("EOF while reading stdin, will quit now.."); break; } switch (input1[0]) { case 's': print_avg_stat(); break; case 'l': list_calls(); break; case 'h': if (!simple_input("Call number to hangup", input1, sizeof(input1))) break; i = atoi(input1); hangup_call(i-1); break; case 'H': hangup_all_calls(); break; case 'q': goto on_exit; default: puts("Invalid command"); printf("%s", MENU); break; } fflush(stdout); } on_exit: hangup_all_calls(); } /***************************************************************************** * Below is a simple module to log all incoming and outgoing SIP messages */ /* Notification on incoming messages */ static pj_bool_t logger_on_rx_msg(pjsip_rx_data *rdata) { PJ_LOG(4,(THIS_FILE, "RX %d bytes %s from %s:%d:\n" "%s\n" "--end msg--", rdata->msg_info.len, pjsip_rx_data_get_info(rdata), rdata->pkt_info.src_name, rdata->pkt_info.src_port, rdata->msg_info.msg_buf)); /* Always return false, otherwise messages will not get processed! */ return PJ_FALSE; } /* Notification on outgoing messages */ static pj_status_t logger_on_tx_msg(pjsip_tx_data *tdata) { /* Important note: * tp_info field is only valid after outgoing messages has passed * transport layer. So don't try to access tp_info when the module * has lower priority than transport layer. */ PJ_LOG(4,(THIS_FILE, "TX %d bytes %s to %s:%d:\n" "%s\n" "--end msg--", (tdata->buf.cur - tdata->buf.start), pjsip_tx_data_get_info(tdata), tdata->tp_info.dst_name, tdata->tp_info.dst_port, tdata->buf.start)); /* Always return success, otherwise message will not get sent! */ return PJ_SUCCESS; } /* The module instance. */ static pjsip_module msg_logger = { NULL, NULL, /* prev, next. */ { "mod-siprtp-log", 14 }, /* Name. */ -1, /* Id */ PJSIP_MOD_PRIORITY_TRANSPORT_LAYER-1,/* Priority */ NULL, /* load() */ NULL, /* start() */ NULL, /* stop() */ NULL, /* unload() */ &logger_on_rx_msg, /* on_rx_request() */ &logger_on_rx_msg, /* on_rx_response() */ &logger_on_tx_msg, /* on_tx_request. */ &logger_on_tx_msg, /* on_tx_response() */ NULL, /* on_tsx_state() */ }; /***************************************************************************** * Console application custom logging: */ static FILE *log_file; static void app_log_writer(int level, const char *buffer, int len) { /* Write to both stdout and file. */ if (level <= app.app_log_level) pj_log_write(level, buffer, len); if (log_file) { int count = fwrite(buffer, len, 1, log_file); PJ_UNUSED_ARG(count); fflush(log_file); } } pj_status_t app_logging_init(void) { /* Redirect log function to ours */ pj_log_set_log_func( &app_log_writer ); /* If output log file is desired, create the file: */ if (app.log_filename) { log_file = fopen(app.log_filename, "wt"); if (log_file == NULL) { PJ_LOG(1,(THIS_FILE, "Unable to open log file %s", app.log_filename)); return -1; } } return PJ_SUCCESS; } void app_logging_shutdown(void) { /* Close logging file, if any: */ if (log_file) { fclose(log_file); log_file = NULL; } } #define INVALID -1 #define VALID 0 int validateIP(char *ipadd) { unsigned b1, b2, b3, b4; unsigned char c; if (sscanf(ipadd, "%3u.%3u.%3u.%3u%c", &b1, &b2, &b3, &b4, &c) != 4) return INVALID; if ((b1 | b2 | b3 | b4) > 255) return INVALID; if (strspn(ipadd, "0123456789.") < strlen(ipadd)) return INVALID; return VALID; } /***** Anpi Diagnostic Tool Main ******/ char *Using = "\n Error: Invalid arguments" "\n Usage: AnpiTalk [User ID] [Service IP Address] [Calls] [Duration]" "\n Example: AnpiTalk anpiuser 10.12.105.130 2 10 \n"; int anpi_tool(int argc, char *argv[]) { unsigned i; pj_status_t status; char anpi_uri[150]; char *calls = "-c"; char *duration = "-d"; char *argvs[6]; /* Must init PJLIB first */ status = pj_init(); if (status != PJ_SUCCESS) return 1; /* if (argc !=5 ){ puts(Using); return -1; } */ if( strlen(argv[1]) > 100 || strlen (argv[1]) < 5) { puts("Error: User_ID should be atleast 5 character length and less than 100 characters"); puts(Using); return -1; } if (validateIP(argv[2]) != VALID){ puts(Using); return -1; } if ( atoi(argv[3]) > 5 || atoi(argv[3]) < 1){ puts("Error: Number of calls should not exceed 5 and at least 1"); puts(Using); return -1; } strcpy(anpi_uri, "sip:Anpi_Diagnosis@"); strcat(anpi_uri, argv[2]); if (!isdigit(argv[3][0])) printf(Using); argvs[0] = argv[0]; argvs[1] = anpi_uri; argvs[2] = calls; argvs[3] = argv[3]; argvs[4] = duration; // -d (duration in seconds) argvs[5] = argv[4]; if(atoi(argv[4]) <= 0) argc = 4; else argc = 6; printf(" %s %s, %s, %s ", argv[0], argvs[1], argvs[2], argvs[3]); /* Get command line options */ status = init_options(argc, argvs, argv[1]); if (status != PJ_SUCCESS) return 1; /* Verify options: */ /* Auto-quit can not be specified for UAS */ if (app.auto_quit && app.uri_to_call.slen == 0) { printf("Error: --auto-quit option only valid for outgoing " "mode (UAC) only\n"); return 1; } /* Init logging */ status = app_logging_init(); if (status != PJ_SUCCESS) return 1; /* Init SIP etc */ status = init_sip(); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Initialization has failed", status); destroy_sip(); return 1; } /* Register module to log incoming/outgoing messages */ pjsip_endpt_register_module(app.sip_endpt, &msg_logger); /* Init media */ status = init_media(); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Media initialization failed", status); destroy_sip(); return 1; } /* Start worker threads */ #if PJ_HAS_THREADS for (i=0; i<app.thread_count; ++i) { pj_thread_create( app.pool, "app", &sip_worker_thread, NULL, 0, 0, &app.sip_thread[i]); } #endif /* If URL is specified, then make call immediately */ if (app.uri_to_call.slen) { unsigned i; PJ_LOG(3,(THIS_FILE, "Making %d calls to %s..", app.max_calls, app.uri_to_call.ptr)); for (i=0; i<app.max_calls; ++i) { status = make_call(&app.uri_to_call); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Error making call", status); break; } pj_thread_sleep(app.call_gap); } if (app.auto_quit) { /* Wait for calls to complete */ while (app.uac_calls < app.max_calls) pj_thread_sleep(100); pj_thread_sleep(200); } else { #if PJ_HAS_THREADS /* Start user interface loop */ console_main(); #endif } } else { PJ_LOG(3,(THIS_FILE, "Ready for incoming calls (max=%d)", app.max_calls)); #if PJ_HAS_THREADS /* Start user interface loop */ console_main(); #endif } #if !PJ_HAS_THREADS PJ_LOG(3,(THIS_FILE, "Press Ctrl-C to quit")); for (;;) { pj_time_val t = {0, 10}; pjsip_endpt_handle_events(app.sip_endpt, &t); } #endif /* Shutting down... */ destroy_sip(); destroy_media(); if (app.pool) { pj_pool_release(app.pool); app.pool = NULL; pj_caching_pool_destroy(&app.cp); } app_logging_shutdown(); /* Shutdown PJLIB */ pj_shutdown(); return 0; } #include <time.h> /******** Subbu **************/ static void print_call_log(int call_index) { struct call *call = &app.call[call_index]; int len; pjsip_inv_session *inv = call->inv; pjsip_dialog *dlg = inv->dlg; struct media_stream *audio = &call->media[0]; char userinfo[128]; char duration[80], last_update[80]; char bps[16], ipbps[16], packets[16], bytes[16], ipbytes[16]; unsigned decor; pj_time_val now; // char *P1, *P2; // char user_id[256]; // int index; FILE *dlog; time_t timer; char buffer[25]; struct tm* tm_info; pj_time_val t; decor = pj_log_get_decor(); pj_log_set_decor(PJ_LOG_HAS_NEWLINE); pj_gettimeofday(&now); if (app.report_filename) puts(app.report_filename); /* Print duration */ if (inv->state >= PJSIP_INV_STATE_CONFIRMED && call->connect_time.sec) { PJ_TIME_VAL_SUB(now, call->connect_time); sprintf(duration, " [duration: %02ld:%02ld:%02ld.%03ld]", now.sec / 3600, (now.sec % 3600) / 60, (now.sec % 60), now.msec); } else { duration[0] = '\0'; } /* Call number and state */ PJ_LOG(3, (THIS_FILE, "Call #%d: %s%s", call_index, pjsip_inv_state_name(inv->state), duration)); #if 0 /* Begin on ALG subbu */ PJ_LOG(3, (THIS_FILE, "Call #%d: %s%s", call_index, pjsip_inv_state_name(inv->state), duration)); // inv->invite_req->msg->body->data; /* End on ALG subbu */ #endif /* Call identification */ len = pjsip_hdr_print_on(dlg->remote.info, userinfo, sizeof(userinfo)); if (len < 0) pj_ansi_strcpy(userinfo, "<--uri too long-->"); else userinfo[len] = '\0'; PJ_LOG(3, (THIS_FILE, " %s", userinfo)); if (call->inv == NULL || call->inv->state < PJSIP_INV_STATE_CONFIRMED || call->connect_time.sec == 0) { pj_log_set_decor(decor); return; } /* Subbu Begin */ /* P1= strstr(userinfo, "sip:"); if (P1) P2 = strstr(userinfo, "@"); if (P1 && P2){ P1 +=4; for(index = 0; (P1+index) < P2 && index < 256; index++) user_id[index] = P1[index]; user_id[index] = '\0'; strcat(user_id, ".log"); printf("\n********** file name is %s**", user_id); dlog = fopen(user_id, "a"); if (dlog){ fprintf(dlog, "%s\n", userinfo); } } /* Subbu End */ /* Signaling quality */ { char pdd[64], connectdelay[64]; pj_time_val t; if (call->response_time.sec) { t = call->response_time; PJ_TIME_VAL_SUB(t, call->start_time); sprintf(pdd, "got 1st response in %ld ms", PJ_TIME_VAL_MSEC(t)); } else { pdd[0] = '\0'; } if (call->connect_time.sec) { t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); sprintf(connectdelay, ", connected after: %ld ms", PJ_TIME_VAL_MSEC(t)); } else { connectdelay[0] = '\0'; } PJ_LOG(3, (THIS_FILE, " Signaling quality: %s%s", pdd, connectdelay)); } PJ_LOG(3, (THIS_FILE, " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)", (int)audio->si.fmt.encoding_name.slen, audio->si.fmt.encoding_name.ptr, audio->clock_rate, audio->samples_per_frame * 1000 / audio->clock_rate, good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame))); if (audio->rtcp.stat.rx.update_cnt == 0) strcpy(last_update, "never"); else { pj_gettimeofday(&now); PJ_TIME_VAL_SUB(now, audio->rtcp.stat.rx.update); sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", now.sec / 3600, (now.sec % 3600) / 60, now.sec % 60, now.msec); } if(dlog) fprintf(dlog, " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)\n", (int)audio->si.fmt.encoding_name.slen, audio->si.fmt.encoding_name.ptr, audio->clock_rate, audio->samples_per_frame * 1000 / audio->clock_rate, good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame)); PJ_LOG(3, (THIS_FILE, " RX stat last update: %s\n" " total %s packets %sB received (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.rx.pkt), good_number(bytes, audio->rtcp.stat.rx.bytes), good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), "", audio->rtcp.stat.rx.loss, audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.dup, audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.reorder, audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), "", audio->rtcp.stat.rx.loss_period.min / 1000.0, audio->rtcp.stat.rx.loss_period.mean / 1000.0, audio->rtcp.stat.rx.loss_period.max / 1000.0, audio->rtcp.stat.rx.loss_period.last / 1000.0, "", audio->rtcp.stat.rx.jitter.min / 1000.0, audio->rtcp.stat.rx.jitter.mean / 1000.0, audio->rtcp.stat.rx.jitter.max / 1000.0, audio->rtcp.stat.rx.jitter.last / 1000.0, "" )); if(dlog) fprintf(dlog, " RX stat last update: %s\n" " total %s packets %sB received (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s\n", last_update, good_number(packets, audio->rtcp.stat.rx.pkt), good_number(bytes, audio->rtcp.stat.rx.bytes), good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), "", audio->rtcp.stat.rx.loss, audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.dup, audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.reorder, audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), "", audio->rtcp.stat.rx.loss_period.min / 1000.0, audio->rtcp.stat.rx.loss_period.mean / 1000.0, audio->rtcp.stat.rx.loss_period.max / 1000.0, audio->rtcp.stat.rx.loss_period.last / 1000.0, "", audio->rtcp.stat.rx.jitter.min / 1000.0, audio->rtcp.stat.rx.jitter.mean / 1000.0, audio->rtcp.stat.rx.jitter.max / 1000.0, audio->rtcp.stat.rx.jitter.last / 1000.0, "" ); if (audio->rtcp.stat.tx.update_cnt == 0) strcpy(last_update, "never"); else { pj_gettimeofday(&now); PJ_TIME_VAL_SUB(now, audio->rtcp.stat.tx.update); sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", now.sec / 3600, (now.sec % 3600) / 60, now.sec % 60, now.msec); } PJ_LOG(3, (THIS_FILE, " TX stat last update: %s\n" " total %s packets %sB sent (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.tx.pkt), good_number(bytes, audio->rtcp.stat.tx.bytes), good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), "", audio->rtcp.stat.tx.loss, audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.dup, audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.reorder, audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), "", audio->rtcp.stat.tx.loss_period.min / 1000.0, audio->rtcp.stat.tx.loss_period.mean / 1000.0, audio->rtcp.stat.tx.loss_period.max / 1000.0, audio->rtcp.stat.tx.loss_period.last / 1000.0, "", audio->rtcp.stat.tx.jitter.min / 1000.0, audio->rtcp.stat.tx.jitter.mean / 1000.0, audio->rtcp.stat.tx.jitter.max / 1000.0, audio->rtcp.stat.tx.jitter.last / 1000.0, "" )); if(dlog) fprintf(dlog, " TX stat last update: %s\n" " total %s packets %sB sent (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s\n", last_update, good_number(packets, audio->rtcp.stat.tx.pkt), good_number(bytes, audio->rtcp.stat.tx.bytes), good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), "", audio->rtcp.stat.tx.loss, audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.dup, audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.reorder, audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), "", audio->rtcp.stat.tx.loss_period.min / 1000.0, audio->rtcp.stat.tx.loss_period.mean / 1000.0, audio->rtcp.stat.tx.loss_period.max / 1000.0, audio->rtcp.stat.tx.loss_period.last / 1000.0, "", audio->rtcp.stat.tx.jitter.min / 1000.0, audio->rtcp.stat.tx.jitter.mean / 1000.0, audio->rtcp.stat.tx.jitter.max / 1000.0, audio->rtcp.stat.tx.jitter.last / 1000.0, "" ); PJ_LOG(3, (THIS_FILE, " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", audio->rtcp.stat.rtt.min / 1000.0, audio->rtcp.stat.rtt.mean / 1000.0, audio->rtcp.stat.rtt.max / 1000.0, audio->rtcp.stat.rtt.last / 1000.0, "" )); if(dlog){ fprintf(dlog, " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", audio->rtcp.stat.rtt.min / 1000.0, audio->rtcp.stat.rtt.mean / 1000.0, audio->rtcp.stat.rtt.max / 1000.0, audio->rtcp.stat.rtt.last / 1000.0, "" ); fprintf(dlog, " Call Duration : %s\n ", duration); time(&timer); tm_info = localtime(&timer); strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info); fprintf(dlog, " Date & Time : %s\n",buffer); t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); fprintf(dlog, " Connected in : %d ms\n", PJ_TIME_VAL_MSEC(t) ); } if(dlog) fclose(dlog); pj_log_set_decor(decor); } #define DLLSTORE 1 static char *DLL_call_log(int call_index) { struct call *call = &app.call[call_index]; int len; pjsip_inv_session *inv = call->inv; pjsip_dialog *dlg = inv->dlg; struct media_stream *audio = &call->media[0]; char userinfo[128]; char duration[80], last_update[80]; char bps[16], ipbps[16], packets[16], bytes[16], ipbytes[16]; unsigned decor; pj_time_val now; // char *P1, *P2; // char user_id[256]; // int index; char *logstore = (char *) malloc(4096); char *logstoredll = (char *) malloc(4096); FILE *dlog; time_t timer; char buffer[25]; struct tm* tm_info; pj_time_val t; decor = pj_log_get_decor(); pj_log_set_decor(PJ_LOG_HAS_NEWLINE); pj_gettimeofday(&now); if (app.report_filename) puts(app.report_filename); /* Print duration */ if (inv->state >= PJSIP_INV_STATE_CONFIRMED && call->connect_time.sec) { PJ_TIME_VAL_SUB(now, call->connect_time); sprintf(duration, " [duration: %02ld:%02ld:%02ld.%03ld]", now.sec / 3600, (now.sec % 3600) / 60, (now.sec % 60), now.msec); } else { duration[0] = '\0'; } #if DLLSTORE sprintf(ToolData.call, "\n" THIS_FILE "Call #%d: %s%s", call_index, pjsip_inv_state_name(inv->state), duration); strcat(ToolData.call, logstore); #else /* Call number and state */ PJ_LOG(3, (THIS_FILE, "Call #%d: %s%s", call_index, pjsip_inv_state_name(inv->state), duration)); #endif #if 0 /* Begin on ALG subbu */ PJ_LOG(3, (THIS_FILE, "Call #%d: %s%s", call_index, pjsip_inv_state_name(inv->state), duration)); // inv->invite_req->msg->body->data; /* End on ALG subbu */ #endif /* Call identification */ len = pjsip_hdr_print_on(dlg->remote.info, userinfo, sizeof(userinfo)); if (len < 0) pj_ansi_strcpy(userinfo, "<--uri too long-->"); else userinfo[len] = '\0'; #if DLLSTORE sprintf(ToolData.call, "\n"THIS_FILE, " %s", userinfo); strcat(ToolData.call, logstore); #else PJ_LOG(3, (THIS_FILE, " %s", userinfo)); #endif if (call->inv == NULL || call->inv->state < PJSIP_INV_STATE_CONFIRMED || call->connect_time.sec == 0) { pj_log_set_decor(decor); return NULL; } /* Subbu Begin */ /* P1= strstr(userinfo, "sip:"); if (P1) P2 = strstr(userinfo, "@"); if (P1 && P2){ P1 +=4; for(index = 0; (P1+index) < P2 && index < 256; index++) user_id[index] = P1[index]; user_id[index] = '\0'; strcat(user_id, ".log"); printf("\n********** file name is %s**", user_id); dlog = fopen(user_id, "a"); if (dlog){ fprintf(dlog, "%s\n", userinfo); } } /* Subbu End */ /* Signaling quality */ { char pdd[64], connectdelay[64]; pj_time_val t; if (call->response_time.sec) { t = call->response_time; PJ_TIME_VAL_SUB(t, call->start_time); sprintf(pdd, "got 1st response in %ld ms", PJ_TIME_VAL_MSEC(t)); } else { pdd[0] = '\0'; } if (call->connect_time.sec) { t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); sprintf(connectdelay, ", connected after: %ld ms", PJ_TIME_VAL_MSEC(t)); } else { connectdelay[0] = '\0'; } #if DLLSTORE sprintf(logstore, THIS_FILE " Signaling quality: %s%s", pdd, connectdelay); strcat(logstoredll, logstore); } #else PJ_LOG(3, (THIS_FILE, " Signaling quality: %s%s", pdd, connectdelay)); } #endif #if DLLSTORE sprintf(ToolData.call, "\n"THIS_FILE " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)", (int)audio->si.fmt.encoding_name.slen, audio->si.fmt.encoding_name.ptr, audio->clock_rate, audio->samples_per_frame * 1000 / audio->clock_rate, good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame)); strcat(ToolData.call, logstore); #else PJ_LOG(3, (THIS_FILE, " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)", (int)audio->si.fmt.encoding_name.slen, audio->si.fmt.encoding_name.ptr, audio->clock_rate, audio->samples_per_frame * 1000 / audio->clock_rate, good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame))); #endif if (audio->rtcp.stat.rx.update_cnt == 0) strcpy(last_update, "never"); else { pj_gettimeofday(&now); PJ_TIME_VAL_SUB(now, audio->rtcp.stat.rx.update); sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", now.sec / 3600, (now.sec % 3600) / 60, now.sec % 60, now.msec); } dlog = NULL; if(dlog) fprintf(dlog, " Stream #0: audio %.*s@%dHz, %dms/frame, %sB/s (%sB/s +IP hdr)\n", (int)audio->si.fmt.encoding_name.slen, audio->si.fmt.encoding_name.ptr, audio->clock_rate, audio->samples_per_frame * 1000 / audio->clock_rate, good_number(bps, audio->bytes_per_frame * audio->clock_rate / audio->samples_per_frame), good_number(ipbps, (audio->bytes_per_frame+32) * audio->clock_rate / audio->samples_per_frame)); #if DLLSTORE sprintf(ToolData.call, "\n"THIS_FILE " RX stat last update: %s\n" " total %s packets %sB received (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.rx.pkt), good_number(bytes, audio->rtcp.stat.rx.bytes), good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), "", audio->rtcp.stat.rx.loss, audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.dup, audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.reorder, audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), "", audio->rtcp.stat.rx.loss_period.min / 1000.0, audio->rtcp.stat.rx.loss_period.mean / 1000.0, audio->rtcp.stat.rx.loss_period.max / 1000.0, audio->rtcp.stat.rx.loss_period.last / 1000.0, "", audio->rtcp.stat.rx.jitter.min / 1000.0, audio->rtcp.stat.rx.jitter.mean / 1000.0, audio->rtcp.stat.rx.jitter.max / 1000.0, audio->rtcp.stat.rx.jitter.last / 1000.0, "" ); strcat(ToolData.call, logstore); #else PJ_LOG(3, (THIS_FILE, " RX stat last update: %s\n" " total %s packets %sB received (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.rx.pkt), good_number(bytes, audio->rtcp.stat.rx.bytes), good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), "", audio->rtcp.stat.rx.loss, audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.dup, audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.reorder, audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), "", audio->rtcp.stat.rx.loss_period.min / 1000.0, audio->rtcp.stat.rx.loss_period.mean / 1000.0, audio->rtcp.stat.rx.loss_period.max / 1000.0, audio->rtcp.stat.rx.loss_period.last / 1000.0, "", audio->rtcp.stat.rx.jitter.min / 1000.0, audio->rtcp.stat.rx.jitter.mean / 1000.0, audio->rtcp.stat.rx.jitter.max / 1000.0, audio->rtcp.stat.rx.jitter.last / 1000.0, "" )); #endif if(dlog) fprintf(dlog, " RX stat last update: %s\n" " total %s packets %sB received (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s\n", last_update, good_number(packets, audio->rtcp.stat.rx.pkt), good_number(bytes, audio->rtcp.stat.rx.bytes), good_number(ipbytes, audio->rtcp.stat.rx.bytes + audio->rtcp.stat.rx.pkt * 32), "", audio->rtcp.stat.rx.loss, audio->rtcp.stat.rx.loss * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.dup, audio->rtcp.stat.rx.dup * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), audio->rtcp.stat.rx.reorder, audio->rtcp.stat.rx.reorder * 100.0 / (audio->rtcp.stat.rx.pkt + audio->rtcp.stat.rx.loss), "", audio->rtcp.stat.rx.loss_period.min / 1000.0, audio->rtcp.stat.rx.loss_period.mean / 1000.0, audio->rtcp.stat.rx.loss_period.max / 1000.0, audio->rtcp.stat.rx.loss_period.last / 1000.0, "", audio->rtcp.stat.rx.jitter.min / 1000.0, audio->rtcp.stat.rx.jitter.mean / 1000.0, audio->rtcp.stat.rx.jitter.max / 1000.0, audio->rtcp.stat.rx.jitter.last / 1000.0, "" ); if (audio->rtcp.stat.tx.update_cnt == 0) strcpy(last_update, "never"); else { pj_gettimeofday(&now); PJ_TIME_VAL_SUB(now, audio->rtcp.stat.tx.update); sprintf(last_update, "%02ldh:%02ldm:%02ld.%03lds ago", now.sec / 3600, (now.sec % 3600) / 60, now.sec % 60, now.msec); } #if DLLSTORE sprintf(ToolData.call, "\n"THIS_FILE " TX stat last update: %s\n" " total %s packets %sB sent (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.tx.pkt), good_number(bytes, audio->rtcp.stat.tx.bytes), good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), "", audio->rtcp.stat.tx.loss, audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.dup, audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.reorder, audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), "", audio->rtcp.stat.tx.loss_period.min / 1000.0, audio->rtcp.stat.tx.loss_period.mean / 1000.0, audio->rtcp.stat.tx.loss_period.max / 1000.0, audio->rtcp.stat.tx.loss_period.last / 1000.0, "", audio->rtcp.stat.tx.jitter.min / 1000.0, audio->rtcp.stat.tx.jitter.mean / 1000.0, audio->rtcp.stat.tx.jitter.max / 1000.0, audio->rtcp.stat.tx.jitter.last / 1000.0, "" ); strcat(ToolData.call, logstore); #else PJ_LOG(3, (THIS_FILE, " TX stat last update: %s\n" " total %s packets %sB sent (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s", last_update, good_number(packets, audio->rtcp.stat.tx.pkt), good_number(bytes, audio->rtcp.stat.tx.bytes), good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), "", audio->rtcp.stat.tx.loss, audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.dup, audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.reorder, audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), "", audio->rtcp.stat.tx.loss_period.min / 1000.0, audio->rtcp.stat.tx.loss_period.mean / 1000.0, audio->rtcp.stat.tx.loss_period.max / 1000.0, audio->rtcp.stat.tx.loss_period.last / 1000.0, "", audio->rtcp.stat.tx.jitter.min / 1000.0, audio->rtcp.stat.tx.jitter.mean / 1000.0, audio->rtcp.stat.tx.jitter.max / 1000.0, audio->rtcp.stat.tx.jitter.last / 1000.0, "" )); #endif if(dlog) fprintf(dlog, " TX stat last update: %s\n" " total %s packets %sB sent (%sB +IP hdr)%s\n" " pkt loss=%d (%3.1f%%), dup=%d (%3.1f%%), reorder=%d (%3.1f%%)%s\n" " (msec) min avg max last\n" " loss period: %7.3f %7.3f %7.3f %7.3f%s\n" " jitter : %7.3f %7.3f %7.3f %7.3f%s\n", last_update, good_number(packets, audio->rtcp.stat.tx.pkt), good_number(bytes, audio->rtcp.stat.tx.bytes), good_number(ipbytes, audio->rtcp.stat.tx.bytes + audio->rtcp.stat.tx.pkt * 32), "", audio->rtcp.stat.tx.loss, audio->rtcp.stat.tx.loss * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.dup, audio->rtcp.stat.tx.dup * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), audio->rtcp.stat.tx.reorder, audio->rtcp.stat.tx.reorder * 100.0 / (audio->rtcp.stat.tx.pkt + audio->rtcp.stat.tx.loss), "", audio->rtcp.stat.tx.loss_period.min / 1000.0, audio->rtcp.stat.tx.loss_period.mean / 1000.0, audio->rtcp.stat.tx.loss_period.max / 1000.0, audio->rtcp.stat.tx.loss_period.last / 1000.0, "", audio->rtcp.stat.tx.jitter.min / 1000.0, audio->rtcp.stat.tx.jitter.mean / 1000.0, audio->rtcp.stat.tx.jitter.max / 1000.0, audio->rtcp.stat.tx.jitter.last / 1000.0, "" ); #if DLLSTORE sprintf(ToolData.call, "\n"THIS_FILE, " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", audio->rtcp.stat.rtt.min / 1000.0, audio->rtcp.stat.rtt.mean / 1000.0, audio->rtcp.stat.rtt.max / 1000.0, audio->rtcp.stat.rtt.last / 1000.0, "" ); strcat(ToolData.call, logstore); #else PJ_LOG(3, (THIS_FILE, " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", audio->rtcp.stat.rtt.min / 1000.0, audio->rtcp.stat.rtt.mean / 1000.0, audio->rtcp.stat.rtt.max / 1000.0, audio->rtcp.stat.rtt.last / 1000.0, "" )); #endif if(dlog){ fprintf(dlog, " RTT delay : %7.3f %7.3f %7.3f %7.3f%s\n", audio->rtcp.stat.rtt.min / 1000.0, audio->rtcp.stat.rtt.mean / 1000.0, audio->rtcp.stat.rtt.max / 1000.0, audio->rtcp.stat.rtt.last / 1000.0, "" ); fprintf(dlog, " Call Duration : %s\n ", duration); time(&timer); tm_info = localtime(&timer); strftime(buffer, 25, "%Y:%m:%d %H:%M:%S", tm_info); fprintf(dlog, " Date & Time : %s\n",buffer); t = call->connect_time; PJ_TIME_VAL_SUB(t, call->start_time); fprintf(dlog, " Connected in : %d ms\n", PJ_TIME_VAL_MSEC(t) ); } if(dlog) fclose(dlog); pj_log_set_decor(decor); printf(" <NAME>, <NAME>\n %s", logstoredll); return (char * ) NULL; } } /* extern C */
81f697a055c902cf242e5a5bddb2e1e9d7b22e57
[ "C", "C++" ]
2
C
dongdong-2009/ASip
6d0caeac14951121357971f54a78863062481218
59494ee9d68227137c01fac5d57cc4d797069396
refs/heads/master
<repo_name>dewhisna/m6811dis<file_sep>/programs/m6811dis/memclass.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* MEMCLASS This is the C++ object definition for a Memory Object. The Memory object is an object that encompasses the whole of defined memory to be used for file conversions, disassemblers, etc. Author: <NAME> Date: January 28, 1997 Written in: Borland C++ 4.52 Updated: June 22, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. Updated: July 21, 1997 to expand TMemRange function base. Description: Each memory object represents the entire memory being acted upon, and typically, only one memory object needs to be created for an application. The memory is divided into pages (for paged memory applications) and each page has a descriptor byte that the application can use for processing -- useful for things such as "is_loaded", "is_data", "is_code", etc. Note: All Addresses and All Block Numbers are ZERO ORIGINATED! Size numbers (such as NBlocks and BlockSize) are ONE ORIGINATED! */ #include "memclass.h" #include "errmsgs.h" #ifndef NULL #define NULL 0 #endif // The following are the function declarations for TMemRange // TMemRange -- Constructor // The following constructs a TMemRange object by setting the StartAddr and // Size, and nullifying the next pointer. TMemRange::TMemRange(unsigned long aStartAddr, unsigned long aSize, unsigned long aUserData) { StartAddr = aStartAddr; Size = aSize; UserData = aUserData; Next=NULL; } // TMemRange -- Duplicating Constructor // This function is sorta like 'strdup'. It creates a new MemRange object // and copies itself to it and then calls itself recursively to duplicate // the objects linked with the Next pointer. // Supports: ERR_OUT_OF_MEMORY throwback TMemRange::TMemRange(TMemRange& aRange) { StartAddr=aRange.StartAddr; Size=aRange.Size; UserData=aRange.UserData; Next=NULL; try { if (aRange.Next!=NULL) { Next=new TMemRange(*aRange.Next); if (Next==NULL) THROW_MEMORY_EXCEPTION_ERROR(0); } } catch (EXCEPTION_ERROR*) { PurgeRange(); throw; } } // TMemRange -- Destructor // The following destructs a TMemRange object by checking to see if Next // points to a valid pointer to a linked list of MemRange Objects. If it // does, it recursively destroys additionally allocated MemRange Objects. TMemRange::~TMemRange(void) { PurgeRange(); } // TMemRange -- PurgeRange // The following destructs all children of the called range. This // is useful in re-using (and re-initializing) existing TMemRange objects. // This function is used by the destructor to destroy children as well // when an object is removed. The difference is that this function allows // us to destroy the children without killing the parent. void TMemRange::PurgeRange(void) { StartAddr = 0; Size = 0; UserData = 0; if (Next!=NULL) { delete Next; Next=NULL; } } // TMemRange -- AddressInRange // The following determines if a specified address exists within the // ranges specified by the current object (or its children). // This is useful for programs needing to identify addresses that are // in a range without necessarily needing to use descriptor bytes or // other methods of address referal. // The routine returns a '1' (or TRUE) if the address lies inside the // linked list of range (where this object is the head) or '0' (or // FALSE) if it does not. int TMemRange::AddressInRange(unsigned long aAddr) { if ((aAddr>=StartAddr) && (aAddr<(StartAddr+Size))) return(1); else if (Next!=NULL) return (Next->AddressInRange(aAddr)); return (0); } // TMemRange -- Consolidate // The following function spans through the TMemRange and finds the // lowest and highest addresses. It then purges the TMemRange and // sets its size and length to the corresponding values. void TMemRange::Consolidate(void) { unsigned long MinAddr, MaxAddr; TMemRange *aRange; MinAddr = StartAddr; MaxAddr = StartAddr+Size; aRange = Next; while (aRange) { if (aRange->StartAddr < MinAddr) MinAddr = aRange->StartAddr; if ((aRange->StartAddr+aRange->Size) > MaxAddr) MaxAddr = aRange->StartAddr+aRange->Size; aRange = aRange->Next; } PurgeRange(); StartAddr = MinAddr; Size = MaxAddr - MinAddr; } // IsNullRange // The following function will test the range to see if it // is null and return a TRUE if it is or FALSE if not. A // null range is defined as one whose size records are all // zero. int TMemRange::IsNullRange(void) { if (Size != 0) return 0; if (Next != NULL) return (Next->IsNullRange()); return 1; } // Invert // The following is the converse of Consolidate. It transforms // the range list to its inverse within the bounds of the // given range. // Note: The UserData is lost from the original Range... (obviously) // Supports: ERR_OUT_OF_MEMORY throwback void TMemRange::Invert(void) { TMemRange* TempRange; TMemRange NewRange(0, 0, 0); TMemRange* ptRange; unsigned long StartA; unsigned long Ending; // Duplicate ourselves: try { TempRange = new TMemRange(*this); } catch (EXCEPTION_ERROR*) { throw; } // clean and sort the copy try { TempRange->Compact(); TempRange->RemoveOverlaps(); TempRange->Sort(); } catch (EXCEPTION_ERROR*) { delete TempRange; throw; } // Get our bounds from the consolidated version Ending = 0; ptRange = TempRange; while (ptRange != NULL) { StartA = ptRange->StartAddr; if (StartA > Ending) { try { NewRange.AddRange(Ending, StartA-Ending); // Add range between zones } catch (EXCEPTION_ERROR*) { delete TempRange; throw; } } Ending = StartA + ptRange->Size; // Move Ending ptRange=ptRange->Next; } // Purge us and fill ourselves with the new inverted range PurgeRange(); // Copy the new range structure to this range structure if (NewRange.Next != NULL) { // Copy the first record StartAddr = NewRange.Next->StartAddr; Size = NewRange.Next->Size; UserData = NewRange.Next->UserData; // And concatenate the rest try { Concatenate(NewRange.Next->Next); } catch (EXCEPTION_ERROR*) { throw; } } // Clean memory: NewRange.PurgeRange(); TempRange->PurgeRange(); delete TempRange; } // Sort // The following sorts the range in ascending format. Useful // for traversing, etc. If two ranges have the same starting // address, then the shorter is placed ahead of the longer. // Since range lists are very short, we'll use a simple // bubble sort. // Supports: ERR_OUT_OF_MEMORY throwback void TMemRange::Sort(void) { TMemRange TempRange(0, 0, 0); TMemRange Swap(0, 0, 0); TMemRange* TempA; TMemRange* TempB; TMemRange* TempX; TMemRange* TempY; unsigned long StartA, EndA; unsigned long StartB, EndB; int Flag; try { TempRange.Concatenate(this); } catch (EXCEPTION_ERROR*) { throw; } TempA = &TempRange; TempB = TempA->Next; while (TempB != NULL) { TempX=TempB; TempY=TempB->Next; StartA = TempB->StartAddr; EndA = StartA+TempB->Size; Flag = 0; while ((!Flag) && (TempY != NULL)) { StartB = TempY->StartAddr; EndB = StartB+TempY->Size; if ( (StartB<StartA) || ((StartB==StartA) && (EndB<EndA)) ) { Flag = 1; } else { TempX=TempX->Next; TempY=TempY->Next; } } if (!Flag) { // If none was found greater than this A/B pair, advance -- loop to end TempA=TempA->Next; TempB=TempB->Next; } else { // We found one, lets swap it Swap.StartAddr = TempY->StartAddr; Swap.Size = TempY->Size; Swap.UserData = TempY->UserData; TempY->StartAddr = TempB->StartAddr; TempY->Size = TempB->Size; TempY->UserData = TempB->UserData; TempB->StartAddr = Swap.StartAddr; TempB->Size = Swap.Size; TempB->UserData = Swap.UserData; // Reloop, but don't advance A/B pair -- this way all pairs are tested } } // Purge us and fill ourselves with the new sorted range PurgeRange(); // Copy the new range structure to this range structure if (TempRange.Next != NULL) { // Copy the first record StartAddr = TempRange.Next->StartAddr; Size = TempRange.Next->Size; UserData = TempRange.Next->UserData; // And concatenate the rest try { Concatenate(TempRange.Next->Next); } catch (EXCEPTION_ERROR*) { throw; } } // Clean memory: TempRange.PurgeRange(); } // RemoveOverlaps // The following function traverses the range and removes // overlaps. If overlaps exist, the offending range // entries are replaced by a single range spanning the same // total range. Note that the order of the ranges will // change if overlaps exist and are not deterministic. // Also, the UserData value must be IDENTICAL on the // offending ranges, otherwise, they are not changed. // Supports: ERR_OUT_OF_MEMORY throwback void TMemRange::RemoveOverlaps(void) { TMemRange TempRange(0, 0, 0); TMemRange* TempA; TMemRange* TempB; TMemRange* TempX; TMemRange* TempY; unsigned long StartA, EndA; unsigned long StartB, EndB; int Flag; try { TempRange.Concatenate(this); } catch (EXCEPTION_ERROR*) { throw; } TempA = &TempRange; TempB = TempA->Next; while (TempB != NULL) { TempX=TempB; TempY=TempB->Next; StartA = TempB->StartAddr; EndA = StartA+TempB->Size; Flag = 0; while ((!Flag) && (TempY != NULL)) { StartB = TempY->StartAddr; EndB = StartB+TempY->Size; if ((TempB->UserData == TempY->UserData) && ( ((StartA>=StartB) && (StartA<EndB)) || ((EndA>=StartB) && (EndA<EndB)) ) ) { Flag = 1; } else { TempX=TempX->Next; TempY=TempY->Next; } } if (!Flag) { // If no overlap with this A/B pair, advance -- continue till end TempA=TempA->Next; TempB=TempB->Next; } else { if (StartB<StartA) StartA=StartB; if (EndB>EndA) EndA=EndB; // Consolidate to remove overlap: TempB->StartAddr = StartA; TempB->Size = EndA-StartA; // Remove extraneous range: TempX->Next = TempY->Next; TempY->Next = NULL; // Nullify to avoid false delete delete TempY; TempY = TempX->Next; // Reloop, but don't advance A/B pair -- this way all pairs are tested } } // Purge us and fill ourselves with the new compressed range PurgeRange(); // Copy the new range structure to this range structure if (TempRange.Next != NULL) { // Copy the first record StartAddr = TempRange.Next->StartAddr; Size = TempRange.Next->Size; UserData = TempRange.Next->UserData; // And concatenate the rest try { Concatenate(TempRange.Next->Next); } catch (EXCEPTION_ERROR*) { throw; } } // Clean memory: TempRange.PurgeRange(); } // Compact // This function removes any size-zero entries within // the range, unless of course there is only one range (this one) // and it has a zero size. void TMemRange::Compact(void) { TMemRange* TempA; TMemRange* TempB; TempA = this; TempB = Next; while (TempB != NULL) { if (TempB->Size == 0) { TempA->Next = TempB->Next; TempB->Next = NULL; // Nullify to avoid false delete delete TempB; TempB = TempA->Next; } else { TempA = TempA->Next; TempB = TempB->Next; } } // If this one is 0, and we have more after it, rotate data up if ((Size == 0) && (Next != NULL)) { TempA = Next; StartAddr = TempA->StartAddr; Size = TempA->Size; UserData = TempA->UserData; Next = TempA->Next; TempA->Next = NULL; // Nullify to avoid false delete delete TempA; } } // Concatenate // The following traverses the passed in range and appends // it to the end of this range. // Supports: ERR_OUT_OF_MEMORY throwback void TMemRange::Concatenate(TMemRange* aRange) { TMemRange* TempRange; TempRange = aRange; while (TempRange != NULL) { try { if (TempRange->Size != 0) { AddRange(TempRange->StartAddr, TempRange->Size, TempRange->UserData); } } catch (EXCEPTION_ERROR*) { throw; } TempRange = TempRange->Next; } } // GetStartAddr // This function returns the protected StartAddr element. unsigned long TMemRange::GetStartAddr(void) { return(StartAddr); } // SetStartAddr // This function sets the protected StartAddr element void TMemRange::SetStartAddr(unsigned long aStartAddr) { StartAddr=aStartAddr; } // GetSize // This function returns the protected Size element. unsigned long TMemRange::GetSize(void) { return(Size); } // SetSize // This function sets the protected Size element. void TMemRange::SetSize(unsigned long aSize) { Size=aSize; } // GetNext // Returns the next pointer TMemRange *TMemRange::GetNext(void) { return(Next); } // SetNext // Sets the next pointer void TMemRange::SetNext(TMemRange *aNext) { Next=aNext; } // GetUserData // This function returns the user-set data. User-set data // is just to allow additional storage for the user without // having to allocate additional ranges -- sorta like user // data in listboxes, etc. Useful to correlate ranges with // other objects and events. unsigned long TMemRange::GetUserData(void) { return (UserData); } // SetUserData // This function sets the user-set data. User-set data // is just to allow additional storage for the user without // having to allocate additional ranges -- sorta like user // data in listboxes, etc. Useful to correlate ranges with // other objects and events. void TMemRange::SetUserData(unsigned long aUserData) { UserData = aUserData; } // AddRange // This function allocates a new Range object based on the passed // parameters and then follows through the chain of Nexts recursively // to add it to the TAIL. // Supports: ERR_OUT_OF_MEMORY throwback TMemRange *TMemRange::AddRange(unsigned long aStartAddr, unsigned long aSize, unsigned long aUserData) { TMemRange *RetVal; RetVal=NULL; if (Next!=NULL) { try { RetVal=Next->AddRange(aStartAddr, aSize, aUserData); } catch (EXCEPTION_ERROR*) { throw; } } else { RetVal=new TMemRange(aStartAddr, aSize, aUserData); if (RetVal!=NULL) { Next=RetVal; } else { THROW_MEMORY_EXCEPTION_ERROR(0); } } return(RetVal); } // The following are the function declarations for TMappingObject // TMappingObject -- Constructor // The following constructs a TMappingObject by setting the LogicalAddr, // BlockNumber, and Physical Address, and nullifying the next pointer. TMappingObject::TMappingObject(unsigned long ALogicalAddr, unsigned int ABlockNumber, unsigned long APhysAddr) { LogicalAddr = ALogicalAddr; BlockNumber = ABlockNumber; PhysicalAddr = APhysAddr; Next=NULL; } // TMappingObject -- Duplication Constructor // Works sorta like 'strdup'. It allocates memory for a new TMappingObject, // copies itself to the new object, and returns a pointer to the new one. // Also, this function is recursive -- if the object this function is called // for has a valid next pointer, it calls the Duplication Constructor with // the next to duplicate the nexts in the newly created object. // Supports: ERR_OUT_OF_MEMORY throwback. TMappingObject::TMappingObject(TMappingObject& aMap) { LogicalAddr = aMap.LogicalAddr; BlockNumber = aMap.BlockNumber; PhysicalAddr = aMap.PhysicalAddr; Next=NULL; try { if (aMap.Next!=NULL) { Next=new TMappingObject(*aMap.Next); if (Next==NULL) THROW_MEMORY_EXCEPTION_ERROR(0); } } catch (EXCEPTION_ERROR*) { if (Next!=NULL) { delete Next; Next=NULL; } throw; } } // TMappingObject -- Destructor // The following destructs a TMappingObject by checking to see if Next // points to a valid pointer to a linked list of MappingObjects. If it // does, it recursively destroys additionally allocated MappingObjects. TMappingObject::~TMappingObject(void) { if (Next!=NULL) { delete Next; Next=NULL; } } // GetLogicalAddr // Returns the protected LogicalAddr element. unsigned long TMappingObject::GetLogicalAddr(void) { return LogicalAddr; } // GetBlockNumber // Returns the protected BlockNumber element. unsigned int TMappingObject::GetBlockNumber(void) { return BlockNumber; } // GetPhysicalAddr // Returns the protected PhysicalAddr element. unsigned long TMappingObject::GetPhysicalAddr(void) { return PhysicalAddr; } // SetNext // Sets the Next pointer. void TMappingObject::SetNext(TMappingObject *ANext) { Next = ANext; } // GetNext // Returns the protected Next pointer element. TMappingObject *TMappingObject::GetNext(void) { return Next; } // AddMapping // This function allocates a new TMappingObject based on the passed // parameters and then follows through the chain of Nexts recursively // to add it to the TAIL. // Supports: ERR_OUT_OF_MEMORY throwback TMappingObject *TMappingObject::AddMapping(unsigned long ALogicalAddr, unsigned int ABlockNumber, unsigned long APhysAddr) { TMappingObject *RetVal; RetVal=NULL; if (Next!=NULL) { try { RetVal=Next->AddMapping(ALogicalAddr, ABlockNumber, APhysAddr); } catch (EXCEPTION_ERROR*) { throw; } } else { RetVal=new TMappingObject(ALogicalAddr, ABlockNumber, APhysAddr); if (RetVal!=NULL) { Next=RetVal; } else { THROW_MEMORY_EXCEPTION_ERROR(0); } } return(RetVal); } // The following are the function declarations for TMemObject // TMemObject -- Constructor // The following constructs a TMemObject by setting NumBlocks and BlockSize, // allocates the necessary memory for the object, and calls ClearMemory to // set all memory elements to FillByte with a descriptor of 0. And it // nullifies the BlockMap pointer. // Supports: ERR_OUT_OF_MEMORY throwback. TMemObject::TMemObject(unsigned int NBlocks, unsigned long BSize, unsigned char FillByte, int UseDesc) { try { CreateMemObject(NBlocks, BSize, FillByte, UseDesc); } catch (EXCEPTION_ERROR*) { throw; } } // TMemObject -- Duplicating Constructor // Works sorta like 'strdup'. It allocates memory for a new TMemObject, // copies itself to the new object, and returns a pointer to the new one. // If BlockMap is a valid BlockMap pointer, it calls the MappingObject // Duplicating Contructor to duplicate the mapping as well. // Supports: ERR_OUT_OF_MEMORY throwback. TMemObject::TMemObject(TMemObject& aMem) { unsigned long i; try { CreateMemObject(aMem.NumBlocks, aMem.BlockSize, 0x00, ((aMem.Descriptors!=NULL) ? 1 : 0)); } catch (EXCEPTION_ERROR*) { throw; } for (i=0; (i<GetMemSize()); ++i) { if (aMem.Data) Data[i]=aMem.Data[i]; if (aMem.Descriptors) Descriptors[i]=aMem.Descriptors[i]; } try { if (aMem.BlockMap!=NULL) BlockMap=new TMappingObject(*aMem.BlockMap); } catch (EXCEPTION_ERROR*) { // Cleanup on error ClearMapping(); // Dispose of all mapping objects if (Descriptors) delete[] Descriptors; // Free Allocated memory if (Data) delete[] Data; throw; } } // TMemObject -- Constructor From Range // This constructor creates a copy of the passed in range, // consolidates it to find the actual bounds of the range, // and then creates a Memory Object capable of holding // the entire range. The Memory Object will consist of // a single block of the calculated size and a mapping // object will be created and attached to the memory // in accordance with the range. TMemObject::TMemObject(TMemRange& aRange, unsigned char FillByte, int UseDesc) { TMemRange *TempRange; try { TempRange = new TMemRange(aRange); } catch (EXCEPTION_ERROR*) { throw; } if (TempRange) { TempRange->Consolidate(); try { // Create the memory and setup the mapping CreateMemObject(1,TempRange->GetSize(), FillByte, UseDesc); } catch (EXCEPTION_ERROR*) { // Cleanup on error delete TempRange; throw; } try { AddMapping(TempRange->GetStartAddr(), 0, TempRange->GetStartAddr()); } catch (EXCEPTION_ERROR*) { // Cleanup if we encounter an error ClearMapping(); // Dispose of all mapping objects if (Descriptors) delete[] Descriptors; // Free Allocated memory if (Data) delete[] Data; throw; } } delete TempRange; } // TMemObject -- Destructor // The following destructs a TMemObject by calling ClearMapping to // destroy all associated mapping objects and then it frees all memory // allocated for the memory object. TMemObject::~TMemObject(void) { ClearMapping(); // Dispose of all mapping objects if (Descriptors) delete[] Descriptors; // Free Allocated memory if (Data) delete[] Data; } // CreateMemObject // This function creates a TMemObject by allocating and initializing // necessary memory. It is here in its own function so that all the // various overloaded constructors can call it. void TMemObject::CreateMemObject(unsigned int NBlocks, unsigned long BSize, unsigned char FillByte, int UseDesc) { Data = new unsigned char[NBlocks*BSize]; if (Data == NULL) THROW_MEMORY_EXCEPTION_ERROR(0); // Report Error if out of memory if (UseDesc) { Descriptors = new unsigned char[NBlocks*BSize]; if (Descriptors == NULL) { delete[] Data; THROW_MEMORY_EXCEPTION_ERROR(0); // Report Error if out of memory } } else Descriptors = NULL; NumBlocks=NBlocks; BlockSize=BSize; BlockMap=NULL; ClearMemory(FillByte); } // GetByte // Returns the memory data byte addressed by the passed in Logical Address, // based on the current Block Mapping. unsigned char TMemObject::GetByte(unsigned long LogicalAddr) { TMappingObject *Temp_Ptr; if (Data) { Temp_Ptr = BlockMap; while (Temp_Ptr != NULL) { if ((LogicalAddr>=Temp_Ptr->GetLogicalAddr()) && (LogicalAddr<(Temp_Ptr->GetLogicalAddr()+BlockSize))) { return (Data[(LogicalAddr-Temp_Ptr->GetLogicalAddr())+(Temp_Ptr->GetBlockNumber()*BlockSize)]); } Temp_Ptr=Temp_Ptr->GetNext(); } } return (0); } // SetByte // Sets the memory data byte addressed by the passed in Logical Address, // based on the current Block Mapping to the passed in Byte. int TMemObject::SetByte(unsigned long LogicalAddr, unsigned char Byte) { TMappingObject *Temp_Ptr; if (Data) { Temp_Ptr = BlockMap; while (Temp_Ptr != NULL) { if ((LogicalAddr>=Temp_Ptr->GetLogicalAddr()) && (LogicalAddr<(Temp_Ptr->GetLogicalAddr()+BlockSize))) { Data[(LogicalAddr-Temp_Ptr->GetLogicalAddr())+(Temp_Ptr->GetBlockNumber()*BlockSize)]=Byte; return(1); } Temp_Ptr=Temp_Ptr->GetNext(); } } return(0); } // GetDescriptor // Returns the memory descriptor byte addressed by the passed in Logical Address, // based on the current Block Mapping. unsigned char TMemObject::GetDescriptor(unsigned long LogicalAddr) { TMappingObject *Temp_Ptr; if (Descriptors) { Temp_Ptr = BlockMap; while (Temp_Ptr != NULL) { if ((LogicalAddr>=Temp_Ptr->GetLogicalAddr()) && (LogicalAddr<(Temp_Ptr->GetLogicalAddr()+BlockSize))) { return (Descriptors[(LogicalAddr-Temp_Ptr->GetLogicalAddr())+(Temp_Ptr->GetBlockNumber()*BlockSize)]); } Temp_Ptr=Temp_Ptr->GetNext(); } } return (0); } // SetDescriptor // Sets the memory descriptor byte addressed by the passed in Logical Address, // based on the current Block Mapping to the passed in Desc. int TMemObject::SetDescriptor(unsigned long LogicalAddr, unsigned char Desc) { TMappingObject *Temp_Ptr; if (Descriptors) { Temp_Ptr = BlockMap; while (Temp_Ptr != NULL) { if ((LogicalAddr>=Temp_Ptr->GetLogicalAddr()) && (LogicalAddr<(Temp_Ptr->GetLogicalAddr()+BlockSize))) { Descriptors[(LogicalAddr-Temp_Ptr->GetLogicalAddr())+(Temp_Ptr->GetBlockNumber()*BlockSize)]=Desc; return(1); } Temp_Ptr=Temp_Ptr->GetNext(); } } return(0); } // GetMemSize // Returns the size of the memory allocated for data bytes. unsigned long TMemObject::GetMemSize(void) { return(NumBlocks*BlockSize); } // ClearMemory // Sets all allocated data bytes to the specified FillByte and sets // all corresponding descriptor bytes to 0. void TMemObject::ClearMemory(unsigned char FillByte) { unsigned long i; for (i=0; (i<GetMemSize()); ++i) { if (Data) Data[i]=FillByte; if (Descriptors) Descriptors[i]=0; } } // ClearMapping // If BlockMap is not NULL, it destroys the object (and its child // objects) that it points to, and sets BlockMap to NULL. void TMemObject::ClearMapping(void) { if (BlockMap != NULL) { delete BlockMap; BlockMap=NULL; } } // AddMapping // Adds a mapping object at the TAIL of the BlockMap IF the defined object // is within range of the allocated Memory space. // Supports: ERR_OUT_OF_MEMORY throwback // ERR_OUT_OF_RANGE throwback (IF MAPTHROW is defined) // ERR_MAPPING_OVERLAP throwback (IF MAPTHROW is defined) void TMemObject::AddMapping(unsigned long ALogicalAddr, unsigned int ABlockNumber, unsigned long APhysAddr) { TMappingObject *Temp_Ptr; #ifdef MAPTHROW if (ABlockNumber>=NumBlocks) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_OUT_OF_RANGE, 0, ""); #endif if (ABlockNumber>=NumBlocks) return; #ifdef MAPTHROW Temp_Ptr = BlockMap; while (Temp_Ptr != NULL) { if ((ALogicalAddr>=Temp_Ptr->GetLogicalAddr()) && (ALogicalAddr<(Temp_Ptr->GetLogicalAddr()+BlockSize))) { break; } Temp_Ptr=Temp_Ptr->GetNext(); } if (Temp_Ptr != NULL) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_MAPPING_OVERLAP, 0, ""); #endif if (BlockMap==NULL) { Temp_Ptr = new TMappingObject(ALogicalAddr, ABlockNumber, APhysAddr); if (Temp_Ptr == NULL) THROW_MEMORY_EXCEPTION_ERROR(0); // Return error if no memory BlockMap=Temp_Ptr; } else { try { BlockMap->AddMapping(ALogicalAddr, ABlockNumber, APhysAddr); } catch (EXCEPTION_ERROR*) { throw; } } } // GetPhysicalAddr // Looks the LogicalAddr up in the defined BlockMap and returns the // equivalent PhysicalAddr. unsigned long TMemObject::GetPhysicalAddr(unsigned long LogicalAddr) { TMappingObject *Temp_Ptr; Temp_Ptr = BlockMap; while (Temp_Ptr != NULL) { if ((LogicalAddr>=Temp_Ptr->GetLogicalAddr()) && (LogicalAddr<(Temp_Ptr->GetLogicalAddr()+BlockSize))) { return (Temp_Ptr->GetPhysicalAddr()+(LogicalAddr-Temp_Ptr->GetLogicalAddr())); } Temp_Ptr=Temp_Ptr->GetNext(); } return (0x0000); } <file_sep>/programs/m6811dis/memclass.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* MEMCLASS This is the C++ Memory Object Class Header File. Author: <NAME> Date: January 28, 1997 Written in: Borland C++ 4.52 Updated: June 22, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. Updated: July 21, 1997 to expand TMemRange function base. */ #ifndef MEMCLASS_H #define MEMCLASS_H #include "errmsgs.h" class TMemRange { protected: unsigned long StartAddr; unsigned long Size; unsigned long UserData; TMemRange *Next; public: TMemRange(unsigned long aStartAddr, unsigned long aSize, unsigned long aUserData = 0); TMemRange(TMemRange& aRange); virtual ~TMemRange(void); void PurgeRange(void); int AddressInRange(unsigned long aAddr); void Consolidate(void); int IsNullRange(void); void Invert(void); void Sort(void); void RemoveOverlaps(void); void Compact(void); void Concatenate(TMemRange* aRange); unsigned long GetStartAddr(void); void SetStartAddr(unsigned long aStartAddr); unsigned long GetSize(void); void SetSize(unsigned long aSize); TMemRange *GetNext(void); void SetNext(TMemRange *aNext); unsigned long GetUserData(void); void SetUserData(unsigned long aUserData); TMemRange *AddRange(unsigned long aStartAddr, unsigned long aSize, unsigned long aUserData = 0); }; class TMappingObject { protected: unsigned long LogicalAddr; unsigned int BlockNumber; unsigned long PhysicalAddr; TMappingObject *Next; public: TMappingObject(unsigned long ALogicalAddr, unsigned int ABlockNumber, unsigned long APhysAddr); TMappingObject(TMappingObject& aMap); virtual ~TMappingObject(void); unsigned long GetLogicalAddr(void); unsigned int GetBlockNumber(void); unsigned long GetPhysicalAddr(void); void SetNext(TMappingObject *ANext); TMappingObject *GetNext(void); TMappingObject *AddMapping(unsigned long ALogicalAddr, unsigned int ABlockNumber, unsigned long APhysAddr); }; class TMemObject { protected: unsigned int NumBlocks; unsigned long BlockSize; unsigned char *Data; unsigned char *Descriptors; TMappingObject *BlockMap; public: TMemObject(unsigned int NBlocks, unsigned long BSize, unsigned char FillByte, int UseDesc); TMemObject(TMemObject& aMem); TMemObject(TMemRange& aRange, unsigned char FillByte, int UseDesc); virtual ~TMemObject(void); unsigned char GetByte(unsigned long LogicalAddr); int SetByte(unsigned long LogicalAddr, unsigned char Byte); unsigned char GetDescriptor(unsigned long LogicalAddr); int SetDescriptor(unsigned long LogicalAddr, unsigned char Desc); unsigned long GetMemSize(void); void ClearMemory(unsigned char FillByte); void ClearMapping(void); void AddMapping(unsigned long ALogicalAddr, unsigned int ABlockNumber, unsigned long APhysAddr); unsigned long GetPhysicalAddr(unsigned long LogicalAddr); private: void CreateMemObject(unsigned int NBlocks, unsigned long BSize, unsigned char FillByte, int UseDesc); }; #endif // MEMCLASS_H <file_sep>/programs/dist/linux/m6811dis/readme.txt The Linux version of M6811DIS was compiled against LSB (Linux Standard Base). To guarantee runability, install LSB: sudo apt-get install lsb <file_sep>/programs/funcanal/funcanal.h // funcanal.h : Application header file // // $Log: funcanal.h,v $ // Revision 1.1 2002/07/01 05:50:00 dewhisna // Initial Revision // // #if !defined(AFX_FUNCANAL_H__EBA8556D_010B_4CA0_AAC4_8E188F312700__INCLUDED_) #define AFX_FUNCANAL_H__EBA8556D_010B_4CA0_AAC4_8E188F312700__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "resource.h" #endif // !defined(AFX_FUNCANAL_H__EBA8556D_010B_4CA0_AAC4_8E188F312700__INCLUDED_) <file_sep>/programs/m6811dis/m6811dis.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // // Original Written in Turbo Pascal V7.0 // Ported to MS Visual C++ 5.0/6.0 // This version ported to GCC to be platform independent // // 1.0 Initial release // // 1.1 "Spit" version --- created August 28, 1997 by <NAME> // This version has the new "SPIT" command added to the .CTL // file parsing to enable/disable code-seeking. Also, the .OP // file was done away with and the file-io bugs and index ranges // were fixed. // // 1.2 Translated code from Pascal to C++ to allow for easy expansion // of label size and number of labels. Added in support from m6811dm // for multiple input modules. Control files from previous versions // are backward compatible (except for special m6811dm compile)... // The only thing not compatible with the old version control files // is that on the old version if no entry or indirect values were // specified, the file load addressed was used. On this version, the // default behavior of the control file parser is to issue an error // if there are no entry points or code-indirects specified. This is // necessary because the true load address isn't necessarily known // because of file loading and offsetting is handled exclusively by // DFC libraries. // #include <stdlib.h> #include <stdio.h> #include <iostream> #include "m6811dis.h" #include "m6811gdc.h" int main(int argc, char *argv[]) { bool OkFlag; int Count; CM6811Disassembler theDisassembler; printf("M6811 Disassembler V%ld.%02ld -- GDC V%ld.%02ld\n", (theDisassembler.GetVersionNumber()&0x0000FF00ul)>>8, (theDisassembler.GetVersionNumber()&0x000000FFul), (theDisassembler.GetVersionNumber()&0xFF000000ul)>>24, (theDisassembler.GetVersionNumber()&0x00FF0000ul)>>16); printf("Copyright(c)1996-2014 by <NAME>\n"); printf("\n"); if (argc<2) { printf("Usage: m6811dis <ctrl filename1> [<ctrl filename2> <ctrl filename3> ...]\n"); return -1; } OkFlag = true; Count = 1; while ((OkFlag) && (Count < argc)) { ifstreamControlFile CtrlFile(argv[Count]); if (!CtrlFile.is_open()) { printf("*** Error: Opening control file \"%s\" for reading...\n", argv[Count]); return -2; } OkFlag = theDisassembler.ReadControlFile(CtrlFile, (Count == argc-1), &std::cout, &std::cerr); CtrlFile.close(); Count++; } if (OkFlag) theDisassembler.Disassemble(&std::cout, &std::cerr); return 0; } <file_sep>/programs/m6811dis/bindfc.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* BINARYDFC --- BINARY Data File Converter Class This is the C++ Module that contains routines to read and write binary data files, by defining a new derived class DFC_BINARY from the base class DataFileConverter. This module makes use of the MEMCLASS type for memory interface. Author: <NAME> Date: March 7, 1997 Written in: Borland C++ 4.52 Updated: June 23, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. Updated: June 29, 1997 to use iostream instead of run-time library so that external DLL calls will function correctly. */ #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string> #include <time.h> #include "bindfc.h" // RetrieveFileMapping: // // This function reads in an already opened BINARY file pointed to by // 'aFile' and generates a TMemRange object that encapsulates the file's // contents, offsetted by 'NewBase' (allowing loading of different files // to different base addresses). // // Author: <NAME> // Date: June 28, 1997 int TDFC_Binary::RetrieveFileMapping(std::istream *aFile, unsigned long NewBase, TMemRange *aRange) const { if (aRange) { aRange->PurgeRange(); aRange->SetStartAddr(NewBase); aFile->seekg(0L, std::ios_base::end); aRange->SetSize(aFile->tellg()); if (aRange->GetSize() == static_cast<unsigned long>(-1)) aRange->SetSize(0); aFile->seekg(0L, std::ios_base::beg); } return 1; } // ReadDataFile: // // This function reads in an already opened BINARY file pointed to by // 'aFile' into the MemObject pointed to by 'aMemory' offsetted by // 'NewBase' (allowing loading of different files to different base // address and setting the corresponding Memory Descriptors to 'aDesc'... // // Author: <NAME> // Date: March 7, 1997 int TDFC_Binary::ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc) const { int RetVal; // Return Value unsigned char aByte; unsigned long CurrAddr; // Current Memory Address RetVal=1; CurrAddr = NewBase; aFile->seekg(0L, std::ios_base::beg); while ((!aFile->eof()) && (aFile->peek() != EOF) && (aFile->good())) { aByte = aFile->get(); if (!aMemory->SetByte(CurrAddr, aByte)) { THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_OVERFLOW, 0, ""); } if (aMemory->GetDescriptor(CurrAddr)!=0) RetVal=0; aMemory->SetDescriptor(CurrAddr, aDesc); CurrAddr++; } return(RetVal); } // WriteDataFile: // // This function writes to an already opened BINARY file pointed to by // 'aFile' from the MemObject pointed to by 'aMemory' and whose Descriptor // has a match specified by 'aDesc'. Matching is done by 'anding' the // aDesc value with the descriptor in memory. If the result is non-zero, // the location is written. Unless, aDesc=0, in which case ALL locations // are written regardless of the actual descriptor. If the aDesc validator // computes out as false, then the data is filled according to the FillMode. // // Author: <NAME> // Date: January 29, 1997 int TDFC_Binary::WriteDataFile(std::ostream *aFile, TMemRange *aRange, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc, int UsePhysicalAddr, unsigned int FillMode) const { TMemRange *CurrRange; // Range Spanning variable int RetVal; // Return Value unsigned long BytesLeft; // Remaining number of bytes to check/write unsigned long CurrAddr; // Current Logical Memory Address unsigned long RealAddr = 0; // Current Written Address equivalent int NeedNewOffset; srand( (unsigned)time( NULL ) ); CurrRange=aRange; RetVal=1; NeedNewOffset = 1; while (CurrRange!=NULL) { CurrAddr=CurrRange->GetStartAddr(); BytesLeft=CurrRange->GetSize(); while (BytesLeft) { while (BytesLeft && NeedNewOffset) { if ((aDesc==0) || (aDesc & aMemory->GetDescriptor(CurrAddr)) || (FillMode!=DFC_FILL_TYPE(NO_FILL))) { if (UsePhysicalAddr) { RealAddr=aMemory->GetPhysicalAddr(CurrAddr)+NewBase; } else { RealAddr=CurrAddr+NewBase; } NeedNewOffset=0; } else { BytesLeft--; CurrAddr++; } } while (BytesLeft && !NeedNewOffset) { if ((aDesc==0) || (aDesc & aMemory->GetDescriptor(CurrAddr))) { aFile->put(aMemory->GetByte(CurrAddr)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0, ""); } else { switch GET_DFC_FILL_TYPE(FillMode) { case DFC_FILL_TYPE(ALWAYS_FILL_WITH): case DFC_FILL_TYPE(CONDITIONAL_FILL_WITH): aFile->put(GET_DFC_FILL_BYTE(FillMode)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0, ""); break; case DFC_FILL_TYPE(ALWAYS_FILL_WITH_RANDOM): case DFC_FILL_TYPE(CONDITIONAL_FILL_WITH_RANDOM): aFile->put((unsigned char)(rand()%256)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0, ""); break; default: aFile->put((unsigned char)0x00); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0, ""); break; } } BytesLeft--; CurrAddr++; RealAddr++; if ((aDesc==0) || (aDesc & aMemory->GetDescriptor(CurrAddr)) || (FillMode!=DFC_FILL_TYPE(NO_FILL))) { if (UsePhysicalAddr) { if (RealAddr!=(aMemory->GetPhysicalAddr(CurrAddr)+NewBase)) { NeedNewOffset=1; } } } else { NeedNewOffset=1; } } } CurrRange=CurrRange->GetNext(); } return(RetVal); } <file_sep>/programs/funcanal/FuncView/FuncViewPrjDoc.cpp // FuncViewPrjDoc.cpp : implementation of the CFuncViewPrjDoc class // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncViewPrjDoc.cpp,v $ // Revision 1.1 2003/09/13 05:45:44 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ProgDlg.h" #include "MainFrm.h" #include "FuncViewPrjDoc.h" // Project Document View -- ChildFrame #include "ChildFrm2.h" // Func Diff View -- ChildFrame2 #include "FuncListView.h" #include "ChildFrm3.h" // Symbol Map View -- ChildFrame3 #include "ChildFrm4.h" // Output View -- ChildFrame4 #include "OutputView.h" #include "ChildFrm5.h" // Comp Matrix View -- ChildFrame5 #include "ChildFrm6.h" // Comp Diff Edit View -- ChildFrame6 #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static const char *m_arrstrFileSetSectionNames[CFuncViewPrjDoc::FVFS_COUNT] = { "LeftFiles", "RightFiles" }; static const char *m_strMatrixSectionName = "MatrixFiles"; static const char m_strNumFilesEntry[] = "NumFiles"; static const char m_strFileEntryPrefix[] = "File"; ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc IMPLEMENT_DYNCREATE(CFuncViewPrjDoc, CDocument) BEGIN_MESSAGE_MAP(CFuncViewPrjDoc, CDocument) //{{AFX_MSG_MAP(CFuncViewPrjDoc) ON_COMMAND(ID_VIEW_FUNC_DIFF, OnViewFuncDiff) ON_UPDATE_COMMAND_UI(ID_VIEW_FUNC_DIFF, OnUpdateViewFuncDiff) ON_COMMAND(ID_SYMBOLS_RESET, OnSymbolsReset) ON_COMMAND(ID_VIEW_SYMBOL_MAP, OnViewSymbolMap) ON_UPDATE_COMMAND_UI(ID_VIEW_SYMBOL_MAP, OnUpdateViewSymbolMap) ON_COMMAND(ID_VIEW_OUTPUT_WINDOW, OnViewOutputWindow) ON_UPDATE_COMMAND_UI(ID_VIEW_OUTPUT_WINDOW, OnUpdateViewOutputWindow) ON_COMMAND(ID_VIEW_COMP_MATRIX, OnViewCompMatrix) ON_UPDATE_COMMAND_UI(ID_VIEW_COMP_MATRIX, OnUpdateViewCompMatrix) ON_COMMAND(ID_MATRIX_REBUILD, OnMatrixRebuild) ON_COMMAND(ID_MATRIX_REBUILD_FORCE, OnMatrixRebuildForce) ON_COMMAND(ID_SYMBOLS_EXPORT, OnSymbolsExport) ON_UPDATE_COMMAND_UI(ID_SYMBOLS_EXPORT, OnUpdateSymbolsExport) ON_COMMAND(ID_VIEW_COMP_DIFF, OnViewCompDiff) ON_UPDATE_COMMAND_UI(ID_VIEW_COMP_DIFF, OnUpdateViewCompDiff) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc construction/destruction CFuncViewPrjDoc::CFuncViewPrjDoc() { m_bFileOpenInProgress = FALSE; m_nMatrixRowCount = 0; m_nMatrixColCount = 0; m_ppnMatrix = NULL; } CFuncViewPrjDoc::~CFuncViewPrjDoc() { FreeMatrixMemory(); } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc callbacks BOOL CALLBACK CFuncViewPrjDoc::FuncDescFileProgressCallback(int nProgressPos, int nProgressMax, BOOL bAllowCancel, LPARAM lParam) { CFuncViewPrjDoc *pDoc = (CFuncViewPrjDoc*)lParam; ASSERT_VALID(pDoc); MSG msg; while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc serialization void CFuncViewPrjDoc::Serialize(CArchive& ar) { ASSERT(FALSE); // This function isn't used -- OnOpenDocument and OnSaveDocument are used instead if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc diagnostics #ifdef _DEBUG void CFuncViewPrjDoc::AssertValid() const { CDocument::AssertValid(); } void CFuncViewPrjDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc commands BOOL CFuncViewPrjDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } void CFuncViewPrjDoc::DeleteContents() { int i; for (i=0; i<GetFileSetCount(); i++) { m_arrFileSets[i].DeleteContents(); } m_objSymbolMap.FreeAll(); m_mapLeftToRightFunc.RemoveAll(); m_mapRightToLeftFunc.RemoveAll(); m_strCompDiffText = ""; m_strOutputText = ""; SetMatrixPathName("", TRUE); CDocument::DeleteContents(); } BOOL CFuncViewPrjDoc::OnOpenDocument(LPCTSTR lpszPathName) { if (IsModified()) TRACE0("Warning: OnOpenDocument replaces an unsaved document.\n"); CFileException fe; CFile* pFile = GetFile(lpszPathName, CFile::modeRead|CFile::shareDenyWrite, &fe); if (pFile == NULL) { ReportSaveLoadException(lpszPathName, &fe, FALSE, AFX_IDP_FAILED_TO_OPEN_DOC); return FALSE; } pFile->Close(); delete pFile; DeleteContents(); SetModifiedFlag(); // dirty during de-serialize m_bFileOpenInProgress = TRUE; OnViewOutputWindow(); CChildFrame4 *pFrame = (CChildFrame4 *)FindFrame(RUNTIME_CLASS(CChildFrame4)); COutputView *pOutputView = NULL; COutputViewFile *pOutputViewFile = NULL; if (pFrame) pOutputView = pFrame->m_pOutputView; if (pOutputView) pOutputViewFile = pOutputView->GetOutputFile(); if (pFrame) pFrame->BeginModalState(); // Put it in modal state during reading int i; int ndx; CString strTemp; CString strTemp2; LPTSTR pBuffer; int nCount; for (ndx = 0; ndx < GetFileSetCount(); ndx++) { nCount = ::GetPrivateProfileInt(m_arrstrFileSetSectionNames[ndx], m_strNumFilesEntry, 0, lpszPathName); for (i=0; i<nCount; i++) { strTemp.Format("%s%ld", LPCTSTR(m_strFileEntryPrefix), i); pBuffer = strTemp2.GetBuffer(1024); ::GetPrivateProfileString(m_arrstrFileSetSectionNames[ndx], strTemp, _T(""), pBuffer, 1024, lpszPathName); strTemp2.ReleaseBuffer(); AddFile(ndx, strTemp2, pOutputViewFile, pOutputViewFile); } } // Currently, only support 1 matrix file: strTemp.Format("%s0", LPCTSTR(m_strFileEntryPrefix)); pBuffer = strTemp2.GetBuffer(1024); ::GetPrivateProfileString(m_strMatrixSectionName, strTemp, _T(""), pBuffer, 1024, lpszPathName); strTemp2.ReleaseBuffer(); SetMatrixPathName(strTemp2, TRUE); SetModifiedFlag(FALSE); // start off with unmodified if (pFrame) pFrame->EndModalState(); // Exit modal state for that window if (pOutputViewFile) pOutputViewFile->Close(); m_bFileOpenInProgress = FALSE; return TRUE; } BOOL CFuncViewPrjDoc::OnSaveDocument(LPCTSTR lpszPathName) { CFileException fe; CFile* pFile = NULL; pFile = GetFile(lpszPathName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive, &fe); if (pFile == NULL) { ReportSaveLoadException(lpszPathName, &fe, TRUE, AFX_IDP_INVALID_FILENAME); return FALSE; } pFile->Close(); int i; int ndx; CString strTemp; int nCount; for (ndx = 0; ndx < GetFileSetCount(); ndx++) { nCount = GetFileCount(ndx); strTemp.Format("%ld", nCount); ::WritePrivateProfileString(m_arrstrFileSetSectionNames[ndx], m_strNumFilesEntry, strTemp, lpszPathName); for (i=0; i<nCount; i++) { strTemp.Format("%s%ld", LPCTSTR(m_strFileEntryPrefix), i); ::WritePrivateProfileString(m_arrstrFileSetSectionNames[ndx], strTemp, GetFilePathName(ndx, i), lpszPathName); } } // Currently, only support 1 matrix file: strTemp.Format("%s0", LPCTSTR(m_strFileEntryPrefix)); ::WritePrivateProfileString(m_strMatrixSectionName, strTemp, GetMatrixPathName(), lpszPathName); SetModifiedFlag(FALSE); // back to unmodified return TRUE; // success } CString CFuncViewPrjDoc::GetFileSetDescription(int nFileSet) { switch (nFileSet) { case FVFS_LEFT_FILES: return "Left-Hand Function Definition Files"; case FVFS_RIGHT_FILES: return "Right-Hand Function Definition Files"; } return ""; } BOOL CFuncViewPrjDoc::AddFile(int nFileSet, LPCTSTR pszFilePathName, CFile *pMsgFile, CFile *pErrFile) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return FALSE; BOOL bFileOpenInProgress = m_bFileOpenInProgress; m_bFileOpenInProgress = TRUE; BOOL bRetVal = m_arrFileSets[nFileSet].AddFile(pszFilePathName, pMsgFile, pErrFile, FuncDescFileProgressCallback, (LPARAM)this); m_bFileOpenInProgress = bFileOpenInProgress; return bRetVal; } int CFuncViewPrjDoc::FindFile(int nFileSet, LPCTSTR pszFilePathName) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return -1; return m_arrFileSets[nFileSet].FindFile(pszFilePathName); } BOOL CFuncViewPrjDoc::RemoveFile(int nFileSet, int nIndex) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return FALSE; return m_arrFileSets[nFileSet].RemoveFile(nIndex); } int CFuncViewPrjDoc::GetFileCount(int nFileSet) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return 0; return m_arrFileSets[nFileSet].GetFileCount(); } CString CFuncViewPrjDoc::GetFilePathName(int nFileSet, int nIndex) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return ""; return m_arrFileSets[nFileSet].GetFilePathName(nIndex); } CString CFuncViewPrjDoc::GetFileName(int nFileSet, int nIndex) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return ""; return m_arrFileSets[nFileSet].GetFileName(nIndex); } CFuncDescFile *CFuncViewPrjDoc::GetFuncDescFile(int nFileSet, int nIndex) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return NULL; return m_arrFileSets[nFileSet].GetFuncDescFile(nIndex); } int CFuncViewPrjDoc::GetFuncCount(int nFileSet, int nIndex) { if ((nFileSet < 0) || (nFileSet >= GetFileSetCount())) return 0; return m_arrFileSets[nFileSet].GetFuncCount(nIndex); } BOOL CFuncViewPrjDoc::AllocateMatrixMemory() { FreeMatrixMemory(); // First, make sure old memory has been freed int nRows = GetFuncCount(FVFS_LEFT_FILES, -1); int nCols = GetFuncCount(FVFS_RIGHT_FILES, -1); int i; BOOL bFail = FALSE; if ((nRows == 0) || (nCols == 0)) return FALSE; m_nMatrixRowCount = nRows; m_nMatrixColCount = nCols; m_ppnMatrix = new double*[nRows]; if (m_ppnMatrix == NULL) { m_nMatrixRowCount = 0; m_nMatrixColCount = 0; return FALSE; } for (i=0; i<nRows; i++) { m_ppnMatrix[i] = new double[nCols]; if (m_ppnMatrix[i] == NULL) bFail = TRUE; } if (bFail) { FreeMatrixMemory(); return FALSE; } return TRUE; } void CFuncViewPrjDoc::FreeMatrixMemory() { if ((m_nMatrixRowCount == 0) || (m_ppnMatrix == NULL)) { m_nMatrixRowCount = 0; m_nMatrixColCount = 0; m_ppnMatrix = NULL; return; } int i; for (i=0; i<m_nMatrixRowCount; i++) { if (m_ppnMatrix[i] == NULL) continue; delete[] (m_ppnMatrix[i]); } delete[] m_ppnMatrix; m_ppnMatrix = NULL; m_nMatrixRowCount = 0; m_nMatrixColCount = 0; } CString CFuncViewPrjDoc::GetMatrixPathName() { return m_strMatrixPathName; } void CFuncViewPrjDoc::SetMatrixPathName(LPCTSTR pszPathName, BOOL bFreeCurrentMatrix) { if (bFreeCurrentMatrix) FreeMatrixMemory(); m_strMatrixPathName = pszPathName; } BOOL CFuncViewPrjDoc::ReadOrBuildMatrix(BOOL bForceRebuild) { CStdioFile mtxFile; BOOL bHaveFile = FALSE; BOOL bFileValid = FALSE; CString strTemp; CString strTemp2; int nPos; int nRows; int nCols; // A call to allocate will clear the old memory, // allocate new, and set the row/col counts: if (!AllocateMatrixMemory()) return FALSE; if (!m_strMatrixPathName.IsEmpty()) { bHaveFile = TRUE; // If we aren't forcing a rebuild, see if we can open the file: if ((!bForceRebuild) && (mtxFile.Open(m_strMatrixPathName, CFile::modeRead | CFile::shareDenyWrite | CFile::typeText))) { strTemp = ""; if (mtxFile.ReadString(strTemp)) { strTemp.TrimLeft(); strTemp.TrimRight(); nPos = strTemp.Find(','); if (nPos != -1) { nRows = atoi(strTemp.Left(nPos)); nCols = atoi(strTemp.Mid(nPos + 1)); } else { nRows = atoi(strTemp); nCols = 0; } if ((nRows == m_nMatrixRowCount) && (nCols == m_nMatrixColCount)) bFileValid = TRUE; } if (!bFileValid) mtxFile.Close(); } } if ((bHaveFile) && (!bFileValid)) { // If we have a filepath but it isn't valid (or we are forcing an overwrite), // try and open the file for writing. If that fails, assume we // just don't have a file: if (!mtxFile.Open(m_strMatrixPathName, CFile::modeCreate | CFile::modeWrite | CFile::shareExclusive | CFile::typeText)) bHaveFile = FALSE; } // At this point, we have one of the following conditions: // bHaveFile bFileValid Reasons Action // --------- ---------- ------------------ ---------------------------------------- // FALSE FALSE No path specified Compare putting results only into memory // Failed to create // TRUE FALSE File doesn't exist File has been opened for writing so compare // File's wrong size to memory and also write to hard file // Forcing Overwrite // FALSE TRUE Should never happen Compare putting results only into memory // TRUE TRUE File's correct File has been opened for reading, read // it into memory rather than doing compare CProgressDlg progDlg(IDS_PROGRESS_MATRIX_COMPARE); int i, j; int nLeftFileIndex; int nLeftFuncIndex; int nRightFileIndex; int nRightFuncIndex; CFuncDesc *pLeftFunc; CFuncDesc *pRightFunc; CWnd *pParent = ((CMDIFrameWnd*)theApp.m_pMainWnd)->GetActiveView(); if (pParent == NULL) pParent = ((CMDIFrameWnd*)theApp.m_pMainWnd)->GetActiveFrame(); progDlg.Create(pParent); progDlg.SetRange(0, ((bHaveFile && bFileValid) ? m_nMatrixRowCount : m_nMatrixRowCount*m_nMatrixColCount)); progDlg.SetStep(1); if (bHaveFile) { if (bFileValid) { progDlg.SetStatus("Reading from Matrix File..."); // If reading from a file and verify x-breakpoints (i.e. righthand function names): strTemp = ""; mtxFile.ReadString(strTemp); strTemp.TrimLeft(); strTemp.TrimRight(); nPos = strTemp.Find(','); strTemp = strTemp.Mid(nPos+1); // Toss first (unused) field strTemp.TrimLeft(); nRightFileIndex = 0; nRightFuncIndex = 0; for (j=0; j<m_nMatrixColCount; j++) { nPos = strTemp.Find(','); if (nPos != -1) { strTemp2 = strTemp.Left(nPos); strTemp2.TrimRight(); strTemp = strTemp.Mid(nPos+1); strTemp.TrimLeft(); } else { strTemp2 = strTemp; strTemp = ""; } pRightFunc = GetNextFunction(FVFS_RIGHT_FILES, nRightFileIndex, nRightFuncIndex); if ((pRightFunc == NULL) || (strTemp2.Compare(pRightFunc->GetMainName()) != 0)) { // Right-side function names don't match. Close file to reset things // and call recursively but force the overwrite: mtxFile.Close(); progDlg.DestroyWindow(); return ReadOrBuildMatrix(TRUE); } } } else { progDlg.SetStatus("Comparing and Writing to Matrix File..."); // If writing to a file, write the size info and x-breakpoints: strTemp.Format("%ld,%ld\n", m_nMatrixRowCount, m_nMatrixColCount); mtxFile.WriteString(strTemp); nRightFileIndex = 0; nRightFuncIndex = 0; strTemp = ""; for (j=0; j<m_nMatrixColCount; j++) { pRightFunc = GetNextFunction(FVFS_RIGHT_FILES, nRightFileIndex, nRightFuncIndex); if (pRightFunc == NULL) continue; strTemp += "," + pRightFunc->GetMainName(); } strTemp += "\n"; mtxFile.WriteString(strTemp); } } else { progDlg.SetStatus("Comparing..."); } nLeftFileIndex = 0; nLeftFuncIndex = 0; for (i=0; i<m_nMatrixRowCount; i++) { pLeftFunc = GetNextFunction(FVFS_LEFT_FILES, nLeftFileIndex, nLeftFuncIndex); if (pLeftFunc == NULL) continue; if ((bHaveFile) && (bFileValid)) { // If reading from a file, do so: strTemp = ""; strTemp2 = ""; mtxFile.ReadString(strTemp); strTemp.TrimLeft(); strTemp.TrimRight(); nPos = strTemp.Find(','); // Read x-breakpoint if (nPos != -1) { strTemp2 = strTemp.Left(nPos); strTemp2.TrimRight(); } if (strTemp2.Compare(pLeftFunc->GetMainName()) != 0) { // Left-side function names don't match. Close file to reset things // and call recursively but force the overwrite: mtxFile.Close(); progDlg.DestroyWindow(); return ReadOrBuildMatrix(TRUE); } strTemp = strTemp.Mid(nPos+1); strTemp.TrimLeft(); for (j=0; j<m_nMatrixColCount; j++) { nPos = strTemp.Find(','); if (nPos != -1) { strTemp2 = strTemp.Left(nPos); strTemp2.TrimRight(); m_ppnMatrix[i][j] = atof(strTemp2); strTemp = strTemp.Mid(nPos+1); strTemp.TrimLeft(); } else { m_ppnMatrix[i][j] = atof(strTemp); strTemp = ""; } } progDlg.StepIt(); if (progDlg.CheckCancelButton()) { FreeMatrixMemory(); return FALSE; } } else { // If not reading from file, we must do full compare // (even if not writing back to a file): nRightFileIndex = 0; nRightFuncIndex = 0; strTemp = pLeftFunc->GetMainName(); for (j=0; j<m_nMatrixColCount; j++) { pRightFunc = GetNextFunction(FVFS_RIGHT_FILES, nRightFileIndex, nRightFuncIndex); if (pRightFunc == NULL) continue; // Note: Function indexes have already been incremented during GetNextFunction m_ppnMatrix[i][j] = ::CompareFunctions(FCM_DYNPROG_GREEDY, GetFuncDescFile(FVFS_LEFT_FILES, nLeftFileIndex), nLeftFuncIndex-1, GetFuncDescFile(FVFS_RIGHT_FILES, nRightFileIndex), nRightFuncIndex-1, FALSE); strTemp2.Format(",%.12g", m_ppnMatrix[i][j]); strTemp += strTemp2; progDlg.StepIt(); if (progDlg.CheckCancelButton()) { FreeMatrixMemory(); return FALSE; } } strTemp += "\n"; // If we are writing to a file, do so: if ((bHaveFile) && (!bFileValid)) mtxFile.WriteString(strTemp); } } if (bHaveFile) mtxFile.Close(); return TRUE; } BOOL CFuncViewPrjDoc::HaveMatrix() { if ((m_nMatrixRowCount == 0) || (m_nMatrixColCount == 0) || (m_ppnMatrix == NULL)) return FALSE; int nRows = GetFuncCount(FVFS_LEFT_FILES, -1); int nCols = GetFuncCount(FVFS_RIGHT_FILES, -1); if ((nRows != m_nMatrixRowCount) || (nCols != m_nMatrixColCount)) return FALSE; return TRUE; } CFuncDesc *CFuncViewPrjDoc::GetNextFunction(int nFileSet, int &nFileIndex, int &nFuncIndex) { CFuncDescFile *pFuncFile; BOOL bFound; if (nFileIndex >= GetFileCount(nFileSet)) return NULL; bFound = FALSE; for (; (nFileIndex < GetFileCount(nFileSet)); nFileIndex++) { pFuncFile = GetFuncDescFile(nFileSet, nFileIndex); if (pFuncFile == NULL) { nFuncIndex = 0; continue; } if (nFuncIndex < pFuncFile->GetFuncCount()) { bFound = TRUE; break; } nFuncIndex = 0; } if ((!bFound) || (pFuncFile == NULL)) return NULL; CFuncDesc *pRetVal = pFuncFile->GetFunc(nFuncIndex); nFuncIndex++; return pRetVal; } CFuncDesc *CFuncViewPrjDoc::GetFileFuncIndexFromLinearIndex(int nFileSet, int nLinearIndex, int &nFileIndex, int &nFuncIndex) { CFuncDescFile *pFuncFile; BOOL bFound; int nLinear; nLinear = 0; bFound = FALSE; for (nFileIndex = 0; nFileIndex < GetFileCount(nFileSet); nFileIndex++) { pFuncFile = GetFuncDescFile(nFileSet, nFileIndex); if (pFuncFile == NULL) continue; for (nFuncIndex = 0; nFuncIndex < pFuncFile->GetFuncCount(); nFuncIndex++) { if (nLinear == nLinearIndex) { bFound = TRUE; break; } nLinear++; } if (bFound) break; } if ((!bFound) || (pFuncFile == NULL)) return NULL; return pFuncFile->GetFunc(nFuncIndex); } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc::CFileSet void CFuncViewPrjDoc::CFileSet::DeleteContents() { m_arrFuncDesc.FreeAll(); } BOOL CFuncViewPrjDoc::CFileSet::AddFile(LPCTSTR pszFilePathName, CFile *pMsgFile, CFile *pErrFile, LPFUNCANALPROGRESSCALLBACK pfnCallback, LPARAM lParamCallback) { CString strFilePathName = pszFilePathName; if (strFilePathName.IsEmpty()) return FALSE; CFuncDescFile *pFuncDescFile; pFuncDescFile = new CFuncDescFile; if (pFuncDescFile == NULL) return FALSE; pFuncDescFile->SetProgressCallback(pfnCallback, lParamCallback); CFile theFile; if (!theFile.Open(strFilePathName, CFile::modeRead | CFile::typeBinary | CFile::shareDenyWrite)) { delete pFuncDescFile; return FALSE; } if (!pFuncDescFile->ReadFuncDescFile(theFile, pMsgFile, pErrFile)) { theFile.Close(); delete pFuncDescFile; return FALSE; } theFile.Close(); m_arrFuncDesc.Add(pFuncDescFile); return TRUE; } int CFuncViewPrjDoc::CFileSet::FindFile(LPCTSTR pszFilePathName) { CString strFilePathName = pszFilePathName; int i; CFuncDescFile *pFuncDescFile; for (i=0; i<m_arrFuncDesc.GetSize(); i++) { pFuncDescFile = m_arrFuncDesc.GetAt(i); if (pFuncDescFile == NULL) continue; if (pFuncDescFile->GetFuncPathName().Compare(strFilePathName) == 0) return i; } return -1; } BOOL CFuncViewPrjDoc::CFileSet::RemoveFile(int nIndex) { ASSERT((nIndex >= 0) && (nIndex < m_arrFuncDesc.GetSize())); if ((nIndex < 0) || (nIndex >= m_arrFuncDesc.GetSize())) return FALSE; CFuncDescFile *pFuncDesc = m_arrFuncDesc.GetAt(nIndex); m_arrFuncDesc.RemoveAt(nIndex); if (pFuncDesc) delete pFuncDesc; return TRUE; } int CFuncViewPrjDoc::CFileSet::GetFileCount() { return m_arrFuncDesc.GetSize(); } CString CFuncViewPrjDoc::CFileSet::GetFilePathName(int nIndex) { ASSERT((nIndex >= 0) && (nIndex < m_arrFuncDesc.GetSize())); if ((nIndex < 0) || (nIndex >= m_arrFuncDesc.GetSize())) return ""; CFuncDescFile *pFuncDesc = m_arrFuncDesc.GetAt(nIndex); if (pFuncDesc == NULL) return ""; return pFuncDesc->GetFuncPathName(); } CString CFuncViewPrjDoc::CFileSet::GetFileName(int nIndex) { ASSERT((nIndex >= 0) && (nIndex < m_arrFuncDesc.GetSize())); if ((nIndex < 0) || (nIndex >= m_arrFuncDesc.GetSize())) return ""; CFuncDescFile *pFuncDesc = m_arrFuncDesc.GetAt(nIndex); if (pFuncDesc == NULL) return ""; return pFuncDesc->GetFuncFileName(); } CFuncDescFile *CFuncViewPrjDoc::CFileSet::GetFuncDescFile(int nIndex) { ASSERT((nIndex >= 0) && (nIndex < m_arrFuncDesc.GetSize())); if ((nIndex < 0) || (nIndex >= m_arrFuncDesc.GetSize())) return NULL; CFuncDescFile *pFuncDesc = m_arrFuncDesc.GetAt(nIndex); return pFuncDesc; } int CFuncViewPrjDoc::CFileSet::GetFuncCount(int nIndex) { ASSERT((nIndex >= -1) && (nIndex < m_arrFuncDesc.GetSize())); if ((nIndex < -1) || (nIndex >= m_arrFuncDesc.GetSize())) return 0; if (nIndex != -1) { CFuncDescFile *pFuncDesc = m_arrFuncDesc.GetAt(nIndex); if (pFuncDesc == NULL) return 0; return pFuncDesc->GetFuncCount(); } return m_arrFuncDesc.GetFuncCount(); } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjDoc commands CFrameWnd *CFuncViewPrjDoc::FindFrame(CRuntimeClass *pFrameClass) { CFrameWnd *pFrame; CView *pView; POSITION pos; pos = GetFirstViewPosition(); while (pos) { pView = GetNextView(pos); if (pView == NULL) continue; pFrame = pView->GetParentFrame(); if (pFrame == NULL) continue; if (pFrame->IsKindOf(pFrameClass)) return pFrame; } return NULL; } CFrameWnd *CFuncViewPrjDoc::CreateFrame(UINT nIDResource, CRuntimeClass *pFrameClass, BOOL bDoInitialUpdate) { CCreateContext context; context.m_pCurrentFrame = NULL; context.m_pCurrentDoc = this; context.m_pNewViewClass = NULL; context.m_pLastView = NULL; context.m_pNewDocTemplate = GetDocTemplate(); CFrameWnd *pFrame = (CFrameWnd*)(pFrameClass->CreateObject()); if (pFrame == NULL) { TRACE1("Warning: Dynamic create of frame %hs failed.\n", pFrameClass->m_lpszClassName); return NULL; } ASSERT_KINDOF(CFrameWnd, pFrame); // create new from resource if (!pFrame->LoadFrame(nIDResource, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, // default frame styles NULL, &context)) { TRACE0("Warning: Couldn't create a frame.\n"); // frame will be deleted in PostNcDestroy cleanup return NULL; } if (bDoInitialUpdate) pFrame->InitialUpdateFrame(this, TRUE); return pFrame; } void CFuncViewPrjDoc::OnViewFuncDiff() { CFrameWnd *pFrame; pFrame = FindFrame(RUNTIME_CLASS(CChildFrame2)); if (pFrame) { // ((CMainFrame*)theApp.m_pMainWnd)->MDIActivate(pFrame); ASSERT_KINDOF(CMDIChildWnd, pFrame); ((CMDIChildWnd*)pFrame)->MDIDestroy(); return; } pFrame = CreateFrame(IDR_FUNCDIFFTYPE, RUNTIME_CLASS(CChildFrame2), FALSE); if (pFrame == NULL) return; CChildFrame2 *pChildFrame = (CChildFrame2 *)pFrame; ASSERT(pChildFrame->m_pLeftFuncList != NULL); ASSERT(pChildFrame->m_pRightFuncList != NULL); if ((pChildFrame->m_pLeftFuncList == NULL) || (pChildFrame->m_pRightFuncList == NULL)) { AfxMessageBox("ERROR : Couldn't locate function list views!", MB_OK | MB_ICONEXCLAMATION); return; } pChildFrame->m_pLeftFuncList->SetFileSetIndex(FVFS_LEFT_FILES); pChildFrame->m_pRightFuncList->SetFileSetIndex(FVFS_RIGHT_FILES); pFrame->InitialUpdateFrame(this, TRUE); } void CFuncViewPrjDoc::OnUpdateViewFuncDiff(CCmdUI* pCmdUI) { CFrameWnd *pFrame = FindFrame(RUNTIME_CLASS(CChildFrame2)); pCmdUI->Enable(!m_bFileOpenInProgress); pCmdUI->SetCheck((pFrame != NULL) ? 1 : 0); } void CFuncViewPrjDoc::OnViewSymbolMap() { CFrameWnd *pFrame; pFrame = FindFrame(RUNTIME_CLASS(CChildFrame3)); if (pFrame) { // ((CMainFrame*)theApp.m_pMainWnd)->MDIActivate(pFrame); ASSERT_KINDOF(CMDIChildWnd, pFrame); ((CMDIChildWnd*)pFrame)->MDIDestroy(); return; } pFrame = CreateFrame(IDR_SYMBOLMAPTYPE, RUNTIME_CLASS(CChildFrame3)); if (pFrame == NULL) return; } void CFuncViewPrjDoc::OnUpdateViewSymbolMap(CCmdUI* pCmdUI) { CFrameWnd *pFrame = FindFrame(RUNTIME_CLASS(CChildFrame3)); pCmdUI->Enable(!m_bFileOpenInProgress); pCmdUI->SetCheck((pFrame != NULL) ? 1 : 0); } void CFuncViewPrjDoc::OnViewOutputWindow() { CFrameWnd *pFrame; pFrame = FindFrame(RUNTIME_CLASS(CChildFrame4)); if (pFrame) { // ((CMainFrame*)theApp.m_pMainWnd)->MDIActivate(pFrame); ASSERT_KINDOF(CMDIChildWnd, pFrame); ((CMDIChildWnd*)pFrame)->MDIDestroy(); return; } pFrame = CreateFrame(IDR_OUTPUTTYPE, RUNTIME_CLASS(CChildFrame4)); if (pFrame == NULL) return; } void CFuncViewPrjDoc::OnUpdateViewOutputWindow(CCmdUI* pCmdUI) { CFrameWnd *pFrame = FindFrame(RUNTIME_CLASS(CChildFrame4)); pCmdUI->Enable(!m_bFileOpenInProgress); pCmdUI->SetCheck((pFrame != NULL) ? 1 : 0); } void CFuncViewPrjDoc::OnViewCompMatrix() { CFrameWnd *pFrame; pFrame = FindFrame(RUNTIME_CLASS(CChildFrame5)); if (pFrame) { // ((CMainFrame*)theApp.m_pMainWnd)->MDIActivate(pFrame); ASSERT_KINDOF(CMDIChildWnd, pFrame); ((CMDIChildWnd*)pFrame)->MDIDestroy(); return; } pFrame = CreateFrame(IDR_COMPMATRIXTYPE, RUNTIME_CLASS(CChildFrame5)); if (pFrame == NULL) return; } void CFuncViewPrjDoc::OnUpdateViewCompMatrix(CCmdUI* pCmdUI) { CFrameWnd *pFrame = FindFrame(RUNTIME_CLASS(CChildFrame5)); pCmdUI->Enable(!m_bFileOpenInProgress); pCmdUI->SetCheck((pFrame != NULL) ? 1 : 0); } void CFuncViewPrjDoc::OnViewCompDiff() { CFrameWnd *pFrame; pFrame = FindFrame(RUNTIME_CLASS(CChildFrame6)); if (pFrame) { // ((CMainFrame*)theApp.m_pMainWnd)->MDIActivate(pFrame); ASSERT_KINDOF(CMDIChildWnd, pFrame); ((CMDIChildWnd*)pFrame)->MDIDestroy(); return; } pFrame = CreateFrame(IDR_COMPDIFFEDITTYPE, RUNTIME_CLASS(CChildFrame6)); if (pFrame == NULL) return; } void CFuncViewPrjDoc::OnUpdateViewCompDiff(CCmdUI* pCmdUI) { CFrameWnd *pFrame = FindFrame(RUNTIME_CLASS(CChildFrame6)); pCmdUI->Enable(!m_bFileOpenInProgress); pCmdUI->SetCheck((pFrame != NULL) ? 1 : 0); } void CFuncViewPrjDoc::UpdateFrameCounts() { CMap<CString, LPCSTR, int, int> nFrames; CMap<CString, LPCSTR, int, int> iFrame; int nTemp; // walk all frames of views (mark and sweep approach) POSITION pos = GetFirstViewPosition(); while (pos != NULL) { CView* pView = GetNextView(pos); ASSERT_VALID(pView); ASSERT(::IsWindow(pView->m_hWnd)); if (pView->IsWindowVisible()) // Do not count invisible windows. { CFrameWnd* pFrame = pView->GetParentFrame(); if (pFrame != NULL) pFrame->m_nWindow = -1; // unknown nFrames.SetAt(pFrame->GetRuntimeClass()->m_lpszClassName, 0); iFrame.SetAt(pFrame->GetRuntimeClass()->m_lpszClassName, 1); } } // now do it again counting the unique ones pos = GetFirstViewPosition(); while (pos != NULL) { CView* pView = GetNextView(pos); ASSERT_VALID(pView); ASSERT(::IsWindow(pView->m_hWnd)); if (pView->IsWindowVisible()) // Do not count invisible windows. { CFrameWnd* pFrame = pView->GetParentFrame(); if (pFrame != NULL && pFrame->m_nWindow == -1) { ASSERT_VALID(pFrame); // not yet counted (give it a 1 based number) nFrames.Lookup(pFrame->GetRuntimeClass()->m_lpszClassName, nTemp); pFrame->m_nWindow = ++nTemp; nFrames.SetAt(pFrame->GetRuntimeClass()->m_lpszClassName, nTemp); } } } // lastly walk the frames and update titles (assume same order) // go through frames updating the appropriate one pos = GetFirstViewPosition(); while (pos != NULL) { CView* pView = GetNextView(pos); ASSERT_VALID(pView); ASSERT(::IsWindow(pView->m_hWnd)); if (pView->IsWindowVisible()) // Do not count invisible windows. { CFrameWnd* pFrame = pView->GetParentFrame(); if (pFrame != NULL) { iFrame.Lookup(pFrame->GetRuntimeClass()->m_lpszClassName, nTemp); if (pFrame->m_nWindow == nTemp) { ASSERT_VALID(pFrame); nFrames.Lookup(pFrame->GetRuntimeClass()->m_lpszClassName, nTemp); if (nTemp == 1) pFrame->m_nWindow = 0; // the only one of its kind pFrame->OnUpdateFrameTitle(TRUE); iFrame.Lookup(pFrame->GetRuntimeClass()->m_lpszClassName, nTemp); iFrame.SetAt(pFrame->GetRuntimeClass()->m_lpszClassName, nTemp + 1); } } } } } void CFuncViewPrjDoc::OnSymbolsReset() { if (AfxMessageBox("Are you sure you want to reset all symbols?", MB_YESNO | MB_ICONQUESTION) != IDYES) return; m_objSymbolMap.FreeAll(); m_mapLeftToRightFunc.RemoveAll(); m_mapRightToLeftFunc.RemoveAll(); m_strCompDiffText = ""; UpdateAllViews(NULL, SYMBOL_MAP_ALL, NULL); // Signal all symbol table UpdateAllViews(NULL, COMP_DIFF_TYPE_BASE, NULL); // Update CompDiffEditViews } void CFuncViewPrjDoc::OnSymbolsExport() { static const char pszFilter[] = "Symbol Files (*.sym)|*.sym|All Files (*.*)|*.*||"; CFileDialog dlg(FALSE, "sym", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST, pszFilter, NULL); if (dlg.DoModal() != IDOK) return; CStdioFile outFile; if (!outFile.Open(dlg.GetPathName(), CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeText)) { AfxMessageBox("Failed to create export file!", MB_OK | MB_ICONEXCLAMATION); return; } CStringArray arrSym; CStringArray arrSymMatch; CDWordArray arrHitCount; DWORD nTotalHitCount; int i,j,k; CString strTemp; CWaitCursor wait; for (i=0; i<4; i++) { switch (i) { case 0: m_objSymbolMap.GetLeftSideCodeSymbolList(arrSym); outFile.WriteString("Left-Side Code Symbols:\n"); break; case 1: m_objSymbolMap.GetLeftSideDataSymbolList(arrSym); outFile.WriteString("\nLeft-Side Data Symbols:\n"); break; case 2: m_objSymbolMap.GetRightSideCodeSymbolList(arrSym); outFile.WriteString("\n\nRight-Side Code Symbols:\n"); break; case 3: m_objSymbolMap.GetRightSideDataSymbolList(arrSym); outFile.WriteString("\nRight-Side Data Symbols:\n"); break; default: continue; } for (j=0; j<arrSym.GetSize(); j++) { switch (i) { case 0: nTotalHitCount = m_objSymbolMap.GetLeftSideCodeHitList(arrSym.GetAt(j), arrSymMatch, arrHitCount); break; case 1: nTotalHitCount = m_objSymbolMap.GetLeftSideDataHitList(arrSym.GetAt(j), arrSymMatch, arrHitCount); break; case 2: nTotalHitCount = m_objSymbolMap.GetRightSideCodeHitList(arrSym.GetAt(j), arrSymMatch, arrHitCount); break; case 3: nTotalHitCount = m_objSymbolMap.GetRightSideDataHitList(arrSym.GetAt(j), arrSymMatch, arrHitCount); break; default: continue; } outFile.WriteString(arrSym.GetAt(j)); ASSERT(arrSymMatch.GetSize() == arrHitCount.GetSize()); // These should have same number of members! for (k=0; k<arrSymMatch.GetSize(); k++) { ASSERT(nTotalHitCount != 0); // Should never have members with no hits! strTemp.Format(",%s,%ld,%f%%", LPCTSTR(arrSymMatch.GetAt(k)), arrHitCount.GetAt(k), ((double)arrHitCount.GetAt(k)/nTotalHitCount)*100); outFile.WriteString(strTemp); } outFile.WriteString("\n"); } } outFile.Close(); } void CFuncViewPrjDoc::OnUpdateSymbolsExport(CCmdUI* pCmdUI) { pCmdUI->Enable(!m_objSymbolMap.IsEmpty()); } void CFuncViewPrjDoc::OnMatrixRebuild() { if (!ReadOrBuildMatrix(FALSE)) { AfxMessageBox("Comparison Matrix Build Failed!", MB_OK | MB_ICONEXCLAMATION); } UpdateAllViews(NULL, MATRIX_TYPE_BASE, NULL); } void CFuncViewPrjDoc::OnMatrixRebuildForce() { if (!ReadOrBuildMatrix(TRUE)) { AfxMessageBox("Comparison Matrix Build Failed!", MB_OK | MB_ICONEXCLAMATION); } UpdateAllViews(NULL, MATRIX_TYPE_BASE, NULL); } void CFuncViewPrjDoc::AddFunctionAssociation(LPCTSTR pszLeftFuncName, LPCTSTR pszRightFuncName) { m_mapLeftToRightFunc.SetAt(pszLeftFuncName, pszRightFuncName); m_mapRightToLeftFunc.SetAt(pszRightFuncName, pszLeftFuncName); } BOOL CFuncViewPrjDoc::LookupLeftFuncAssociation(LPCTSTR pszLeftFuncName, CString &strRightFuncName) { return m_mapLeftToRightFunc.Lookup(pszLeftFuncName, strRightFuncName); } BOOL CFuncViewPrjDoc::LookupRightFuncAssociation(LPCTSTR pszRightFuncName, CString &strLeftFuncName) { return m_mapRightToLeftFunc.Lookup(pszRightFuncName, strLeftFuncName); } <file_sep>/programs/m6811dis/dfc.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* DFC -- DataFileConverter Class This is the C++ DataFileConverter Object Class Header File. Author: <NAME> Date: January 29, 1997 Written in: Borland C++ 4.52 Updated: June 22, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. */ #ifndef DFC_H #define DFC_H #include <iostream> #include <vector> #include "memclass.h" #include "errmsgs.h" #define DFC_FILL_BYTE(abyte) (abyte * 256) enum { DFC_NO_FILL, DFC_ALWAYS_FILL_WITH, DFC_ALWAYS_FILL_WITH_RANDOM, DFC_CONDITIONAL_FILL_WITH, DFC_CONDITIONAL_FILL_WITH_RANDOM }; #define DFC_FILL_TYPE(atype) ((unsigned char) DFC_##atype) #define GET_DFC_FILL_TYPE(afill) ((unsigned char)(afill%256)) #define GET_DFC_FILL_BYTE(afill) ((unsigned char)(afill/256)) #define NO_FILL \ (DFC_FILL_TYPE(NO_FILL)) #define ALWAYS_FILL_WITH(abyte) \ (DFC_FILL_TYPE(ALWAYS_FILL_WITH) | DFC_FILL_BYTE(abyte)) #define ALWAYS_FILL_WITH_RANDOM \ (DFC_FILL_TYPE(ALWAYS_FILL_WITH_RANDOM)) #define CONDITIONAL_FILL_WITH(abyte) \ (DFC_FILL_TYPE(CONDITIONAL_FILL_WITH) | DFC_FILL_BYTE(abyte)) #define CONDITIONAL_FILL_WITH_RANDOM \ (DFC_FILL_TYPE(CONDITIONAL_FILL_WITH_RANDOM)) ///////////////////////////////////////////////////////////////////////////// class CDFCObject { public: // Construction CDFCObject(); virtual ~CDFCObject(); // GetLibraryName: Returns the basic name of the DFC Library, like "Intel", "Binary", etc. virtual std::string GetLibraryName(void) const = 0; // GetShortDescription: Returns the short description of the DFC Library, like "Intel Hex Data File Converter": virtual std::string GetShortDescription(void) const = 0; // GetDescription: Returns a long description of the DFC Library, with more details than short description: virtual std::string GetDescription(void) const = 0; // DefaultExtension: // This function returns a constant character string that represents // the default filename extension for the defined data file type. This // is used by calling programs in open-file dialogs. virtual const char *DefaultExtension(void) const { return "*"; } // RetrieveFileMapping // This is a null function that must be overriden in child Data File Converter // classes. Overriding functions are to read the open BINARY file specified // by 'aFile' and determine the mapping (or range) criteria for the particular // file that is necessary to completely read the file, but including all // breaks that exist in the file. For example, a binary file will set only // the base range mapping and set it to the NewBase with the size equal to the // file length, since the entire file is read at that base. An Intel hex file, // for example, will be searched for each skip in offset and that will start // new range entries. So if an Intel file, for example, has a group at 0000-7FFF, // a group from C000-DFFF and a group from FFD6-FFFF and the NewBase is 10000, // then 3 range entries will be created as: 1) Start: 10000, Size: 8000, // 2) Start 1C000, Size: 2000, and 3) Start: 1FFD6, Size: 2A. // Such a routine is needed when reading an unknown file in, as in a generic // file converter routine. By reading the necessary sizing structure of the // data file, memory can dynamically be allocated to accommodate such a file. // This function returns a '1' if everything was read without problems. A // '0' is returned if a problem was found in determining the range (but a // problem that is non-detrimental). // The following throw backs are performed AND loading is halted as follows: // ERR_CHECKSUM if there is a checksum error encountered during loading. // ERR_UNEXPECTED_EOF if end_of_file is encountered before it was expected. // ERR_OUT_OF_MEMORY if an allocation of a new MemRange entry fails. // virtual int RetrieveFileMapping(std::istream *aFile, unsigned long NewBase, TMemRange *aRange) const; // ReadDataFile: // This is a null function that must be overriden in child Data File Converter // routines. Overriding functions are to read the open BINARY file specified // by 'aFile' into the Memory Class object 'aMemory' with an offset of // 'NewBase'. Files that have addresses specified internally, the internal // addresses are treaded as 'Logical Addresses' in the memory structure. // NewBase too is treaded as a Logical Address, but this can be used to // load a file that really has physical addresses into a special logical // area. For example, a file with internal address for 0x0000-0x7FFF // that needs to be read into logical 0x10000. Just use NewBase=0x10000. // The Memory locations that receive bytes from the loaded file will have // their Descriptor bytes changed to 'aDesc'. This function returns a // '1' if everything was read without problems. A '0' is returned if // a memory location overwrote an existing already loaded location. // The following throw backs are performed AND loading is halted as follows: // ERR_CHECKSUM if there is a checksum error encountered during loading. // ERR_UNEXPECTED_EOF if end_of_file is encountered before it was expected. // ERR_OVERFLOW if an attempt is made to load an address outside the memory bounds. // virtual int ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc) const = 0; // WriteDataFile: // This is a null function that must be overriden in child Data File Converter // routines. Overriding functions are to write the open BINARY file specified // by 'aFile' from the Memory Class object 'aMemory' from the LOGICAL memory // range specified by 'aRange'. If 'UsePhysicalAddr' is non-zero, calls are // made to the Memory object to convert the logical addresses to physical // addresses, and the physical addresses are used in the output file. The // offset 'NewBase' is added to the final address going in the file. Note // that this doesn't apply to children writing an image file that has no // address information (like a binary file). Data written is based on the // validator 'aDesc'. If 'aDesc' is ZERO, ALL data in the specified range // is written. Otherwise, the 'aDesc' is ANDED with EACH descriptor byte from // memory and if the result is non-zero, the data is written. This allows // code to be written separately from data, etc... // The the validator computes as False, then data is actually written or // not written based on the FillMode value, as follows: // 0000 = No filling done on unused bytes -- on Hex files, this // results in a smaller, more compact file. // xx01 = Fill unused bytes with the byte value specified by 'xx'. // This is useful for binary files. (Regardless of type) // 0002 = Fill unused bytes with random values. This is useful for // data fodder. // xx03 = Fill unused bytes with the byte values specified by 'xx' // if and only if datafile type requires padding (such as binary). // 0004 = Fill unused bytes with random values if and only // if datafile type requires padding (such as binary). This // is useful for data fodder. // // Note types 3&4 are equivalent to 1&2 except that the particular DFC // makes the decision as to whether padding is necessary or not. This // allows the calling program to be totally generic in the call, // without having to know (for example) if a file is a binary type // and needs padding or a hex type and doesn't. Hex file types should // not pad on such instances, but binary file types should but only // within the specified range. // // A '1' is returned if everything was successful in the write operation. // The following throw backs are performed AND writing is halted as follows: // ERR_WRITEFAILED if there was an error in while writing to the output file. // ERR_OVERFLOW if a write to a address included file yielded an oversized address. virtual int WriteDataFile(std::ostream *aFile, TMemRange *aRange, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc, int UsePhysicalAddr, unsigned int FillMode) const = 0; }; ///////////////////////////////////////////////////////////////////////////// class CDFCArray : public std::vector<CDFCObject *> { private: CDFCArray(); public: ~CDFCArray(); const CDFCObject *locateDFC(const std::string &strLibraryName) const; static CDFCArray *instance(); }; ///////////////////////////////////////////////////////////////////////////// #endif // DFC_H <file_sep>/programs/funcanal/FuncView/FuncViewPrjVw.h // FuncViewPrjVw.h : interface of the CFuncViewPrjView class // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncViewPrjVw.h,v $ // Revision 1.1 2003/09/13 05:45:45 dewhisna // Initial Revision // // #if !defined(AFX_FUNCVIEWPRJVW_H__D64C9E65_798E_486F_8563_28B4FD7D6EDD__INCLUDED_) #define AFX_FUNCVIEWPRJVW_H__D64C9E65_798E_486F_8563_28B4FD7D6EDD__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CFuncViewPrjDoc; ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjView view class CFuncViewPrjView : public CTreeView { protected: // create from serialization only CFuncViewPrjView(); DECLARE_DYNCREATE(CFuncViewPrjView) // Attributes public: CFuncViewPrjDoc* GetDocument(); protected: HTREEITEM m_hMatrixBaseNode; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFuncViewPrjView) public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // called first time after construct virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); //}}AFX_VIRTUAL // Implementation public: virtual ~CFuncViewPrjView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: void FillFileLists(); void FillMatrixLists(); // Generated message map functions protected: //{{AFX_MSG(CFuncViewPrjView) afx_msg void OnEditClear(); afx_msg void OnUpdateEditClear(CCmdUI* pCmdUI); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in FuncViewPrjVw.cpp inline CFuncViewPrjDoc* CFuncViewPrjView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FUNCVIEWPRJVW_H__D64C9E65_798E_486F_8563_28B4FD7D6EDD__INCLUDED_) <file_sep>/programs/funcanal/FuncView/resource.h //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by FuncView.rc // #define IDD_ABOUTBOX 100 #define CG_IDD_PROGRESS 101 #define CG_IDS_PROGRESS_CAPTION 102 #define IDS_PROGRESS_MATRIX_COMPARE 103 #define IDR_MAINFRAME 128 #define IDR_FUNCVPTYPE 129 #define IDR_FUNCDIFFTYPE 130 #define IDR_SYMBOLMAPTYPE 131 #define IDR_OUTPUTTYPE 132 #define IDR_COMPMATRIXTYPE 133 #define IDR_COMPDIFFEDITTYPE 134 #define CG_IDC_PROGDLG_PROGRESS 1001 #define CG_IDC_PROGDLG_PERCENT 1002 #define CG_IDC_PROGDLG_STATUS 1003 #define ID_VIEW_FUNC_DIFF 32771 #define ID_INDICATOR_MATCH_PERCENT 32772 #define ID_SYMBOLS_ADD 32773 #define ID_SYMBOLS_RESET 32774 #define ID_SYMBOLS_EXPORT 32775 #define ID_VIEW_SYMBOL_MAP 32776 #define ID_VIEW_OUTPUT_WINDOW 32777 #define ID_VIEW_COMP_MATRIX 32778 #define ID_MATRIX_REBUILD 32779 #define ID_MATRIX_REBUILD_FORCE 32780 #define ID_VIEW_COMP_DIFF 32781 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_3D_CONTROLS 1 #define _APS_NEXT_RESOURCE_VALUE 134 #define _APS_NEXT_COMMAND_VALUE 32782 #define _APS_NEXT_CONTROL_VALUE 1004 #define _APS_NEXT_SYMED_VALUE 104 #endif #endif <file_sep>/programs/funcanal/FuncView/FuncView.h // FuncView.h : main header file for the FUNCVIEW application // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncView.h,v $ // Revision 1.1 2003/09/13 05:45:42 dewhisna // Initial Revision // // #if !defined(AFX_FUNCVIEW_H__B8D0CB16_BC1E_4ED0_856D_C48685662F00__INCLUDED_) #define AFX_FUNCVIEW_H__B8D0CB16_BC1E_4ED0_856D_C48685662F00__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CFuncViewApp: // See FuncView.cpp for the implementation of this class // class CFuncViewApp : public CWinApp { public: CFuncViewApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFuncViewApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CFuncViewApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; extern CFuncViewApp theApp; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FUNCVIEW_H__B8D0CB16_BC1E_4ED0_856D_C48685662F00__INCLUDED_) <file_sep>/programs/funcanal/FuncView/FuncDiffEditView.cpp // FuncDiffEditView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncDiffEditView.cpp,v $ // Revision 1.1 2003/09/13 05:45:39 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "FuncViewPrjDoc.h" #include "FuncDiffEditView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFuncDiffEditView IMPLEMENT_DYNCREATE(CFuncDiffEditView, CEditView) CFuncDiffEditView::CFuncDiffEditView() { m_fntEditor.CreatePointFont(100, "Courier New"); m_strMatchPercentage = ""; } CFuncDiffEditView::~CFuncDiffEditView() { } BEGIN_MESSAGE_MAP(CFuncDiffEditView, CEditView) //{{AFX_MSG_MAP(CFuncDiffEditView) ON_COMMAND(ID_SYMBOLS_ADD, OnSymbolsAdd) ON_UPDATE_COMMAND_UI(ID_SYMBOLS_ADD, OnUpdateSymbolsAdd) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFuncDiffEditView diagnostics #ifdef _DEBUG void CFuncDiffEditView::AssertValid() const { CEditView::AssertValid(); } void CFuncDiffEditView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } CFuncViewPrjDoc* CFuncDiffEditView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CFuncDiffEditView message handlers void CFuncDiffEditView::OnInitialUpdate() { CEdit &theEdit = GetEditCtrl(); theEdit.SetFont(&m_fntEditor); theEdit.SetReadOnly(TRUE); CEditView::OnInitialUpdate(); // This calls OnUpdate } void CFuncDiffEditView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; // CEdit &theEdit = GetEditCtrl(); // theEdit.SetWindowText(""); switch (lHint) { case 0: // Normal Update m_LeftFunc.Reset(); m_RightFunc.Reset(); break; case FILESET_TYPE_BASE: // Left function changed m_LeftFunc = *((CFuncViewFuncRef *)pHint); break; case FILESET_TYPE_BASE+1: // Right function changed m_RightFunc = *((CFuncViewFuncRef *)pHint); break; } if ((lHint == 0) || ((lHint >= FILESET_TYPE_BASE) && (lHint <= FILESET_TYPE_LAST))) { DoDiff(); } } void CFuncDiffEditView::DoDiff() { CEdit &theEdit = GetEditCtrl(); if ((m_LeftFunc.m_pFile == NULL) || (m_RightFunc.m_pFile == NULL) || (m_LeftFunc.m_nIndex < 0) || (m_RightFunc.m_nIndex < 0)) { m_strMatchPercentage = ""; theEdit.SetWindowText(""); return; } // double nCompResult = ::CompareFunctions(FCM_DYNPROG_GREEDY, // m_pLeftFunc->m_pFile, m_pLeftFunc->m_nIndex, // m_pRightFunc->m_pFile, m_pRightFunc->m_nIndex, TRUE); CWaitCursor wait; double nCompResult; CString strTemp = ::DiffFunctions(FCM_DYNPROG_GREEDY, m_LeftFunc.m_pFile, m_LeftFunc.m_nIndex, m_RightFunc.m_pFile, m_RightFunc.m_nIndex, OO_NONE, nCompResult); m_strMatchPercentage.Format("Match: %f%%", nCompResult*100); // Convert LF's to CRLF's so editor will display them correctly: CString strTemp2 = ""; int pos; while (!strTemp.IsEmpty()) { pos = strTemp.Find('\n'); if (pos != -1) { strTemp2 += strTemp.Left(pos); strTemp2 += "\r\n"; strTemp = strTemp.Mid(pos+1); } else { strTemp2 += strTemp; strTemp = ""; } } theEdit.SetWindowText(strTemp2); } void CFuncDiffEditView::OnSymbolsAdd() { if ((m_LeftFunc.m_pFile == NULL) || (m_RightFunc.m_pFile == NULL) || (m_LeftFunc.m_nIndex < 0) || (m_RightFunc.m_nIndex < 0)) { return; } CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; CWaitCursor wait; double nCompResult; CSymbolMap &theSymbolMap = pDoc->GetSymbolMap(); CString strTemp; CFuncDesc *pLeftFunc = m_LeftFunc.m_pFile->GetFunc(m_LeftFunc.m_nIndex); CFuncDesc *pRightFunc = m_RightFunc.m_pFile->GetFunc(m_RightFunc.m_nIndex); if ((pLeftFunc != NULL) && (pRightFunc != NULL)) { if (pDoc->LookupLeftFuncAssociation(pLeftFunc->GetMainName(), strTemp)) return; if (pDoc->LookupRightFuncAssociation(pRightFunc->GetMainName(), strTemp)) return; if (!pDoc->GetCompDiffText().IsEmpty()) pDoc->GetCompDiffText() += "\n"; pDoc->GetCompDiffText() += ::DiffFunctions(FCM_DYNPROG_GREEDY, m_LeftFunc.m_pFile, m_LeftFunc.m_nIndex, m_RightFunc.m_pFile, m_RightFunc.m_nIndex, OO_ADD_ADDRESS, nCompResult, &theSymbolMap); pDoc->AddFunctionAssociation(pLeftFunc->GetMainName(), pRightFunc->GetMainName()); } pDoc->UpdateAllViews(this, SYMBOL_MAP_ALL, NULL); pDoc->UpdateAllViews(this, COMP_DIFF_TYPE_BASE, NULL); // Update CompDiffEditViews } void CFuncDiffEditView::OnUpdateSymbolsAdd(CCmdUI* pCmdUI) { if ((m_LeftFunc.m_pFile == NULL) || (m_RightFunc.m_pFile == NULL) || (m_LeftFunc.m_nIndex < 0) || (m_RightFunc.m_nIndex < 0)) { pCmdUI->Enable(FALSE); return; } pCmdUI->Enable(TRUE); } <file_sep>/programs/funcanal/funccomp.h // funccomp.h: interface for the Fuzzy Function Comparison Logic // // $Log: funccomp.h,v $ // Revision 1.2 2003/09/13 05:39:49 dewhisna // Added output options and returning of match percentage to function diff. // // Revision 1.1 2003/02/09 06:59:30 dewhisna // Initial Revision - Split comparison logic from Function File I/O // // #ifndef _FUNCCOMP_H_ #define _FUNCCOMP_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CFuncDescFile; class CSymbolMap; enum FUNC_COMPARE_METHOD { FCM_DYNPROG_XDROP = 0, FCM_DYNPROG_GREEDY = 1 }; // Output Options: // These are OR'd bit fields of output-options used // in diff and CreateOutputLine methods #define OO_NONE 0 #define OO_ADD_ADDRESS 1 double CompareFunctions(FUNC_COMPARE_METHOD nMethod, CFuncDescFile *pFile1, int nFile1FuncNdx, CFuncDescFile *pFile2, int nFile2FuncNdx, BOOL bBuildEditScript); BOOL GetLastEditScript(CStringArray &anArray); CString DiffFunctions(FUNC_COMPARE_METHOD nMethod, CFuncDescFile *pFile1, int nFile1FuncNdx, CFuncDescFile *pFile2, int nFile2FuncNdx, DWORD nOutputOptions, double &nMatchPercent, CSymbolMap *pSymbolMap = NULL); #endif // _FUNCCOMP_H_ <file_sep>/programs/m6811dis/m6811gdc.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // // // M6811GDC -- This is the class definition for the M6811 Disassembler GDC module // #ifndef _M6811GDC_H #define _M6811GDC_H #include "gdc.h" #define OCTL_MASK 0xFF // Mask for our control byte #define MAKEOCTL(d, s) (((d & 0x0F) << 4) | (s & 0x0F)) #define OCTL_SRC (m_CurrentOpcode.m_Control & 0x0F) #define OCTL_DST ((m_CurrentOpcode.m_Control >> 4) & 0x0F) #define OGRP_MASK 0xFF // Mask for our group byte #define MAKEOGRP(d, s) (((d & 0x0F) << 4) | (s & 0x0F)) #define OGRP_SRC (m_CurrentOpcode.m_Group & 0x0F) #define OGRP_DST ((m_CurrentOpcode.m_Group >> 4) & 0x0F) class CM6811Disassembler : public CDisassembler { public: CM6811Disassembler(); virtual unsigned int GetVersionNumber(void); virtual std::string GetGDCLongName(void); virtual std::string GetGDCShortName(void); virtual bool ResolveIndirect(unsigned int nAddress, unsigned int& nResAddress, int nType); virtual std::string GetExcludedPrintChars(void); virtual std::string GetHexDelim(void); virtual std::string GetCommentStartDelim(void); virtual std::string GetCommentEndDelim(void); virtual bool CompleteObjRead(bool bAddLabels = true, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); virtual bool RetrieveIndirect(std::ostream *msgFile = NULL, std::ostream *errFile = NULL); virtual std::string FormatLabel(LABEL_CODE nLC, const std::string & szLabel, unsigned int nAddress); virtual std::string FormatMnemonic(MNEMONIC_CODE nMCCode); virtual std::string FormatOperands(MNEMONIC_CODE nMCCode); virtual std::string FormatComments(MNEMONIC_CODE nMCCode); virtual bool WritePreSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); private: bool MoveOpcodeArgs(unsigned int nGroup); bool DecodeOpcode(unsigned int nGroup, unsigned int nControl, bool bAddLabels, std::ostream *msgFile, std::ostream *errFile); void CreateOperand(unsigned int nGroup, std::string& sOpStr); bool CheckBranchOutside(unsigned int nGroup); std::string LabelDeref2(unsigned int nAddress); std::string LabelDeref4(unsigned int nAddress); unsigned int OpPointer; unsigned int StartPC; int SectionCount; bool CBDef; }; #endif // _M6811GDC_H <file_sep>/programs/funcanal/FuncView/FuncListView.cpp // FuncListView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncListView.cpp,v $ // Revision 1.1 2003/09/13 05:45:40 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "FuncViewPrjDoc.h" #include "FuncListView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFuncListView IMPLEMENT_DYNCREATE(CFuncListView, CListView) CFuncListView::CFuncListView() { m_nFileSet = -1; } CFuncListView::~CFuncListView() { } BEGIN_MESSAGE_MAP(CFuncListView, CListView) //{{AFX_MSG_MAP(CFuncListView) ON_NOTIFY_REFLECT(LVN_ITEMCHANGED, OnItemchanged) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFuncListView diagnostics #ifdef _DEBUG void CFuncListView::AssertValid() const { CListView::AssertValid(); } void CFuncListView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } CFuncViewPrjDoc* CFuncListView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CFuncListView message handlers void CFuncListView::OnInitialUpdate() { CListCtrl &theList = GetListCtrl(); theList.ModifyStyle(0, LVS_NOSORTHEADER | LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS, SWP_NOACTIVATE); theList.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); theList.InsertColumn(0, "Function Name", LVCFMT_LEFT, 100, 0); theList.InsertColumn(1, "Absolute Addr", LVCFMT_RIGHT, 100, 1); // Call the base OnInitialUpdate which will call OnUpdate which will call FillFuncList: CListView::OnInitialUpdate(); } void CFuncListView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; switch (lHint) { case 0: // Normal update FillFuncList(); break; } if ((lHint >= FILESET_TYPE_BASE) && (lHint <= FILESET_TYPE_LAST)) { // FILESET_TYPE_BASE+nFileSet = Document Fileset Function update (pHint = &CFuncViewFuncRef) } if ((lHint >= SYMBOL_MAP_TYPE_BASE) && (lHint <= SYMBOL_MAP_TYPE_LAST)) { // SYMBOL_MAP_TYPE_BASE+nSymbolMapType = Symbol Map update (pHint = &LPCTSTR) } } void CFuncListView::FillFuncList() { CListCtrl &theList = GetListCtrl(); theList.DeleteAllItems(); m_arrFileIndexes.RemoveAll(); m_arrFuncIndexes.RemoveAll(); if (m_nFileSet == -1) return; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; int nFileCount = pDoc->GetFileCount(m_nFileSet); int nFuncCount; int i,j; int ndx, ndx2, ndx3; CFuncDescFile *pFuncDescFile; CFuncDesc *pFunc; CString strTemp; for (i=0; i<nFileCount; i++) { pFuncDescFile = pDoc->GetFuncDescFile(m_nFileSet, i); if (pFuncDescFile == NULL) continue; nFuncCount = pFuncDescFile->GetFuncCount(); for (j=0; j<nFuncCount; j++) { pFunc = pFuncDescFile->GetFunc(j); if (pFunc == NULL) continue; ndx = theList.InsertItem(theList.GetItemCount(), pFunc->GetMainName()); if (ndx == -1) continue; strTemp.Format("0x%04lX", pFunc->GetMainAddress()); theList.SetItemText(ndx, 1, strTemp); ndx2 = m_arrFileIndexes.Add(i); ndx3 = m_arrFuncIndexes.Add(j); ASSERT(ndx2 == ndx3); theList.SetItemData(ndx, ndx2); } } ASSERT(m_arrFileIndexes.GetSize() == m_arrFuncIndexes.GetSize()); } int CFuncListView::GetFileSetIndex() { return m_nFileSet; } void CFuncListView::SetFileSetIndex(int nFileSet) { m_nFileSet = nFileSet; } void CFuncListView::OnItemchanged(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; *pResult = 0; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; CListCtrl &theList = GetListCtrl(); int nSel = theList.GetNextItem(-1, LVNI_SELECTED); CFuncViewFuncRef aRef; if (nSel != -1) { aRef.m_pFile = pDoc->GetFuncDescFile(m_nFileSet, m_arrFileIndexes.GetAt(theList.GetItemData(nSel))); aRef.m_nIndex = m_arrFuncIndexes.GetAt(theList.GetItemData(nSel)); pDoc->UpdateAllViews(this, FILESET_TYPE_BASE + m_nFileSet, &aRef); } else { aRef.m_pFile = NULL; aRef.m_nIndex = -1; pDoc->UpdateAllViews(this, FILESET_TYPE_BASE + m_nFileSet, &aRef); } } <file_sep>/README.md ![m6811dis logo](./programs/doc/6811chip.png) **This repository has been displaced by the newer and more functional [Generic Code-Seeking Diassembler with Fuzzy-Function Analyzer](https://github.com/dewhisna/gendasm), which has all of the same functionality of this disassembler, plus adds other processors (like the AVR family) and has a functioning Fuzzy-Function Analyzer.** Description ----------- The M6811 Code-Seeking Disassembler is a command-line tool that lets you enter known starting vectors for a given code image for the 6811 micro. It will disassemble the code and follow through branches to assist in the separation of code and data. Its companion Fuzzy Function Analyzer uses DNA Sequence Alignment Algorithms to locate similar code in multiple binaries, facilitating reverse-engineering. Originally written to analyze code from GM automotive engine controllers, but is useful anywhere a 6811 micro is being used. Version 1.0 was written in Borland Pascal in April 1996, and updated to v1.2 in June 1999. It was later rewritten to C++ in July 1999 through Jan 2000. While it's been freely available since its creation, it's being released here as an open-source project so the world can better use it as it sees fit. Version 2.0 is completely reworked in 2014 to compile and run with GCC and STL to make it fully portable and accessible to all computer platforms. License ------- M6811DIS Code-Seeking Disassembler Copyright (C) 1996-2015 <NAME>, a.k.a. Dewtronics. Contact: <http://www.dewtronics.com/> <file_sep>/programs/funcanal/FuncView/FuncViewPrjDoc.h // FuncViewPrjDoc.h : interface of the CFuncViewPrjDoc class // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncViewPrjDoc.h,v $ // Revision 1.1 2003/09/13 05:45:44 dewhisna // Initial Revision // // #if !defined(AFX_FUNCVIEWPRJDOC_H__3E867243_733D_48AF_9052_42CDC35AB42F__INCLUDED_) #define AFX_FUNCVIEWPRJDOC_H__3E867243_733D_48AF_9052_42CDC35AB42F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "../funcdesc.h" #define FILESET_TYPE_BASE 1000 #define FILESET_TYPE_LAST 1999 #define SYMBOL_MAP_TYPE_BASE 2000 #define SYMBOL_MAP_ALL 2000 // Used in updating all views with symbol table into #define SYMBOL_MAP_LEFT_CODE 2001 #define SYMBOL_MAP_RIGHT_CODE 2002 #define SYMBOL_MAP_LEFT_DATA 2003 #define SYMBOL_MAP_RIGHT_DATA 2004 #define SYMBOL_MAP_TYPE_LAST 2999 #define MATRIX_TYPE_BASE 3000 #define MATRIX_TYPE_LAST 3999 #define COMP_DIFF_TYPE_BASE 4000 #define COMP_DIFF_TYPE_ALL 4000 #define COMP_DIFF_TYPE_LAST 4999 class CFuncViewFuncRef : public CObject { public: CFuncDescFile *m_pFile; // Pointer to Function Description File int m_nIndex; // Index to a specific function in File CFuncViewFuncRef() { Reset(); } void Reset() { m_pFile = NULL; m_nIndex = -1; } CFuncViewFuncRef& operator=(const CFuncViewFuncRef& aSrc) { m_pFile = aSrc.m_pFile; m_nIndex = aSrc.m_nIndex; return *this; } }; class CFuncViewPrjDoc : public CDocument { protected: // create from serialization only CFuncViewPrjDoc(); DECLARE_DYNCREATE(CFuncViewPrjDoc) // Attributes public: // Operations public: protected: CFrameWnd *FindFrame(CRuntimeClass *pFrameClass); CFrameWnd *CreateFrame(UINT nIDResource, CRuntimeClass *pFrameClass, BOOL bDoInitialUpdate = TRUE); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFuncViewPrjDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); virtual void DeleteContents(); virtual BOOL OnOpenDocument(LPCTSTR lpszPathName); virtual BOOL OnSaveDocument(LPCTSTR lpszPathName); //}}AFX_VIRTUAL // Implementation public: virtual ~CFuncViewPrjDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif virtual void UpdateFrameCounts(); enum FUNC_VIEW_FILE_SETS { FVFS_LEFT_FILES = 0, FVFS_RIGHT_FILES = 1, FVFS_COUNT = 2 // Always set to the number of file set types }; int GetFileSetCount() const { return FVFS_COUNT; } CString GetFileSetDescription(int nFileSet); BOOL AddFile(int nFileSet, LPCTSTR pszFilePathName, CFile *pMsgFile = NULL, CFile *pErrFile = NULL); // Loads and sets a new filename in the specified fileset int FindFile(int nFileSet, LPCTSTR pszFilePathName); // Finds the specified file in the fileset, returning its 0-based index (or -1 if not found) BOOL RemoveFile(int nFileSet, int nIndex); // Unloads and removes the specified file from the specified fileset int GetFileCount(int nFileSet); // Returns the number of files in the specified set CString GetFilePathName(int nFileSet, int nIndex); // Returns the specified file path name CString GetFileName(int nFileSet, int nIndex); // Returns the specified file name CFuncDescFile *GetFuncDescFile(int nFileSet, int nIndex); // Returns the specified function description int GetFuncCount(int nFileSet, int nIndex); // Returns the number of functions in the specified file of the specified fileset or all functions in the set if index is -1 CFuncDesc *GetNextFunction(int nFileSet, int &nFileIndex, int &nFuncIndex); CFuncDesc *GetFileFuncIndexFromLinearIndex(int nFileSet, int nLinearIndex, int &nFileIndex, int &nFuncIndex); // Calculates/sets nFileIndex and nFuncIndex from a linear index and returns pointer to function CSymbolMap &GetSymbolMap() { return m_objSymbolMap; } void AddFunctionAssociation(LPCTSTR pszLeftFuncName, LPCTSTR pszRightFuncName); BOOL LookupLeftFuncAssociation(LPCTSTR pszLeftFuncName, CString &strRightFuncName); BOOL LookupRightFuncAssociation(LPCTSTR pszRightFuncName, CString &strLeftFuncName); CString &GetCompDiffText() { return m_strCompDiffText; } CString &GetOutputText() { return m_strOutputText; } CString GetMatrixPathName(); void SetMatrixPathName(LPCTSTR pszPathName, BOOL bFreeCurrentMatrix); BOOL ReadOrBuildMatrix(BOOL bForceRebuild = FALSE); BOOL HaveMatrix(); int GetMatrixRowCount() { return m_nMatrixRowCount; } int GetMatrixColumnCount() { return m_nMatrixColCount; } double **GetMatrix() { return m_ppnMatrix; } protected: class CFileSet { public: void DeleteContents(); BOOL AddFile(LPCTSTR pszFilePathName, CFile *pMsgFile = NULL, CFile *pErrFile = NULL, LPFUNCANALPROGRESSCALLBACK pfnCallback = NULL, LPARAM lParamCallback = 0); // Loads and sets a new filename int FindFile(LPCTSTR pszFilePathName); // Finds the specified file, returning its 0-based index (or -1 if not found) BOOL RemoveFile(int nIndex); // Unloads and removes the specified file int GetFileCount(); // Returns the number of files CString GetFilePathName(int nIndex); // Returns the specified file path name CString GetFileName(int nIndex); // Returns the specified file name CFuncDescFile *GetFuncDescFile(int nIndex); // Returns the specified function description int GetFuncCount(int nIndex); // Returns the number of functions in the specified file or all files if index is -1 protected: CFuncDescFileArray m_arrFuncDesc; // Function Desc Files } m_arrFileSets[FVFS_COUNT]; CSymbolMap m_objSymbolMap; CMapStringToString m_mapLeftToRightFunc; // Mapping of left-hand to right-hand functions CMapStringToString m_mapRightToLeftFunc; // Mapping of right-hand to left-hand functions CString m_strOutputText; BOOL m_bFileOpenInProgress; BOOL AllocateMatrixMemory(); void FreeMatrixMemory(); CString m_strMatrixPathName; int m_nMatrixRowCount; // Comparison matrix row count (left files) int m_nMatrixColCount; // Comparison matrix col count (right files) double **m_ppnMatrix; // Comparison matrix data CString m_strCompDiffText; private: static BOOL CALLBACK FuncDescFileProgressCallback(int nProgressPos, int nProgressMax, BOOL bAllowCancel, LPARAM lParam); // Generated message map functions protected: //{{AFX_MSG(CFuncViewPrjDoc) afx_msg void OnViewFuncDiff(); afx_msg void OnUpdateViewFuncDiff(CCmdUI* pCmdUI); afx_msg void OnSymbolsReset(); afx_msg void OnViewSymbolMap(); afx_msg void OnUpdateViewSymbolMap(CCmdUI* pCmdUI); afx_msg void OnViewOutputWindow(); afx_msg void OnUpdateViewOutputWindow(CCmdUI* pCmdUI); afx_msg void OnViewCompMatrix(); afx_msg void OnUpdateViewCompMatrix(CCmdUI* pCmdUI); afx_msg void OnMatrixRebuild(); afx_msg void OnMatrixRebuildForce(); afx_msg void OnSymbolsExport(); afx_msg void OnUpdateSymbolsExport(CCmdUI* pCmdUI); afx_msg void OnViewCompDiff(); afx_msg void OnUpdateViewCompDiff(CCmdUI* pCmdUI); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FUNCVIEWPRJDOC_H__3E867243_733D_48AF_9052_42CDC35AB42F__INCLUDED_) <file_sep>/programs/m6811dis/bindfc.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* BINARYDFC -- Binary Data File Converter Class This is the C++ Binary DataFileConverter Object Class Header File. It is a child of the DFC Object class. Author: <NAME> Date: March 7, 1997 Written in: Borland C++ 4.52 Updated: June 23, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. */ #ifndef BINDFC_H #define BINDFC_H #include <iostream> #include "dfc.h" #include "memclass.h" #include "errmsgs.h" class TDFC_Binary : virtual public CDFCObject { public: virtual std::string GetLibraryName(void) const { return "binary"; } virtual std::string GetShortDescription(void) const { return "Binary Data File Converter"; } virtual std::string GetDescription(void) const { return "Binary Data File Converter"; } virtual const char *DefaultExtension(void) const { return "bin"; } virtual int RetrieveFileMapping(std::istream *aFile, unsigned long NewBase, TMemRange *aRange) const; virtual int ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc) const; virtual int WriteDataFile(std::ostream *aFile, TMemRange *aRange, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc, int UsePhysicalAddr, unsigned int FillMode) const; }; #endif // BINDFC_H <file_sep>/programs/funcanal/stdafx.h // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // // $Log: stdafx.h,v $ // Revision 1.1 2002/07/01 05:50:02 dewhisna // Initial Revision // // #if !defined(AFX_STDAFX_H__8A6A4117_76AF_42B3_B639_E6120063A4C6__INCLUDED_) #define AFX_STDAFX_H__8A6A4117_76AF_42B3_B639_E6120063A4C6__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #include <afx.h> //#include <afxwin.h> // MFC core and standard components //#include <afxext.h> // MFC extensions //#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls //#ifndef _AFX_NO_AFXCMN_SUPPORT //#include <afxcmn.h> // MFC support for Windows Common Controls //#endif // _AFX_NO_AFXCMN_SUPPORT // //#include <iostream> #include <math.h> #include <limits.h> #include <float.h> #include <afxtempl.h> // Template Classes #include <afxcoll.h> // Collection Classes #ifdef LINUX #define cprintf printf #include <unistd.h> #else #include <io.h> #include <conio.h> #endif //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STDAFX_H__8A6A4117_76AF_42B3_B639_E6120063A4C6__INCLUDED_) <file_sep>/programs/funcanal/FuncView/SymbolMapListView.cpp // SymbolMapListView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: SymbolMapListView.cpp,v $ // Revision 1.1 2003/09/13 05:45:49 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "SymbolMapListView.h" #include "FuncViewPrjDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSymbolMapListView IMPLEMENT_DYNCREATE(CSymbolMapListView, CListView) CSymbolMapListView::CSymbolMapListView() { } CSymbolMapListView::~CSymbolMapListView() { } BEGIN_MESSAGE_MAP(CSymbolMapListView, CListView) //{{AFX_MSG_MAP(CSymbolMapListView) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSymbolMapListView diagnostics #ifdef _DEBUG void CSymbolMapListView::AssertValid() const { CListView::AssertValid(); } void CSymbolMapListView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } CFuncViewPrjDoc* CSymbolMapListView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSymbolMapListView message handlers void CSymbolMapListView::OnInitialUpdate() { CListCtrl &theList = GetListCtrl(); theList.ModifyStyle(0, LVS_NOSORTHEADER | LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS, SWP_NOACTIVATE); theList.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); theList.InsertColumn(0, "Symbol Name", LVCFMT_LEFT, 200, 0); theList.InsertColumn(1, "Hit Count", LVCFMT_RIGHT, 70, 1); theList.InsertColumn(2, "Hit Percent", LVCFMT_RIGHT, 100, 2); // Call the base OnInitialUpdate which will call OnUpdate which will call FillSymbolMapList: CListView::OnInitialUpdate(); } void CSymbolMapListView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; switch (lHint) { // SYMBOL_MAP_TYPE_BASE+nSymbolMapType = Symbol Map update (pHint = &LPCTSTR) case 0: // Normal update FillSymbolMapList(); break; case SYMBOL_MAP_LEFT_CODE: case SYMBOL_MAP_RIGHT_CODE: case SYMBOL_MAP_LEFT_DATA: case SYMBOL_MAP_RIGHT_DATA: FillSymbolMapList((DWORD)lHint, (LPCTSTR)pHint); break; case SYMBOL_MAP_ALL: // If the whole list changes, clear view FillSymbolMapList(); break; } } void CSymbolMapListView::FillSymbolMapList(DWORD nSource, LPCTSTR pszSymbolName) { CListCtrl &theList = GetListCtrl(); theList.DeleteAllItems(); CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; CHeaderCtrl *pHeader = theList.GetHeaderCtrl(); CString strSymbolName = pszSymbolName; DWORD nTotalHitCount = 0; CStringArray arrSymbols; CDWordArray arrHitCounts; CSymbolMap &theSymbols = pDoc->GetSymbolMap(); CString strHeaderText; switch (nSource) { case SYMBOL_MAP_LEFT_CODE: nTotalHitCount = theSymbols.GetLeftSideCodeHitList(strSymbolName, arrSymbols, arrHitCounts); strHeaderText = "Right-Hand Code Symbol Name"; break; case SYMBOL_MAP_RIGHT_CODE: nTotalHitCount = theSymbols.GetRightSideCodeHitList(strSymbolName, arrSymbols, arrHitCounts); strHeaderText = "Left-Hand Code Symbol Name"; break; case SYMBOL_MAP_LEFT_DATA: nTotalHitCount = theSymbols.GetLeftSideDataHitList(strSymbolName, arrSymbols, arrHitCounts); strHeaderText = "Right-Hand Data Symbol Name"; break; case SYMBOL_MAP_RIGHT_DATA: nTotalHitCount = theSymbols.GetRightSideDataHitList(strSymbolName, arrSymbols, arrHitCounts); strHeaderText = "Left-Hand Data Symbol Name"; break; default: strHeaderText = "Symbol Name"; break; } if (pHeader) { HDITEM theHeader; theHeader.mask = HDI_TEXT; theHeader.pszText = (LPTSTR)LPCTSTR(strHeaderText); theHeader.cchTextMax = strHeaderText.GetLength(); pHeader->SetItem(0, &theHeader); } int ndx; int i; CString strTemp; ASSERT(arrSymbols.GetSize() == arrHitCounts.GetSize()); // These should have same number of members! for (i=0; i<arrSymbols.GetSize(); i++) { ASSERT(nTotalHitCount != 0); // Should never have members with no hits! ndx = theList.InsertItem(i, arrSymbols.GetAt(i)); if (ndx == -1) continue; strTemp.Format("%ld", arrHitCounts.GetAt(i)); theList.SetItemText(i, 1, strTemp); strTemp.Format("%f%%", ((double)arrHitCounts.GetAt(i)/nTotalHitCount)*100); theList.SetItemText(i, 2, strTemp); } } <file_sep>/programs/funcanal/FuncView/StdAfx.cpp // stdafx.cpp : source file that includes just the standard includes // FuncView.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information // // $Log: StdAfx.cpp,v $ // Revision 1.1 2003/09/13 05:45:49 dewhisna // Initial Revision // // #include "stdafx.h" <file_sep>/programs/funcanal/FuncView/ChildFrm5.h // ChildFrm5.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm5.h,v $ // Revision 1.1 2003/09/13 05:45:35 dewhisna // Initial Revision // // #if !defined(AFX_CHILDFRM5_H__BCBE933F_40AB_4822_9B37_535399CF6EBA__INCLUDED_) #define AFX_CHILDFRM5_H__BCBE933F_40AB_4822_9B37_535399CF6EBA__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ChildFrmBase.h" ///////////////////////////////////////////////////////////////////////////// // CChildFrame5 frame class CChildFrame5 : public CChildFrameBase { DECLARE_DYNCREATE(CChildFrame5) protected: CChildFrame5(); // protected constructor used by dynamic creation // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame5) protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation protected: virtual ~CChildFrame5(); // Generated message map functions //{{AFX_MSG(CChildFrame5) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDFRM5_H__BCBE933F_40AB_4822_9B37_535399CF6EBA__INCLUDED_) <file_sep>/programs/funcanal/FuncView/SymbolMapTreeView.h // SymbolMapTreeView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: SymbolMapTreeView.h,v $ // Revision 1.1 2003/09/13 05:45:51 dewhisna // Initial Revision // // #if !defined(AFX_SYMBOLMAPTREEVIEW_H__E57293FF_22E0_47C9_A41F_DAE7161BB334__INCLUDED_) #define AFX_SYMBOLMAPTREEVIEW_H__E57293FF_22E0_47C9_A41F_DAE7161BB334__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CFuncViewPrjDoc; ///////////////////////////////////////////////////////////////////////////// // CSymbolMapTreeView view class CSymbolMapTreeView : public CTreeView { protected: CSymbolMapTreeView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CSymbolMapTreeView) // Attributes public: CFuncViewPrjDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSymbolMapTreeView) public: virtual void OnInitialUpdate(); protected: virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); //}}AFX_VIRTUAL // Implementation protected: virtual ~CSymbolMapTreeView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: void FillSymbolMapList(); void FillSymbolMapSubList(HTREEITEM hParent, CStringArray &aSymbolList, DWORD nItemData); // Generated message map functions protected: //{{AFX_MSG(CSymbolMapTreeView) afx_msg void OnSelchanged(NMHDR* pNMHDR, LRESULT* pResult); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in SymbolMapTreeView.cpp inline CFuncViewPrjDoc* CSymbolMapTreeView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SYMBOLMAPTREEVIEW_H__E57293FF_22E0_47C9_A41F_DAE7161BB334__INCLUDED_) <file_sep>/programs/m6811dis/errmsgs.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* * ERRMSGS * * This file defines the acceptable "exception" messages for * errorcode handling. * * Author: <NAME> * Date: July 20, 1997 * * This file was added as part of the rewrite process. */ #include "errmsgs.h" #include <string> // Preconstruct an out of memory error, cause if we run out of // memory, we may not have enough memory to construct it then. EXCEPTION_ERROR _OUT_OF_MEMORY_EXCEPTION(0, EXCEPTION_ERROR::ERR_OUT_OF_MEMORY, 0, std::string()); EXCEPTION_ERROR::EXCEPTION_ERROR() { delflag = 1; cause = EXCEPTION_ERROR::ERR_NONE; lcode = 0; name_ex.clear(); } EXCEPTION_ERROR::EXCEPTION_ERROR(EXCEPTION_ERROR& anException) { delflag = anException.delflag; cause = anException.cause; lcode = anException.lcode; name_ex = anException.name_ex; } EXCEPTION_ERROR::EXCEPTION_ERROR(int adelflag, const int acause, const unsigned long alcode, const std::string &anexname) { delflag = adelflag; cause = acause; lcode = alcode; name_ex = anexname; } <file_sep>/programs/funcanal/funcanal.cpp // funcanal.cpp : Defines the entry point for the console application. // // $Log: funcanal.cpp,v $ // Revision 1.4 2003/02/09 06:59:55 dewhisna // Split comparison logic from Function File I/O // // Revision 1.3 2003/01/26 06:33:12 dewhisna // Improved usage help // // Revision 1.2 2002/09/15 22:54:01 dewhisna // Added Symbol Table comparison support // // Revision 1.1 2002/07/01 05:49:59 dewhisna // Initial Revision // // #include "stdafx.h" #include "funcanal.h" #include "funcdesc.h" #include <ReadVer.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void main(int argc, char* argv[]) { CProjectRCVersion aVerRC(::GetModuleHandle(NULL)); CString strTemp; int nPos; WORD nVerMajor, nVerMinor; WORD nVerRev, nVerBuild; CStdioFile FuncFile; CStdioFile MatrixInFile; CStdioFile MatrixOutFile; CStdioFile DFROFile; CStdioFile CompFile; CStdioFile OESFile; CStdioFile SymFile; CStdioFile _StdOut(stdout); // Make stdout into a CFile object for passing to parsers BOOL bNeedUsage; BOOL bOkFlag; CFuncDescFile *pFuncDescFileObj; int nReqArgs; int nMinReqInputFiles; int nArgPos; int i,j,k; int nTemp1, nTemp2; int cTemp; double **ppnCompResult; double nMaxCompResult; double nMinCompLimit; FUNC_COMPARE_METHOD nCompMethod; CFuncDescFile *pFuncFile1; CFuncDescFile *pFuncFile2; BOOL bFlag; CStringArray oes; BOOL bCompOESFlag; CSymbolMap aSymbolMap; CFuncDescFileArray m_FuncFiles; CString m_strMatrixInFilename; CString m_strMatrixOutFilename; CString m_strDFROFilename; CString m_strCompFilename; CString m_strOESFilename; CString m_strSymFilename; BOOL m_bForceOverwrite; if (aVerRC.GetInfo(VINFO_PRODUCTVERSION, strTemp)) { nVerRev = 0; nVerBuild = 0; nPos = strTemp.Find(","); if (nPos != -1) { nVerMajor = (WORD)strtoul(strTemp.Left(nPos), NULL, 0); strTemp = strTemp.Mid(nPos+1); nPos = strTemp.Find(","); if (nPos != - 1) { nVerMinor = (WORD)strtoul(strTemp.Left(nPos), NULL, 0); strTemp = strTemp.Mid(nPos+1); nPos = strTemp.Find(","); if (nPos != -1) { nVerRev = (WORD)strtoul(strTemp.Left(nPos), NULL, 0); nVerBuild = (WORD)strtoul(strTemp.Mid(nPos+1), NULL, 0); } else { nVerRev = (WORD)strtoul(strTemp, NULL, 0); } } else { nVerMinor = (WORD)strtoul(strTemp, NULL, 0); } } else { nVerMajor = (WORD)strtoul(strTemp, NULL, 0); nVerMinor = 0; } printf("Disassembler Function Analyzer V%d.%d", nVerMajor, nVerMinor); if (nVerRev) { printf(".%d", nVerRev); } printf(" (build %d)\n", nVerBuild); } else { printf("Disassembler Function Analyzer\n"); } printf("Copyright(c)2002 by <NAME>\n"); printf("\n"); // Setup Defaults: m_strMatrixOutFilename = ""; m_strDFROFilename = ""; m_strCompFilename = ""; m_strOESFilename = ""; m_strSymFilename = ""; m_bForceOverwrite = FALSE; bNeedUsage = FALSE; nReqArgs = 1; // Must have at least program name nMinReqInputFiles = 1; // and one input filename (determine others below) nArgPos = 1; // Start after the program name nMinCompLimit = 0; nCompMethod = FCM_DYNPROG_XDROP; bCompOESFlag = FALSE; while ((nArgPos < argc) && (!bNeedUsage)) { if ((argv[nArgPos][0] == '-') || (argv[nArgPos][0] == '/')) { switch (argv[nArgPos][1]) { case 'm': switch (argv[nArgPos][2]) { case 'i': // Matrix Input File if (!m_strMatrixInFilename.IsEmpty()) { bNeedUsage = TRUE; continue; } if (strlen(argv[nArgPos]) > 3) { nReqArgs += 1; m_strMatrixInFilename = argv[nArgPos] + 3; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { m_strMatrixInFilename = argv[nArgPos]; } else { bNeedUsage = TRUE; } } break; case 'o': // Matrix Output File if (!m_strMatrixOutFilename.IsEmpty()) { bNeedUsage = TRUE; continue; } if (strlen(argv[nArgPos]) > 3) { nReqArgs += 1; m_strMatrixOutFilename = argv[nArgPos] + 3; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { m_strMatrixOutFilename = argv[nArgPos]; } else { bNeedUsage = TRUE; } } nMinReqInputFiles = 2; // Must have 2 input files break; default: bNeedUsage = TRUE; break; } break; case 'd': if (!m_strDFROFilename.IsEmpty()) { bNeedUsage = TRUE; continue; } if (strlen(argv[nArgPos]) > 2) { nReqArgs += 1; m_strDFROFilename = argv[nArgPos] + 2; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { m_strDFROFilename = argv[nArgPos]; } else { bNeedUsage = TRUE; } } break; case 'c': switch (argv[nArgPos][2]) { case 'n': // Normal Diff case 'e': // Normal Diff with OES inline if (!m_strCompFilename.IsEmpty()) { bNeedUsage = TRUE; continue; } if (argv[nArgPos][2] == 'e') bCompOESFlag = TRUE; if (strlen(argv[nArgPos]) > 3) { nReqArgs += 1; m_strCompFilename = argv[nArgPos] + 3; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { m_strCompFilename = argv[nArgPos]; } else { bNeedUsage = TRUE; } } nMinReqInputFiles = 2; // Must have 2 input files break; default: bNeedUsage = TRUE; break; } break; case 'e': if (!m_strOESFilename.IsEmpty()) { bNeedUsage = TRUE; continue; } if (strlen(argv[nArgPos]) > 2) { nReqArgs += 1; m_strOESFilename = argv[nArgPos] + 2; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { m_strOESFilename = argv[nArgPos]; } else { bNeedUsage = TRUE; } } nMinReqInputFiles = 2; // Must have 2 input files break; case 's': if (!m_strSymFilename.IsEmpty()) { bNeedUsage = TRUE; continue; } if (strlen(argv[nArgPos]) > 2) { nReqArgs += 1; m_strSymFilename = argv[nArgPos] + 2; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { m_strSymFilename = argv[nArgPos]; } else { bNeedUsage = TRUE; } } nMinReqInputFiles = 2; // Must have 2 input files break; case 'f': m_bForceOverwrite = TRUE; nReqArgs++; break; case 'l': if (strlen(argv[nArgPos]) > 2) { nReqArgs += 1; nMinCompLimit = atof(argv[nArgPos] + 2)/100; } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { nMinCompLimit = atof(argv[nArgPos])/100; } else { bNeedUsage = TRUE; } } break; case 'a': if (strlen(argv[nArgPos]) > 2) { nReqArgs += 1; nCompMethod = (FUNC_COMPARE_METHOD)strtoul(argv[nArgPos] + 2, NULL, 10); } else { nReqArgs += 2; nArgPos++; if (nArgPos < argc) { nCompMethod = (FUNC_COMPARE_METHOD)strtoul(argv[nArgPos], NULL, 10); } else { bNeedUsage = TRUE; } } switch (nCompMethod) { case FCM_DYNPROG_XDROP: printf("Using Comparison Algorithm: DynProg X-Drop\n\n"); break; case FCM_DYNPROG_GREEDY: printf("Using Comparison Algorithm: DynProg Greedy\n\n"); break; } break; default: bNeedUsage = TRUE; break; } } else { // If we get here and don't have another option, assume rest is filenames // (nArgPos will be pointing to the first filename) break; } nArgPos++; } nReqArgs += nMinReqInputFiles; if ((!m_strMatrixInFilename.IsEmpty()) && (!m_strMatrixOutFilename.IsEmpty())) bNeedUsage = TRUE; if ((m_strMatrixOutFilename.IsEmpty()) && (m_strDFROFilename.IsEmpty()) && (m_strCompFilename.IsEmpty()) && (m_strOESFilename.IsEmpty()) && (m_strSymFilename.IsEmpty())) { fprintf(stderr, "\n\nNothing to do...\n\n"); bNeedUsage = TRUE; } bNeedUsage = bNeedUsage || (argc<nReqArgs); if (bNeedUsage) { printf("Usage:\n"); printf("FuncAnal [-a <alg>] [-f] [-e <oes-fn>] [-s <sym-fn>] [-mi <mtx-fn> | -mo <mtx-fn>] [-d <dro-fn>] [-cn <cmp-fn> | -ce <cmp-fn>] [-l <limit>] <func-fn1> [<func-fn2>]\n"); printf("\n"); printf("Where:\n\n"); printf(" <oes-fn> = Output Optimal Edit Script Filename to generate\n\n"); printf(" <mtx-fn> = Input or Output Filename of a CSV file to read or to generate\n"); printf(" that denotes percentage of function cross-similarity.\n\n"); printf(" <dro-fn> = Output Filename of a file to generate that contains the\n"); printf(" diff-ready version all of the functions from the input file(s)\n\n"); printf(" <cmp-fn> = Output Filename of a file to generate that contains the full\n"); printf(" cross-functional comparisons.\n\n"); printf(" <func-fn1> = Input Filename of the primary functions-definition-file.\n\n"); printf(" <func-fn2> = Input Filename of the secondary functions-definition-file.\n"); printf(" (Optional only if not using -mo, -cX, -e, or -s)\n\n"); printf(" <alg> = Comparison algorithm to use.\n\n"); printf(" <limit> = Lower-Match Limit.\n\n"); printf("\n"); printf("At least one of the following switches must be used:\n"); printf(" -mo <mtx-fn> Perform cross comparison of files and output a matrix of\n"); printf(" percent match (requires 2 input files). Cannot be used\n"); printf(" with the -mi switch.\n\n"); printf(" -d <dro-fn> Dump the functions definition file(s) in Diff-Ready notation\n\n"); printf(" -cn <cmp-fn> Perform cross comparison of files and output a side-by-side\n"); printf(" diff of most similar functions (Normal Output)\n\n"); printf(" -ce <cmp-fn> Perform cross comparison of files and output a side-by-side\n"); printf(" diff of most similar functions (Include inline OES)\n\n"); printf(" -e <oes-fn> Perform cross comparison of files and output an optimal edit\n"); printf(" script file that details the most optimal way of editing the\n"); printf(" left-most file to get the right-most file\n\n"); printf(" -s <sym-fn> Perform cross comparison of files and output a cross-map\n"); printf(" probability based symbol table\n\n"); printf("\n"); printf("The following switches can be specified but are optional:\n"); printf(" -mi <mtx-fn> Reads the specified matrix file to get function cross\n"); printf(" comparison information rather than recalculating it.\n"); printf(" Cannot be used with the -mo switch.\n\n"); printf(" -f Force output file overwrite without prompting\n\n"); printf(" -l <limit> Minimum-Match Limit. This option is only useful with the -cX,\n"); printf(" -e, and -s options and limits output to functions having a\n"); printf(" match percentage greater than or equal to this value. If not\n"); printf(" specified, the minimum required match is anything greater than\n"); printf(" 0%%. This value should be specified as a percentage or\n"); printf(" fraction of a percent. For example: -l 50 matches anything\n"); printf(" 50%% or higher. -l 23.7 matches anything 23.7%% or higher.\n\n"); printf(" -a <alg> Select a specific comparison algorithm to use. Where <alg> is\n"); printf(" one of the following:\n"); printf(" 0 = Dynamic Programming X-Drop Algorithm\n"); printf(" 1 = Dynamic Programming Greedy Algorithm\n"); printf(" If not specified, the X-Drop algorithm will be used.\n\n"); printf("\n"); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } if (!m_strMatrixOutFilename.IsEmpty()) { if ((!m_bForceOverwrite) && (access(m_strMatrixOutFilename, 0) == 0)) { fprintf(stderr, "\nFile \"%s\" exists! -- Overwrite? (y/n): ", LPCTSTR(m_strMatrixOutFilename)); #ifdef LINUX fflush(stdout); cTemp = toupper(getchar()); #else cTemp = toupper(getche()); #endif fprintf(stderr, "\n\n"); if (cTemp != 'Y') { _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if ((access(m_strMatrixOutFilename, 0) == 0) && (access(m_strMatrixOutFilename, 2) != 0)) { fprintf(stderr, "*** Error: Opening \"%s\" for writing...\n\n", LPCTSTR(m_strMatrixOutFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strDFROFilename.IsEmpty()) { if ((!m_bForceOverwrite) && (access(m_strDFROFilename, 0) == 0)) { fprintf(stderr, "\nFile \"%s\" exists! -- Overwrite? (y/n): ", LPCTSTR(m_strDFROFilename)); #ifdef LINUX fflush(stdout); cTemp = toupper(getchar()); #else cTemp = toupper(getche()); #endif fprintf(stderr, "\n\n"); if (cTemp != 'Y') { _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if ((access(m_strDFROFilename, 0) == 0) && (access(m_strDFROFilename, 2)!=0)) { fprintf(stderr, "*** Error: Opening \"%s\" for writing...\n\n", LPCTSTR(m_strDFROFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strCompFilename.IsEmpty()) { if ((!m_bForceOverwrite) && (access(m_strCompFilename, 0) == 0)) { fprintf(stderr, "\nFile \"%s\" exists! -- Overwrite? (y/n): ", LPCTSTR(m_strCompFilename)); #ifdef LINUX fflush(stdout); cTemp = toupper(getchar()); #else cTemp = toupper(getche()); #endif fprintf(stderr, "\n\n"); if (cTemp != 'Y') { _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if ((access(m_strCompFilename, 0) == 0) && (access(m_strCompFilename, 2)!=0)) { fprintf(stderr, "*** Error: Opening \"%s\" for writing...\n\n", LPCTSTR(m_strCompFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strOESFilename.IsEmpty()) { if ((!m_bForceOverwrite) && (access(m_strOESFilename, 0) == 0)) { fprintf(stderr, "\nFile \"%s\" exists! -- Overwrite? (y/n): ", LPCTSTR(m_strOESFilename)); #ifdef LINUX fflush(stdout); cTemp = toupper(getchar()); #else cTemp = toupper(getche()); #endif fprintf(stderr, "\n\n"); if (cTemp != 'Y') { _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if ((access(m_strOESFilename, 0) == 0) && (access(m_strOESFilename, 2)!=0)) { fprintf(stderr, "*** Error: Opening \"%s\" for writing...\n\n", LPCTSTR(m_strOESFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strSymFilename.IsEmpty()) { if ((!m_bForceOverwrite) && (access(m_strSymFilename, 0) == 0)) { fprintf(stderr, "\nFile \"%s\" exists! -- Overwrite? (y/n): ", LPCTSTR(m_strSymFilename)); #ifdef LINUX fflush(stdout); cTemp = toupper(getchar()); #else cTemp = toupper(getche()); #endif fprintf(stderr, "\n\n"); if (cTemp != 'Y') { _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if ((access(m_strSymFilename, 0) == 0) && (access(m_strSymFilename, 2)!=0)) { fprintf(stderr, "*** Error: Opening \"%s\" for writing...\n\n", LPCTSTR(m_strSymFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strMatrixOutFilename.IsEmpty()) { if (!MatrixOutFile.Open(m_strMatrixOutFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::shareExclusive)) { fprintf(stderr, "*** Error: Opening Matrix Output File \"%s\" for writing...\n", LPCTSTR(m_strMatrixOutFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strDFROFilename.IsEmpty()) { if (!DFROFile.Open(m_strDFROFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::shareExclusive)) { fprintf(stderr, "*** Error: Opening Diff-Ready Output File \"%s\" for writing...\n", LPCTSTR(m_strDFROFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strCompFilename.IsEmpty()) { if (!CompFile.Open(m_strCompFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::shareExclusive)) { fprintf(stderr, "*** Error: Opening Compare Output File \"%s\" for writing...\n", LPCTSTR(m_strCompFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strOESFilename.IsEmpty()) { if (!OESFile.Open(m_strOESFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::shareExclusive)) { fprintf(stderr, "*** Error: Opening Optimal Edit Script Output File \"%s\" for writing...\n", LPCTSTR(m_strOESFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } if (!m_strSymFilename.IsEmpty()) { if (!SymFile.Open(m_strSymFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeText | CFile::shareExclusive)) { fprintf(stderr, "*** Error: Opening Symbol Table Output File \"%s\" for writing...\n", LPCTSTR(m_strSymFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } bOkFlag = TRUE; while ((bOkFlag) && (nArgPos < argc)) { pFuncDescFileObj = new CFuncDescFile; if (pFuncDescFileObj == NULL) { fprintf(stderr, "*** Error: Out of Memory or Failure Creating FuncDescFile Object...\n"); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } m_FuncFiles.Add(pFuncDescFileObj); if (!FuncFile.Open(argv[nArgPos], CFile::modeRead | CFile::typeText | CFile::shareDenyWrite)) { fprintf(stderr, "*** Error: Opening Function Definition File \"%s\" for reading...\n", argv[nArgPos]); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } bOkFlag = pFuncDescFileObj->ReadFuncDescFile(FuncFile, &_StdOut, &_StdOut); FuncFile.Close(); nArgPos++; if (!m_strDFROFilename.IsEmpty()) { for (i=0; i<pFuncDescFileObj->GetFuncCount(); i++) { strTemp.Format("File \"%s\" Function \"%s\" (%ld):\n", LPCTSTR(pFuncDescFileObj->GetFuncFileName()), LPCTSTR(pFuncDescFileObj->GetFunc(i)->GetMainName()), i+1); DFROFile.WriteString(strTemp); DFROFile.WriteString(pFuncDescFileObj->GetFunc(i)->ExportToDiff()); DFROFile.WriteString("\n\n"); } } } //m_FuncFiles.CompareFunctions(CFuncDescFileArray::FCM_DYNPROG_GREEDY, 0, 31, 1, 32,TRUE); //_StdOut.m_pStream = NULL; // prevent closing of stdout //return; if ((!m_strMatrixOutFilename.IsEmpty()) || (!m_strCompFilename.IsEmpty()) || (!m_strOESFilename.IsEmpty()) || (!m_strSymFilename.IsEmpty())) { if (m_strMatrixInFilename.IsEmpty()) { printf("Cross-Comparing Functions...\n"); } else { printf("Using specified Cross-Comparison Matrix File: \"%s\"...\n", LPCTSTR(m_strMatrixInFilename)); if (!MatrixInFile.Open(m_strMatrixInFilename, CFile::modeRead | CFile::typeText | CFile::shareDenyWrite)) { fprintf(stderr, "*** Error: Opening Matrix Input File \"%s\" for reading...\n", LPCTSTR(m_strMatrixInFilename)); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } } pFuncFile1 = m_FuncFiles.GetAt(0); pFuncFile2 = m_FuncFiles.GetAt(1); // Allocate Memory: ppnCompResult = new double*[pFuncFile1->GetFuncCount()]; if (ppnCompResult == NULL) { AfxThrowMemoryException(); _StdOut.m_pStream = NULL; // prevent closing of stdout return; } for (i=0; i<pFuncFile1->GetFuncCount(); i++) { ppnCompResult[i] = new double[pFuncFile2->GetFuncCount()]; if (ppnCompResult[i] == NULL) AfxThrowMemoryException(); } if (!m_strMatrixInFilename.IsEmpty()) { // If we have a MatrixIn file, read cross compare info: strTemp = ""; MatrixInFile.ReadString(strTemp); strTemp.TrimLeft(); strTemp.TrimRight(); nPos = strTemp.Find(','); if (nPos != -1) { nTemp1 = atoi(strTemp.Left(nPos)); nTemp2 = atoi(strTemp.Mid(nPos + 1)); } else { nTemp1 = atoi(strTemp); nTemp2 = 0; } if ((nTemp1 != pFuncFile1->GetFuncCount()) || (nTemp2 != pFuncFile2->GetFuncCount())) { fprintf(stderr, "*** Warning: Specified Input Matrix File doesn't match\n"); fprintf(stderr, " the specified function description files. A full\n"); fprintf(stderr, " cross-comparison will be performed!\n\n"); m_strMatrixInFilename.Empty(); } else { MatrixInFile.ReadString(strTemp); // Read and toss x break-points line for (i=0; i<pFuncFile1->GetFuncCount(); i++) { strTemp = ""; MatrixInFile.ReadString(strTemp); strTemp.TrimLeft(); strTemp.TrimRight(); nPos = strTemp.Find(','); strTemp = strTemp.Mid(nPos+1); // Toss y break-point for (j=0; j<pFuncFile2->GetFuncCount(); j++) { nPos = strTemp.Find(','); if (nPos != -1) { ppnCompResult[i][j] = atof(strTemp.Left(nPos)); strTemp = strTemp.Mid(nPos+1); strTemp.TrimLeft(); } else { ppnCompResult[i][j] = atof(strTemp); strTemp = ""; } } } } MatrixInFile.Close(); } if (m_strMatrixInFilename.IsEmpty()) { // If no MatrixIn file was specified, do complete cross comparison: fprintf(stderr, "Please Wait"); if (!m_strMatrixOutFilename.IsEmpty()) { strTemp.Format("%ld,%ld\n", pFuncFile1->GetFuncCount(), pFuncFile2->GetFuncCount()); MatrixOutFile.WriteString(strTemp); for (j=0; j<pFuncFile2->GetFuncCount(); j++) { strTemp.Format(",%ld", j+1); MatrixOutFile.WriteString(strTemp); } } if (!m_strMatrixOutFilename.IsEmpty()) MatrixOutFile.WriteString("\n"); for (i=0; i<pFuncFile1->GetFuncCount(); i++) { fprintf(stderr, "."); if (!m_strMatrixOutFilename.IsEmpty()) { strTemp.Format("%ld", i+1); MatrixOutFile.WriteString(strTemp); } for (j=0; j<pFuncFile2->GetFuncCount(); j++) { ppnCompResult[i][j] = CompareFunctions(nCompMethod, pFuncFile1, i, pFuncFile2, j, FALSE); if (!m_strMatrixOutFilename.IsEmpty()) { strTemp.Format(",%.12g", ppnCompResult[i][j]); MatrixOutFile.WriteString(strTemp); } } if (!m_strMatrixOutFilename.IsEmpty()) MatrixOutFile.WriteString("\n"); } fprintf(stderr, "\n\n"); } printf("\nBest Matches:\n"); if (!m_strCompFilename.IsEmpty()) { CompFile.WriteString("Left Filename : "); CompFile.WriteString(pFuncFile1->GetFuncPathName() + "\n"); CompFile.WriteString("Right Filename : "); CompFile.WriteString(pFuncFile2->GetFuncPathName() + "\n"); CompFile.WriteString("\n"); } if (!m_strOESFilename.IsEmpty()) { OESFile.WriteString("; Left Filename : "); OESFile.WriteString(pFuncFile1->GetFuncPathName() + "\n"); OESFile.WriteString("; Right Filename : "); OESFile.WriteString(pFuncFile2->GetFuncPathName() + "\n"); } if (!m_strSymFilename.IsEmpty()) { SymFile.WriteString("; Left Filename : "); SymFile.WriteString(pFuncFile1->GetFuncPathName() + "\n"); SymFile.WriteString("; Right Filename : "); SymFile.WriteString(pFuncFile2->GetFuncPathName() + "\n"); } aSymbolMap.FreeAll(); for (i=0; i<pFuncFile1->GetFuncCount(); i++) { nMaxCompResult = 0; for (j=0; j<pFuncFile2->GetFuncCount(); j++) nMaxCompResult = __max(nMaxCompResult, ppnCompResult[i][j]); bFlag = FALSE; if ((nMaxCompResult > 0) && (nMaxCompResult >= nMinCompLimit)) { printf(" %s : ", LPCTSTR(PadString(pFuncFile1->GetFunc(i)->GetMainName(), CFuncObject::GetFieldWidth(CFuncObject::FC_LABEL)))); for (j=0; j<pFuncFile2->GetFuncCount(); j++) { if (ppnCompResult[i][j] < nMaxCompResult) continue; if (bFlag) { if (!m_strCompFilename.IsEmpty()) { CompFile.WriteString("\n\n"); } printf(", "); } else { if (!m_strCompFilename.IsEmpty()) { CompFile.WriteString("================================================================================\n"); } } bFlag = TRUE; printf("%s", LPCTSTR(pFuncFile2->GetFunc(j)->GetMainName())); if (!m_strCompFilename.IsEmpty()) { CompFile.WriteString("--------------------------------------------------------------------------------\n"); strTemp.Format(" Left Function : %s (%ld)\n Right Function : %s (%ld)\n Matches by : %f%%\n", LPCTSTR(pFuncFile1->GetFunc(i)->GetMainName()), i+1, LPCTSTR(pFuncFile2->GetFunc(j)->GetMainName()), j+1, ppnCompResult[i][j]*100); CompFile.WriteString(strTemp); CompFile.WriteString("--------------------------------------------------------------------------------\n"); strTemp = DiffFunctions(nCompMethod, pFuncFile1, i, pFuncFile2, j, &aSymbolMap); if (bCompOESFlag) { if (GetLastEditScript(oes)) { for (k=0; k<oes.GetSize(); k++) { CompFile.WriteString(oes.GetAt(k) + "\n"); } } CompFile.WriteString("--------------------------------------------------------------------------------\n"); } CompFile.WriteString(strTemp); CompFile.WriteString("--------------------------------------------------------------------------------\n"); } if (!m_strOESFilename.IsEmpty()) { CompareFunctions(nCompMethod, pFuncFile1, i, pFuncFile2, j, TRUE); if (GetLastEditScript(oes)) { OESFile.WriteString("\n"); strTemp.Format("@%s(%ld)|%s(%ld)\n", LPCTSTR(pFuncFile1->GetFunc(i)->GetMainName()), i+1, LPCTSTR(pFuncFile2->GetFunc(j)->GetMainName()), j+1); OESFile.WriteString(strTemp); for (k=0; k<oes.GetSize(); k++) { OESFile.WriteString(oes.GetAt(k) + "\n"); } } } } if (!m_strCompFilename.IsEmpty()) { CompFile.WriteString("================================================================================\n\n\n"); } printf(" : (%f%%)", nMaxCompResult * 100); printf("\n"); } } printf("\nFunctions in \"%s\" with No Matches:\n", LPCTSTR(pFuncFile1->GetFuncPathName())); bFlag = TRUE; for (i=0; i<pFuncFile1->GetFuncCount(); i++) { nMaxCompResult = 0; for (j=0; j<pFuncFile2->GetFuncCount(); j++) nMaxCompResult = __max(nMaxCompResult, ppnCompResult[i][j]); if ((nMaxCompResult <= 0) || (nMaxCompResult < nMinCompLimit)) { printf(" %s\n", LPCTSTR(pFuncFile1->GetFunc(i)->GetMainName())); bFlag = FALSE; } } if (bFlag) printf(" <None>\n"); printf("\nFunctions in \"%s\" with No Matches:\n", LPCTSTR(pFuncFile2->GetFuncPathName())); bFlag = TRUE; for (j=0; j<pFuncFile2->GetFuncCount(); j++) { nMaxCompResult = 0; for (i=0; i<pFuncFile1->GetFuncCount(); i++) nMaxCompResult = __max(nMaxCompResult, ppnCompResult[i][j]); if ((nMaxCompResult <= 0) || (nMaxCompResult < nMinCompLimit)) { printf(" %s\n", LPCTSTR(pFuncFile2->GetFunc(j)->GetMainName())); bFlag = FALSE; } } if (bFlag) printf(" <None>\n"); // Dump Symbol Tables: CStringArray arrSymbolList; CStringArray arrHitList; CDWordArray arrHitCount; DWORD nTotalHits; int nSymWidth; printf("\nCross-Comparing Symbol Tables...\n"); printf("\nLeft-Side Code Symbol Matches:\n"); printf("------------------------------\n"); if (!m_strSymFilename.IsEmpty()) { SymFile.WriteString("\nLeft-Side Code Symbol Matches:\n"); SymFile.WriteString("------------------------------\n"); } aSymbolMap.GetLeftSideCodeSymbolList(arrSymbolList); nSymWidth = 0; for (i=0; i<arrSymbolList.GetSize(); i++) { if (arrSymbolList.GetAt(i).GetLength() > nSymWidth) nSymWidth = arrSymbolList.GetAt(i).GetLength(); } for (i=0; i<arrSymbolList.GetSize(); i++) { nTotalHits = aSymbolMap.GetLeftSideCodeHitList(arrSymbolList.GetAt(i), arrHitList, arrHitCount); ASSERT(arrHitList.GetSize() == arrHitCount.GetSize()); strTemp = arrSymbolList.GetAt(i); for (j=0; j<(nSymWidth-arrSymbolList.GetAt(i).GetLength()); j++) strTemp += ' '; printf("%s : ", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp + " : "); if (arrHitList.GetSize() > 0) { if (nTotalHits == 0) nTotalHits = 1; // Safe-guard for divide by zero for (j=0; j<arrHitList.GetSize(); j++) { if (arrHitList.GetAt(j).IsEmpty()) arrHitList.SetAt(j, "???"); strTemp.Format("%s%s (%f%%)", ((j!=0) ? ", " : ""), LPCTSTR(arrHitList.GetAt(j)), ((double)arrHitCount.GetAt(j)/nTotalHits)*100); printf("%s", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp); } printf("\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("\n"); } else { printf("<none>\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("<none>\n"); } } printf("\nLeft-Side Data Symbol Matches:\n"); printf("------------------------------\n"); if (!m_strSymFilename.IsEmpty()) { SymFile.WriteString("\nLeft-Side Data Symbol Matches:\n"); SymFile.WriteString("------------------------------\n"); } aSymbolMap.GetLeftSideDataSymbolList(arrSymbolList); nSymWidth = 0; for (i=0; i<arrSymbolList.GetSize(); i++) { if (arrSymbolList.GetAt(i).GetLength() > nSymWidth) nSymWidth = arrSymbolList.GetAt(i).GetLength(); } for (i=0; i<arrSymbolList.GetSize(); i++) { nTotalHits = aSymbolMap.GetLeftSideDataHitList(arrSymbolList.GetAt(i), arrHitList, arrHitCount); ASSERT(arrHitList.GetSize() == arrHitCount.GetSize()); strTemp = arrSymbolList.GetAt(i); for (j=0; j<(nSymWidth-arrSymbolList.GetAt(i).GetLength()); j++) strTemp += ' '; printf("%s : ", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp + " : "); if (arrHitList.GetSize() > 0) { if (nTotalHits == 0) nTotalHits = 1; // Safe-guard for divide by zero for (j=0; j<arrHitList.GetSize(); j++) { if (arrHitList.GetAt(j).IsEmpty()) arrHitList.SetAt(j, "???"); strTemp.Format("%s%s (%f%%)", ((j!=0) ? ", " : ""), LPCTSTR(arrHitList.GetAt(j)), ((double)arrHitCount.GetAt(j)/nTotalHits)*100); printf("%s", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp); } printf("\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("\n"); } else { printf("<none>\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("<none>\n"); } } printf("\nRight-Side Code Symbol Matches:\n"); printf("-------------------------------\n"); if (!m_strSymFilename.IsEmpty()) { SymFile.WriteString("\nRight-Side Code Symbol Matches:\n"); SymFile.WriteString("-------------------------------\n"); } aSymbolMap.GetRightSideCodeSymbolList(arrSymbolList); nSymWidth = 0; for (i=0; i<arrSymbolList.GetSize(); i++) { if (arrSymbolList.GetAt(i).GetLength() > nSymWidth) nSymWidth = arrSymbolList.GetAt(i).GetLength(); } for (i=0; i<arrSymbolList.GetSize(); i++) { nTotalHits = aSymbolMap.GetRightSideCodeHitList(arrSymbolList.GetAt(i), arrHitList, arrHitCount); ASSERT(arrHitList.GetSize() == arrHitCount.GetSize()); strTemp = arrSymbolList.GetAt(i); for (j=0; j<(nSymWidth-arrSymbolList.GetAt(i).GetLength()); j++) strTemp += ' '; printf("%s : ", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp + " : "); if (arrHitList.GetSize() > 0) { if (nTotalHits == 0) nTotalHits = 1; // Safe-guard for divide by zero for (j=0; j<arrHitList.GetSize(); j++) { if (arrHitList.GetAt(j).IsEmpty()) arrHitList.SetAt(j, "???"); strTemp.Format("%s%s (%f%%)", ((j!=0) ? ", " : ""), LPCTSTR(arrHitList.GetAt(j)), ((double)arrHitCount.GetAt(j)/nTotalHits)*100); printf("%s", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp); } printf("\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("\n"); } else { printf("<none>\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("<none>\n"); } } printf("\nRight-Side Data Symbol Matches:\n"); printf("-------------------------------\n"); if (!m_strSymFilename.IsEmpty()) { SymFile.WriteString("\nRight-Side Data Symbol Matches:\n"); SymFile.WriteString("-------------------------------\n"); } aSymbolMap.GetRightSideDataSymbolList(arrSymbolList); nSymWidth = 0; for (i=0; i<arrSymbolList.GetSize(); i++) { if (arrSymbolList.GetAt(i).GetLength() > nSymWidth) nSymWidth = arrSymbolList.GetAt(i).GetLength(); } for (i=0; i<arrSymbolList.GetSize(); i++) { nTotalHits = aSymbolMap.GetRightSideDataHitList(arrSymbolList.GetAt(i), arrHitList, arrHitCount); ASSERT(arrHitList.GetSize() == arrHitCount.GetSize()); strTemp = arrSymbolList.GetAt(i); for (j=0; j<(nSymWidth-arrSymbolList.GetAt(i).GetLength()); j++) strTemp += ' '; printf("%s : ", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp + " : "); if (arrHitList.GetSize() > 0) { if (nTotalHits == 0) nTotalHits = 1; // Safe-guard for divide by zero for (j=0; j<arrHitList.GetSize(); j++) { if (arrHitList.GetAt(j).IsEmpty()) arrHitList.SetAt(j, "???"); strTemp.Format("%s%s (%f%%)", ((j!=0) ? ", " : ""), LPCTSTR(arrHitList.GetAt(j)), ((double)arrHitCount.GetAt(j)/nTotalHits)*100); printf("%s", LPCTSTR(strTemp)); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString(strTemp); } printf("\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("\n"); } else { printf("<none>\n"); if (!m_strSymFilename.IsEmpty()) SymFile.WriteString("<none>\n"); } } // Deallocate Memory: for (i=0; i<pFuncFile1->GetFuncCount(); i++) delete[] (ppnCompResult[i]); delete[] ppnCompResult; } printf("\nFunction Analysis Complete...\n\n"); if (!m_strMatrixOutFilename.IsEmpty()) MatrixOutFile.Close(); if (!m_strDFROFilename.IsEmpty()) DFROFile.Close(); if (!m_strCompFilename.IsEmpty()) CompFile.Close(); if (!m_strOESFilename.IsEmpty()) OESFile.Close(); if (!m_strSymFilename.IsEmpty()) SymFile.Close(); _StdOut.m_pStream = NULL; // prevent closing of stdout } <file_sep>/programs/funcanal/FuncView/CompDiffEditView.cpp // CompDiffEditView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: CompDiffEditView.cpp,v $ // Revision 1.1 2003/09/13 05:45:37 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "FuncViewPrjDoc.h" #include "CompDiffEditView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCompDiffEditView IMPLEMENT_DYNCREATE(CCompDiffEditView, CEditView) CCompDiffEditView::CCompDiffEditView() { m_fntEditor.CreatePointFont(100, "Courier New"); } CCompDiffEditView::~CCompDiffEditView() { } BEGIN_MESSAGE_MAP(CCompDiffEditView, CEditView) //{{AFX_MSG_MAP(CCompDiffEditView) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCompDiffEditView diagnostics #ifdef _DEBUG void CCompDiffEditView::AssertValid() const { CEditView::AssertValid(); } void CCompDiffEditView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } CFuncViewPrjDoc* CCompDiffEditView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CCompDiffEditView message handlers void CCompDiffEditView::OnInitialUpdate() { CEdit &theEdit = GetEditCtrl(); theEdit.SetFont(&m_fntEditor); theEdit.SetReadOnly(TRUE); CEditView::OnInitialUpdate(); // This calls OnUpdate } void CCompDiffEditView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; CEdit &theEdit = GetEditCtrl(); CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) { theEdit.SetWindowText(""); return; } if ((lHint == 0) || ((lHint >= COMP_DIFF_TYPE_BASE) && (lHint <= COMP_DIFF_TYPE_LAST))) { // Convert LF's to CRLF's so editor will display them correctly: CString strTemp = pDoc->GetCompDiffText(); CString strTemp2 = ""; int pos; while (!strTemp.IsEmpty()) { pos = strTemp.Find('\n'); if (pos != -1) { strTemp2 += strTemp.Left(pos); strTemp2 += "\r\n"; strTemp = strTemp.Mid(pos+1); } else { strTemp2 += strTemp; strTemp = ""; } } theEdit.SetWindowText(strTemp2); } } <file_sep>/programs/m6811dis/m6811dis.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // // // Header for M6811DIS // #ifndef _M6811DIS_H_ #define _M6811DIS_H_ #endif // _M6811DIS_H_ <file_sep>/programs/funcanal/FuncView/ChildFrm3.cpp // ChildFrm3.cpp : implementation file // // Frame Window for the Symbol Map Views // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm3.cpp,v $ // Revision 1.1 2003/09/13 05:45:33 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ChildFrm3.h" #include "SymbolMapTreeView.h" #include "SymbolMapListView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrame3 IMPLEMENT_DYNCREATE(CChildFrame3, CChildFrameBase) CChildFrame3::CChildFrame3() { } CChildFrame3::~CChildFrame3() { } BEGIN_MESSAGE_MAP(CChildFrame3, CChildFrameBase) //{{AFX_MSG_MAP(CChildFrame3) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame3 message handlers BOOL CChildFrame3::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { if (!m_wndSplitter.CreateStatic(this, 1, 2)) return FALSE; if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CSymbolMapTreeView), CSize(300, 0), pContext)) return FALSE; if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CSymbolMapListView), CSize(300, 0), pContext)) return FALSE; return TRUE; // return CChildFrameBase::OnCreateClient(lpcs, pContext); } <file_sep>/programs/m6811dis/m6811gdc.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // // // M6811GDC -- This is the implementation for the M6811 Disassembler GDC module // // // Groups: (Grp) : xy // Where x (msnb = destination = FIRST operand) // y (lsnb = source = LAST operand) // // 0 = opcode only, nothing follows // 1 = 8-bit absolute address follows only // 2 = 16-bit absolute address follows only // 3 = 8-bit relative address follows only // 4 = 16-bit relative address follows only (Not used on HC11) // 5 = 8-bit data follows only // 6 = 16-bit data follows only // 7 = 8-bit absolute address followed by 8-bit mask // 8 = 8-bit X offset address followed by 8-bit mask // 9 = 8-bit Y offset address followed by 8-bit mask // A = 8-bit X offset address // B = 8-bit Y offset address // // Control: (Algorithm control) : xy // Where x (msnb = destination = FIRST operand) // y (lsnb = source = LAST operand) // // 0 = Disassemble as code // // 1 = Disassemble as code, with data addr label // (on opcodes with post-byte, label generation is dependent upon post-byte value.) // // 2 = Disassemble as undeterminable branch address (Comment code) // // 3 = Disassemble as determinable branch, add branch addr and label // // 4 = Disassemble as conditionally undeterminable branch address (Comment code), // with data addr label, (on opcodes with post-byte, label generation is dependent // upon post-byte value. conditional upon post-byte) // // This version setup for compatibility with the AS6811 assembler // // // Format of Function Output File: // // Any line beginning with a ";" is considered to be a commment line and is ignored // // Memory Mapping: // #type|addr|size // | | |____ Size of Mapped area (hex) // | |_________ Absolute Address of Mapped area (hex) // |______________ Type of Mapped area (One of following: ROM, RAM, IO) // // Label Definitions: // !addr|label // | |____ Label(s) for this address(comma separated) // |_________ Absolute Address (hex) // // Start of New Function: // @xxxx|name // | |____ Name(s) of Function (comma separated list) // |_________ Absolute Address of Function Start relative to overall file (hex) // // Mnemonic Line (inside function): // xxxx|xxxx|label|xxxxxxxxxx|xxxxxx|xxxx|DST|SRC|mnemonic|operands // | | | | | | | | | |____ Disassembled operand output (ascii) // | | | | | | | | |_____________ Disassembled mnemonic (ascii) // | | | | | | |___|___________________ See below for SRC/DST format // | | | | | |___________________________ Addressing/Data bytes from operand portion of instruction (hex) // | | | | |_________________________________ Opcode bytes from instruction (hex) // | | | |__________________________________________ All bytes from instruction (hex) // | | |___________________________________________________ Label(s) for this address (comma separated list) // | |________________________________________________________ Absolute address of instruction (hex) // |_____________________________________________________________ Relative address of instruction to the function (hex) // // Data Byte Line (inside function): // xxxx|xxxx|label|xx // | | | |____ Data Byte (hex) // | | |_________ Label(s) for this address (comma separated) // | |______________ Absolute address of data byte (hex) // |___________________ Relative address of data byte to the function (hex) // // SRC and DST entries: // #xxxx Immediate Data Value (xxxx=hex value) // C@xxxx Absolute Code Address (xxxx=hex address) // C^n(xxxx) Relative Code Address (n=signed offset in hex, xxxx=resolved absolute address in hex) // C&xx(r) Register Code Offset (xx=hex offset, r=register number or name), ex: jmp 2,x -> "C$02(x)" // D@xxxx Absolute Data Address (xxxx=hex address) // D^n(xxxx) Relative Data Address (n=signed offset in hex, xxxx=resolved absolute address in hex) // D&xx(r) Register Data Offset (xx=hex offset, r=register number or name), ex: ldaa 1,y -> "D$01(y)" // // If any of the above also includes a mask, then the following will be added: // ,Mxx Value mask (xx=hex mask value) // // Note: The address sizes are consistent with the particular process. For example, an HC11 will // use 16-bit addresses (or 4 hex digits). The size of immediate data entries, offsets, and masks will // reflect the actual value. A 16-bit immediate value, offset, or mask, will be outputted as 4 hex // digits, but an 8-bit immediate value, offset, or mask, will be outputted as only 2 hex digits. // #include "m6811gdc.h" #include "gdc.h" #include "stringhelp.h" #include <sstream> #include <cstdio> #include <assert.h> #define DataDelim "'" // Specify ' as delimiter for data literals #define LblcDelim ":" // Delimiter between labels and code #define LbleDelim "" // Delimiter between labels and equates #define ComDelimS ";" // Comment Start delimiter #define ComDelimE "" // Comment End delimiter #define HexDelim "0x" // Hex. delimiter #define VERSION 0x200 // M6811 Disassembler Version number 2.00 // ---------------------------------------------------------------------------- // CM6811Disassembler // ---------------------------------------------------------------------------- CM6811Disassembler::CM6811Disassembler() : CDisassembler() { // = ((NBytes: 0; OpCode: (0, 0); Grp: 0; Control: 1; Mnemonic: '???'), m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x00", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "test")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x01", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "nop")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x02", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "idiv")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x03", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "fdiv")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x04", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "lsrd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x05", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "lsld")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x06", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tap")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x07", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tpa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x08", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "inx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x09", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "dex")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x0A", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "clv")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x0B", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "sev")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x0C", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "clc")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x0D", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "sec")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x0E", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "cli")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x0F", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "sei")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x10", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "sba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x11", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "cba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x12", MAKEOGRP(0x7, 0x3), MAKEOCTL(0x1, 0x3), "brset")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x13", MAKEOGRP(0x7, 0x3), MAKEOCTL(0x1, 0x3), "brclr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x14", MAKEOGRP(0x0, 0x7), MAKEOCTL(0x0, 0x1), "bset")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x15", MAKEOGRP(0x0, 0x7), MAKEOCTL(0x0, 0x1), "bclr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x16", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x17", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tba")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x08", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "iny")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x09", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "dey")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x1C", MAKEOGRP(0x0, 0x9), MAKEOCTL(0x0, 0x0), "bset")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x1D", MAKEOGRP(0x0, 0x9), MAKEOCTL(0x0, 0x0), "bclr")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x1E", MAKEOGRP(0x9, 0x3), MAKEOCTL(0x0, 0x3), "brset")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x1F", MAKEOGRP(0x9, 0x3), MAKEOCTL(0x0, 0x3), "brclr")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x30", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tsy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x35", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tys")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x38", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "puly")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x3A", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "aby")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x3C", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "pshy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x60", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "neg")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x63", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "com")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x64", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "lsr")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x66", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "ror")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x67", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "asr")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x68", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "lsl")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x69", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "rol")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x6A", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "dec")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x6C", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "inc")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x6D", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "tst")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x6E", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x2) | OCTL_STOP, "jmp")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x6F", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "clr")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x8C", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "cpy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x8F", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "xgdy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\x9C", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "cpy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA0", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "suba")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA1", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "cmpa")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA2", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "sbca")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA3", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "subd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA4", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "anda")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA5", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "bita")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA6", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "ldaa")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA7", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "staa")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA8", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "eora")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xA9", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "adca")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xAA", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "oraa")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xAB", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "adda")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xAC", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "cpy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xAD", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x2), "jsr")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xAE", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "lds")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xAF", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "sts")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xBC", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "cpy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xCE", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "ldy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xDE", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "ldy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xDF", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "sty")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE0", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "subb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE1", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "cmpb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE2", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "sbcb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE3", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "addd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE4", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "andb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE5", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "bitb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE6", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "ldab")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE7", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "stab")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE8", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "eorb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xE9", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "adcb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xEA", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "orab")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xEB", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "addb")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xEC", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "ldd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xED", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "std")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xEE", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "ldy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xEF", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "sty")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xFE", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "ldy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x18\xFF", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "sty")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x19", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "daa")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\x83", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "cpd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\x93", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "cpd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\xA3", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "cpd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\xAC", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "cpy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\xB3", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "cpd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\xEE", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "ldy")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\x1A\xEF", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "sty")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x1B", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "aba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x1C", MAKEOGRP(0x0, 0x8), MAKEOCTL(0x0, 0x0), "bset")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x1D", MAKEOGRP(0x0, 0x8), MAKEOCTL(0x0, 0x0), "bclr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x1E", MAKEOGRP(0x8, 0x3), MAKEOCTL(0x0, 0x3), "brset")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x1F", MAKEOGRP(0x8, 0x3), MAKEOCTL(0x0, 0x3), "brclr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x20", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3) | OCTL_STOP, "bra")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x21", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "brn")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x22", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bhi")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x23", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bls")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x24", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bcc")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x25", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bcs")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x26", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bne")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x27", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "beq")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x28", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bvc")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x29", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bvs")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x2A", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bpl")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x2B", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bmi")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x2C", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bge")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x2D", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "blt")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x2E", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bgt")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x2F", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "ble")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x30", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tsx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x31", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "ins")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x32", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "pula")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x33", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "pulb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x34", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "des")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x35", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "txs")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x36", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "psha")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x37", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "pshb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x38", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "pulx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x39", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0) | OCTL_STOP, "rts")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x3A", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "abx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x3B", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0) | OCTL_STOP, "rti")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x3C", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "pshx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x3D", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "mul")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x3E", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "wai")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x3F", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "swi")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x40", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "nega")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x43", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "coma")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x44", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "lsra")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x46", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "rora")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x47", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "asra")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x48", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "lsla")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x49", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "rola")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x4A", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "deca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x4C", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "inca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x4D", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tsta")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x4F", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "clra")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x50", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "negb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x53", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "comb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x54", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "lsrb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x56", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "rorb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x57", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "asrb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x58", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "lslb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x59", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "rolb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x5A", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "decb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x5C", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "incb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x5D", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "tstb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x5F", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "clrb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x60", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "neg")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x63", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "com")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x64", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "lsr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x66", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "ror")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x67", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "asr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x68", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "lsl")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x69", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "rol")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x6A", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "dec")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x6C", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "inc")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x6D", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "tst")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x6E", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x2) | OCTL_STOP, "jmp")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x6F", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "clr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x70", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "neg")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x73", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "com")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x74", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "lsr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x76", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "ror")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x77", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "asr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x78", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "lsl")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x79", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "rol")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x7A", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "dec")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x7C", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "inc")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x7D", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "tst")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x7E", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x3) | OCTL_STOP, "jmp")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x7F", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "clr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x80", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "suba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x81", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "cmpa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x82", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "sbca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x83", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "subd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x84", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "anda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x85", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "bita")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x86", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "ldaa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x88", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "eora")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x89", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "adca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x8A", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "oraa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x8B", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "adda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x8C", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "cpx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x8D", MAKEOGRP(0x0, 0x3), MAKEOCTL(0x0, 0x3), "bsr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x8E", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "lds")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x8F", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "xgdx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x90", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "suba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x91", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "cmpa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x92", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "sbca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x93", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "subd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x94", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "anda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x95", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "bita")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x96", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "ldaa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x97", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "staa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x98", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "eora")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x99", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "adca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x9A", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "oraa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x9B", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "adda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x9C", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "cpx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x9D", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x3), "jsr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x9E", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "lds")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\x9F", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "sts")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA0", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "suba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA1", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "cmpa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA2", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "sbca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA3", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "subd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA4", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "anda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA5", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "bita")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA6", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "ldaa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA7", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "staa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA8", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "eora")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xA9", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "adca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xAA", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "oraa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xAB", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "adda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xAC", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "cpx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xAD", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x2), "jsr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xAE", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "lds")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xAF", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "sts")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB0", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "suba")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB1", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "cmpa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB2", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "sbca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB3", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "subd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB4", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "anda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB5", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "bita")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB6", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "ldaa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB7", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "staa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB8", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "eora")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xB9", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "adca")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xBA", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "oraa")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xBB", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "adda")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xBC", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "cpx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xBD", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x3), "jsr")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xBE", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "lds")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xBF", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "sts")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC0", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "subb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC1", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "cmpb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC2", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "sbcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC3", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "addd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC4", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "andb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC5", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "bitb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC6", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "ldab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC8", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "eorb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xC9", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "adcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xCA", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "orab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xCB", MAKEOGRP(0x0, 0x5), MAKEOCTL(0x0, 0x0), "addb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xCC", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "ldd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\xCD\xA3", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "cpd")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\xCD\xAC", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "cpx")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\xCD\xEE", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "ldx")); m_Opcodes.AddOpcode(COpcodeEntry(2, (unsigned char *)"\xCD\xEF", MAKEOGRP(0x0, 0xB), MAKEOCTL(0x0, 0x0), "stx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xCE", MAKEOGRP(0x0, 0x6), MAKEOCTL(0x0, 0x0), "ldx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xCF", MAKEOGRP(0x0, 0x0), MAKEOCTL(0x0, 0x0), "stop")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD0", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "subb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD1", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "cmpb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD2", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "sbcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD3", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "addd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD4", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "andb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD5", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "bitb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD6", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "ldab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD7", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "stab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD8", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "eorb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xD9", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "adcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xDA", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "orab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xDB", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "addb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xDC", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "ldd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xDD", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "std")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xDE", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "ldx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xDF", MAKEOGRP(0x0, 0x1), MAKEOCTL(0x0, 0x1), "stx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE0", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "subb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE1", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "cmpb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE2", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "sbcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE3", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "addd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE4", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "andb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE5", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "bitb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE6", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "ldab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE7", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "stab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE8", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "eorb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xE9", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "adcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xEA", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "orab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xEB", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "addb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xEC", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "ldd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xED", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "std")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xEE", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "ldx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xEF", MAKEOGRP(0x0, 0xA), MAKEOCTL(0x0, 0x0), "stx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF0", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "subb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF1", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "cmpb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF2", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "sbcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF3", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "addd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF4", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "andb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF5", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "bitb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF6", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "ldab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF7", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "stab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF8", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "eorb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xF9", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "adcb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xFA", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "orab")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xFB", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "addb")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xFC", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "ldd")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xFD", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "std")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xFE", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "ldx")); m_Opcodes.AddOpcode(COpcodeEntry(1, (unsigned char *)"\xFF", MAKEOGRP(0x0, 0x2), MAKEOCTL(0x0, 0x1), "stx")); m_Memory = new TMemObject(1, 0x10000ul, 0x00, true); // 64K of memory available to processor m_Memory->AddMapping(0ul, 0, 0ul); // Mapped as one block SectionCount = 0; CBDef = true; } unsigned int CM6811Disassembler::GetVersionNumber() { return (CDisassembler::GetVersionNumber() | VERSION); // Get GDC version and append our version to it } std::string CM6811Disassembler::GetGDCLongName() { return "M6811 Disassembler GDC"; } std::string CM6811Disassembler::GetGDCShortName() { return "M6811GDC"; } bool CM6811Disassembler::ResolveIndirect(unsigned int nAddress, unsigned int& nResAddress, int nType) { unsigned int aVector; // In the HC11, we can assume that all indirect addresses are 2-bytes in length // and stored in little endian format. aVector = 0; if ((IsAddressLoaded(nAddress, 2) == false) || // Not only must it be loaded, but we must have never examined it before! (m_Memory->GetDescriptor(nAddress) != DMEM_LOADED) || (m_Memory->GetDescriptor(nAddress+1) != DMEM_LOADED)) { nResAddress = 0; return false; } aVector = m_Memory->GetByte(nAddress) * 256ul + m_Memory->GetByte(nAddress + 1); nResAddress = aVector; m_Memory->SetDescriptor(nAddress, DMEM_CODEINDIRECT + nType); // Flag the addresses as being the proper vector type m_Memory->SetDescriptor(nAddress+1, DMEM_CODEINDIRECT + nType); return true; } std::string CM6811Disassembler::GetExcludedPrintChars() { return "\\" DataDelim; } std::string CM6811Disassembler::GetHexDelim() { return HexDelim; } std::string CM6811Disassembler::GetCommentStartDelim() { return ComDelimS; } std::string CM6811Disassembler::GetCommentEndDelim() { return ComDelimE; } bool CM6811Disassembler::CompleteObjRead(bool bAddLabels, std::ostream *msgFile, std::ostream *errFile) { // Procedure to finish reading opcode from memory. This procedure reads operand bytes, // placing them in m_OpMemory. Plus branch/labels and data/labels are generated (according to function). bool A,B; char strTemp[10]; CBDef = true; // On HC11 all conditionally defined are defined, unlike 6809 OpPointer = m_OpMemory.size(); // Get position of start of operands following opcode StartPC = m_PC - m_OpMemory.size(); // Get PC of first byte of this instruction for branch references // Note: We'll start with the absolute address. Since we don't know what the relative address is // to the start of the function, then the function outputting function (which should know it), // will have to add it in: std::sprintf(strTemp, "%04X|", StartPC); m_sFunctionalOpcode = strTemp; // Move Bytes to m_OpMemory: A = MoveOpcodeArgs(OGRP_DST); B = MoveOpcodeArgs(OGRP_SRC); if ((A == false) || (B == false)) return false; TLabelTableMap::const_iterator itrLabel = m_LabelTable.find(StartPC); if (itrLabel != m_LabelTable.end()) { for (unsigned int i=0; i<itrLabel->second.size(); ++i) { if (i != 0) m_sFunctionalOpcode += ","; m_sFunctionalOpcode += FormatLabel(LC_REF, itrLabel->second.at(i), StartPC); } } m_sFunctionalOpcode += "|"; for (unsigned int i=0; i<m_OpMemory.size(); ++i) { std::sprintf(strTemp, "%02X", m_OpMemory.at(i)); m_sFunctionalOpcode += strTemp; } m_sFunctionalOpcode += "|"; for (unsigned int i=0; i<OpPointer; ++i) { std::sprintf(strTemp, "%02X", m_OpMemory.at(i)); m_sFunctionalOpcode += strTemp; } m_sFunctionalOpcode += "|"; for (unsigned int i=OpPointer; i<m_OpMemory.size(); ++i) { std::sprintf(strTemp, "%02X", m_OpMemory.at(i)); m_sFunctionalOpcode += strTemp; } m_sFunctionalOpcode += "|"; // Decode Operands: A = DecodeOpcode(OGRP_DST, OCTL_DST, bAddLabels, msgFile, errFile); m_sFunctionalOpcode += "|"; B = DecodeOpcode(OGRP_SRC, OCTL_SRC, bAddLabels, msgFile, errFile); if ((A == false) || (B == false)) return false; m_sFunctionalOpcode += "|"; m_sFunctionalOpcode += FormatMnemonic(MC_OPCODE); m_sFunctionalOpcode += "|"; m_sFunctionalOpcode += FormatOperands(MC_OPCODE); // See if this is the end of a function. Note: These preempt all previously // decoded function tags -- such as call, etc: if ((compareNoCase(m_CurrentOpcode.m_Mnemonic, "rts") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "rti") == 0)) { m_FunctionsTable[StartPC] = FUNCF_HARDSTOP; } return true; } bool CM6811Disassembler::RetrieveIndirect(std::ostream * /* msgFile */, std::ostream * /* errFile */) { MEM_DESC b1d, b2d; m_OpMemory.clear(); m_OpMemory.push_back(m_Memory->GetByte(m_PC)); m_OpMemory.push_back(m_Memory->GetByte(m_PC+1)); // All HC11 indirects are Motorola format and are 2-bytes in length, regardless: b1d = (MEM_DESC)m_Memory->GetDescriptor(m_PC); b2d = (MEM_DESC)m_Memory->GetDescriptor(m_PC+1); if (((b1d != DMEM_CODEINDIRECT) && (b1d != DMEM_DATAINDIRECT)) || ((b2d != DMEM_CODEINDIRECT) && (b2d != DMEM_DATAINDIRECT))) { m_PC += 2; return false; // Memory should be tagged as indirect! } if (b1d != b2d) { m_PC += 2; return false; // Memory should be tagged as a correct pair! } if (((b1d == DMEM_CODEINDIRECT) && (m_CodeIndirectTable.find(m_PC) == m_CodeIndirectTable.end())) || ((b1d == DMEM_DATAINDIRECT) && (m_DataIndirectTable.find(m_PC) == m_DataIndirectTable.end()))) { m_PC += 2; return false; // Location must exist in one of the two tables! } m_PC += 2; return true; } bool CM6811Disassembler::MoveOpcodeArgs(unsigned int nGroup) { switch (nGroup) { case 0x2: case 0x4: case 0x6: case 0x7: case 0x8: case 0x9: m_OpMemory.push_back(m_Memory->GetByte(m_PC++)); // Fall through and do it again: case 0x1: case 0x3: case 0x5: case 0xA: case 0xB: m_OpMemory.push_back(m_Memory->GetByte(m_PC++)); break; case 0x0: break; default: return false; } return true; } bool CM6811Disassembler::DecodeOpcode(unsigned int nGroup, unsigned int nControl, bool bAddLabels, std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; char strTemp[30]; char strTemp2[30]; unsigned int nTargetAddr; strTemp[0] = 0; nTargetAddr = 0xFFFFFFFF; switch (nGroup) { case 0x0: // No operand break; case 0x1: // absolute 8-bit, assume msb=$00 switch (nControl) { case 1: if (bAddLabels) GenDataLabel(m_OpMemory[OpPointer], StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "D@%02lX", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; case 3: if (bAddLabels) GenAddrLabel(m_OpMemory[OpPointer], StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "C@%02lX", static_cast<unsigned long>(m_OpMemory[OpPointer])); nTargetAddr = static_cast<unsigned long>(m_OpMemory[OpPointer]); break; default: RetVal = false; } OpPointer++; break; case 0x2: // 16-bit Absolute switch (nControl) { case 1: if (bAddLabels) GenDataLabel(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1], StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "D@%04lX", static_cast<unsigned long>(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])); break; case 3: if (bAddLabels) GenAddrLabel(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1], StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "C@%04lX", static_cast<unsigned long>(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])); nTargetAddr = static_cast<unsigned long>(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]); break; default: RetVal = false; } OpPointer += 2; break; case 0x3: // 8-bit Relative switch (nControl) { case 1: if (bAddLabels) GenDataLabel(m_PC+(signed long)(signed char)(m_OpMemory[OpPointer]), StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "D^%c%02lX(%04lX)", ((((signed long)(signed char)(m_OpMemory[OpPointer])) != labs((signed long)(signed char)(m_OpMemory[OpPointer]))) ? '-' : '+'), labs((signed long)(signed char)(m_OpMemory[OpPointer])), m_PC+(signed long)(signed char)(m_OpMemory[OpPointer])); break; case 3: if (bAddLabels) GenAddrLabel(m_PC+(signed long)(signed char)(m_OpMemory[OpPointer]), StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "C^%c%02lX(%04lX)", ((((signed long)(signed char)(m_OpMemory[OpPointer])) != labs((signed long)(signed char)(m_OpMemory[OpPointer]))) ? '-' : '+'), labs((signed long)(signed char)(m_OpMemory[OpPointer])), m_PC+(signed long)(signed char)(m_OpMemory[OpPointer])); nTargetAddr = m_PC+(signed long)(signed char)(m_OpMemory[OpPointer]); break; default: RetVal = false; } OpPointer++; break; case 0x4: // 16-bit Relative switch (nControl) { case 1: if (bAddLabels) GenDataLabel(m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]), StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "D^%c%04lX(%04lX)", ((((signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])) != labs((signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]))) ? '-' : '+'), labs((signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])), m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])); break; case 3: if (bAddLabels) GenAddrLabel(m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]), StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp, "C^%c%04lX(%04lX)", ((((signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])) != labs((signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]))) ? '-' : '+'), labs((signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])), m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])); nTargetAddr = m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]); break; default: RetVal = false; } OpPointer += 2; break; case 0x5: // Immediate 8-bit data -- no label std::sprintf(strTemp, "#%02lX", static_cast<unsigned long>(m_OpMemory[OpPointer])); OpPointer++; break; case 0x6: // Immediate 16-bit data -- no label std::sprintf(strTemp, "#%04lX", static_cast<unsigned long>(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])); OpPointer += 2; break; case 0x7: // 8-bit Absolute address, and mask strTemp2[0] = 0; switch (nControl) { case 1: if (bAddLabels) GenDataLabel(m_OpMemory[OpPointer], StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp2, "D@%02lX", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; case 3: if (bAddLabels) GenAddrLabel(m_OpMemory[OpPointer], StartPC, std::string(), msgFile, errFile); std::sprintf(strTemp2, "C@%02lX", static_cast<unsigned long>(m_OpMemory[OpPointer])); nTargetAddr = static_cast<unsigned long>(m_OpMemory[OpPointer]); break; default: RetVal = false; } std::sprintf(strTemp, "%s,M%02lX", strTemp2, static_cast<unsigned long>(m_OpMemory[OpPointer+1])); OpPointer += 2; break; case 0x8: // 8-bit offset and 8-bit mask (x) strTemp2[0] = 0; switch (nControl) { case 0: case 1: std::sprintf(strTemp2, "D&%02lX(x)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; case 2: case 3: case 4: std::sprintf(strTemp2, "C&%02lX(x)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; } std::sprintf(strTemp, "%s,M%02lX", strTemp2, static_cast<unsigned long>(m_OpMemory[OpPointer+1])); OpPointer += 2; break; case 0x9: // 8-bit offset and 8-bit mask (y) strTemp2[0] = 0; switch (nControl) { case 0: case 1: std::sprintf(strTemp2, "D&%02lX(y)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; case 2: case 3: case 4: std::sprintf(strTemp2, "C&%02lX(y)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; } std::sprintf(strTemp, "%s,M%02lX", strTemp2, static_cast<unsigned long>(m_OpMemory[OpPointer+1])); OpPointer += 2; break; case 0xA: // 8-bit offset (x) switch (nControl) { case 0: case 1: std::sprintf(strTemp, "D&%02lX(x)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; case 2: case 3: case 4: std::sprintf(strTemp, "C&%02lX(x)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; } OpPointer++; break; case 0xB: // 8-bit offset (y) switch (nControl) { case 0: case 1: std::sprintf(strTemp, "D&%02lX(y)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; case 2: case 3: case 4: std::sprintf(strTemp, "C&%02lX(y)", static_cast<unsigned long>(m_OpMemory[OpPointer])); break; } OpPointer++; break; default: RetVal = false; } m_sFunctionalOpcode += strTemp; // See if this is a function branch reference that needs to be added: if (nTargetAddr != 0xFFFFFFFF) { if ((compareNoCase(m_CurrentOpcode.m_Mnemonic, "jsr") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bsr") == 0)) { // Add these only if it is replacing a lower priority value: TAddressMap::const_iterator itrFunction = m_FunctionsTable.find(nTargetAddr); if (itrFunction == m_FunctionsTable.end()) { m_FunctionsTable[nTargetAddr] = FUNCF_CALL; } else { if (itrFunction->second > FUNCF_CALL) m_FunctionsTable[nTargetAddr] = FUNCF_CALL; } // See if this is the end of a function: if (m_FuncExitAddresses.find(nTargetAddr) != m_FuncExitAddresses.end()) { m_FunctionsTable[StartPC] = FUNCF_EXITBRANCH; } } if ((compareNoCase(m_CurrentOpcode.m_Mnemonic, "brset") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "brclr") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "brn") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bhi") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bls") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bcc") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bcs") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bne") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "beq") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bvc") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bvs") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bpl") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bmi") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bge") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "blt") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bgt") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "ble") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bra") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "jmp") == 0)) { // Add these only if there isn't a function tag here: if (m_FunctionsTable.find(nTargetAddr) == m_FunctionsTable.end()) m_FunctionsTable[nTargetAddr] = FUNCF_BRANCHIN; } } // See if this is the end of a function: if ((compareNoCase(m_CurrentOpcode.m_Mnemonic, "jmp") == 0) || (compareNoCase(m_CurrentOpcode.m_Mnemonic, "bra") == 0)) { if (nTargetAddr != 0xFFFFFFFF) { if (m_FuncExitAddresses.find(nTargetAddr) != m_FuncExitAddresses.end()) { m_FunctionsTable[StartPC] = FUNCF_EXITBRANCH; } else { m_FunctionsTable[StartPC] = FUNCF_BRANCHOUT; } } else { // Non-Deterministic branches get tagged as a branchout: //m_FunctionsTable[StartPC] = FUNCF_BRANCHOUT; // Non-Deterministic branches get tagged as a hardstop (usually it exits the function): m_FunctionsTable[StartPC] = FUNCF_HARDSTOP; } } return RetVal; } void CM6811Disassembler::CreateOperand(unsigned int nGroup, std::string& sOpStr) { char strTemp[30]; switch (nGroup) { case 0x1: // absolute 8-bit, assume msb=$00 sOpStr += "*"; sOpStr += LabelDeref2(m_OpMemory[OpPointer]); OpPointer++; break; case 0x2: // 16-bit Absolute sOpStr += LabelDeref4(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]); OpPointer += 2; break; case 0x3: // 8-bit Relative sOpStr += LabelDeref4(m_PC+(signed long)(signed char)(m_OpMemory[OpPointer])); OpPointer++; break; case 0x4: // 16-bit Relative sOpStr += LabelDeref4(m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1])); OpPointer += 2; break; case 0x5: // Immediate 8-bit data std::sprintf(strTemp, "#%s%02X", GetHexDelim().c_str(), m_OpMemory[OpPointer]); sOpStr += strTemp; OpPointer++; break; case 0x6: // Immediate 16-bit data std::sprintf(strTemp, "#%s%04X", GetHexDelim().c_str(), m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]); sOpStr += strTemp; OpPointer += 2; break; case 0x7: // 8-bit Absolute address, and mask sOpStr += "*"; sOpStr += LabelDeref2(m_OpMemory[OpPointer]); sOpStr += ","; std::sprintf(strTemp, "#%s%02X", GetHexDelim().c_str(), m_OpMemory[OpPointer+1]); sOpStr += strTemp; OpPointer += 2; break; case 0x8: // 8-bit offset and 8-bit mask (x) std::sprintf(strTemp, "%s%02X,x,#%s%02X", GetHexDelim().c_str(), m_OpMemory[OpPointer], GetHexDelim().c_str(), m_OpMemory[OpPointer+1]); sOpStr += strTemp; OpPointer += 2; break; case 0x9: // 8-bit offset and 8-bit mask (y) std::sprintf(strTemp, "%s%02X,y,#%s%02X", GetHexDelim().c_str(), m_OpMemory[OpPointer], GetHexDelim().c_str(), m_OpMemory[OpPointer+1]); sOpStr += strTemp; OpPointer += 2; break; case 0xA: // 8-bit offset (x) std::sprintf(strTemp, "%s%02X,x", GetHexDelim().c_str(), m_OpMemory[OpPointer]); sOpStr += strTemp; OpPointer++; break; case 0xB: // 8-bit offset (y) std::sprintf(strTemp, "%s%02X,y", GetHexDelim().c_str(), m_OpMemory[OpPointer]); sOpStr += strTemp; OpPointer++; break; } } bool CM6811Disassembler::CheckBranchOutside(unsigned int nGroup) { bool RetVal = true; unsigned int Address; switch (nGroup) { case 0x1: // absolute 8-bit, assume msb=$00 Address = m_OpMemory[OpPointer]; RetVal = IsAddressLoaded(Address, 1); OpPointer++; break; case 0x2: // 16-bit Absolute Address = m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]; RetVal = IsAddressLoaded(Address, 1); OpPointer += 2; break; case 0x3: // 8-bit Relative Address = m_PC+(signed long)(signed char)(m_OpMemory[OpPointer]); RetVal = IsAddressLoaded(Address, 1); OpPointer++; break; case 0x4: // 16-bit Relative Address = m_PC+(signed long)(signed short)(m_OpMemory[OpPointer]*256+m_OpMemory[OpPointer+1]); RetVal = IsAddressLoaded(Address, 1); OpPointer += 2; break; } return RetVal; } std::string CM6811Disassembler::FormatLabel(LABEL_CODE nLC, const std::string & szLabel, unsigned int nAddress) { std::string Temp = CDisassembler::FormatLabel(nLC, szLabel, nAddress); // Call parent switch (nLC) { case LC_EQUATE: Temp += LbleDelim; break; case LC_DATA: case LC_CODE: Temp += LblcDelim; break; default: break; } return Temp; } std::string CM6811Disassembler::FormatMnemonic(MNEMONIC_CODE nMCCode) { switch (nMCCode) { case MC_OPCODE: return m_CurrentOpcode.m_Mnemonic; case MC_ILLOP: return "???"; case MC_EQUATE: return "="; case MC_DATABYTE: return ".byte"; case MC_ASCII: return ".ascii"; case MC_INDIRECT: return ".word"; } return "???"; } std::string CM6811Disassembler::FormatOperands(MNEMONIC_CODE nMCCode) { std::string OpStr; char strTemp[30]; unsigned int Address; OpStr = ""; switch (nMCCode) { case MC_ILLOP: case MC_DATABYTE: for (unsigned int i=0; i<m_OpMemory.size(); ++i) { std::sprintf(strTemp, "%s%02X", GetHexDelim().c_str(), m_OpMemory.at(i)); OpStr += strTemp; if (i < (m_OpMemory.size()-1)) OpStr += ","; } break; case MC_ASCII: OpStr += DataDelim; for (unsigned int i=0; i<m_OpMemory.size(); ++i) { std::sprintf(strTemp, "%c", m_OpMemory.at(i)); OpStr += strTemp; } OpStr += DataDelim; break; case MC_EQUATE: std::sprintf(strTemp, "%s%04X", GetHexDelim().c_str(), m_PC); OpStr = strTemp; break; case MC_INDIRECT: { if (m_OpMemory.size() != 2) { assert(false); // Check code and make sure RetrieveIndirect got called and called correctly! break; } Address = m_OpMemory.at(0)*256+m_OpMemory.at(1); std::string strLabel; TAddressLabelMap::const_iterator itrLabel; if ((itrLabel = m_CodeIndirectTable.find(m_PC-2)) != m_CodeIndirectTable.end()) { strLabel = itrLabel->second; } else if ((itrLabel = m_DataIndirectTable.find(m_PC-2)) != m_DataIndirectTable.end()) { strLabel = itrLabel->second; } OpStr = FormatLabel(LC_REF, strLabel, Address); break; } case MC_OPCODE: OpPointer = m_CurrentOpcode.m_OpcodeBytes.size(); // Get position of start of operands following opcode StartPC = m_PC - m_OpMemory.size(); // Get PC of first byte of this instruction for branch references CreateOperand(OGRP_DST, OpStr); // Handle Destination operand first if (OGRP_DST != 0x0) OpStr += ","; CreateOperand(OGRP_SRC, OpStr); // Handle Source operand last break; } return OpStr; } std::string CM6811Disassembler::FormatComments(MNEMONIC_CODE nMCCode) { std::string RetVal; bool Flag; unsigned int Address; RetVal = ""; // Handle Undetermined Branch: switch (nMCCode) { case MC_OPCODE: if ((OCTL_SRC == 0x2) || (OCTL_DST == 0x2) || ((CBDef == false) && ((OCTL_SRC == 0x4) || (OCTL_DST == 0x4)))) { RetVal = "Undetermined Branch Address"; } break; default: break; } // Handle out-of-source branch: Flag = false; switch (nMCCode) { case MC_OPCODE: OpPointer = m_CurrentOpcode.m_OpcodeBytes.size(); // Get position of start of operands following opcode StartPC = m_PC - m_OpMemory.size(); // Get PC of first byte of this instruction for branch references switch (OCTL_DST) { case 0x2: case 0x3: case 0x4: if (CheckBranchOutside(OGRP_DST) == false) Flag = true; break; } switch (OCTL_SRC) { case 0x2: case 0x3: case 0x4: if (CheckBranchOutside(OGRP_SRC) == false) Flag = true; break; } break; case MC_INDIRECT: Address = m_OpMemory.at(0)*256+m_OpMemory.at(1); if (m_CodeIndirectTable.find(m_PC-2) != m_CodeIndirectTable.end()) { if (IsAddressLoaded(Address, 1) == false) Flag = true; } break; default: break; } if (Flag) { if (!RetVal.empty()) RetVal += ", "; RetVal += "Branch Outside Loaded Source(s)"; } // Add general refernce stuff: if (!RetVal.empty()) RetVal += "\t"; RetVal += CDisassembler::FormatComments(nMCCode); // Call parent and add default comments... i.e references return RetVal; } bool CM6811Disassembler::WritePreSection(std::ostream& outFile, std::ostream * /* msgFile */, std::ostream * /* errFile */) { TStringArray OutLine; char strTemp[30]; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); OutLine[FC_MNEMONIC] = ".area"; std::sprintf(strTemp, "CODE%d\t(ABS)", ++SectionCount); OutLine[FC_OPERANDS] = strTemp; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_MNEMONIC] = ".org"; std::sprintf(strTemp, "%s%04X", GetHexDelim().c_str(), m_PC); OutLine[FC_OPERANDS] = strTemp; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_MNEMONIC] = ""; OutLine[FC_OPERANDS] = ""; outFile << MakeOutputLine(OutLine) << "\n"; return true; } std::string CM6811Disassembler::LabelDeref2(unsigned int nAddress) { std::string strTemp; char strCharTemp[30]; TLabelTableMap::const_iterator itrLabel = m_LabelTable.find(nAddress); if (itrLabel != m_LabelTable.end()) { if (itrLabel->second.size()) { strTemp = FormatLabel(LC_REF, itrLabel->second.at(0), nAddress); } else { strTemp = FormatLabel(LC_REF, std::string(), nAddress); } } else { std::sprintf(strCharTemp, "%s%02X", GetHexDelim().c_str(), nAddress); strTemp = strCharTemp; } return strTemp; } std::string CM6811Disassembler::LabelDeref4(unsigned int nAddress) { std::string strTemp; char strCharTemp[30]; TLabelTableMap::const_iterator itrLabel = m_LabelTable.find(nAddress); if (itrLabel != m_LabelTable.end()) { if (itrLabel->second.size()) { strTemp = FormatLabel(LC_REF, itrLabel->second.at(0), nAddress); } else { strTemp = FormatLabel(LC_REF, std::string(), nAddress); } } else { std::sprintf(strCharTemp, "%s%04X", GetHexDelim().c_str(), nAddress); strTemp = strCharTemp; } return strTemp; } <file_sep>/programs/funcanal/funccomp.cpp // funccomp.cpp: implementation of the Fuzzy Function Comparison Logic // // $Log: funccomp.cpp,v $ // Revision 1.2 2003/09/13 05:39:49 dewhisna // Added output options and returning of match percentage to function diff. // // Revision 1.1 2003/02/09 06:59:29 dewhisna // Initial Revision - Split comparison logic from Function File I/O // // // // The Edit Script is defined as follows: // // During comparison an optimal edit script is calculated and is stored as a CStringArray. Each // entry is a string of the following format, which is similar to the Diff format except // that each entry is unique rather than specifying ranges: // xxxCyyy // // Where: // xxx = Left side index // yyy = Right side index // C is one of the following symbols: // '>' - Delete xxx from left at point yyy in right or // insert xxx from left at point yyy in right // '-' - Replace xxx in left with yyyy in right // '<' - Insert yyy from right at left point xxx or // delete yyy from right at point xxx in left // #include "stdafx.h" #include "funcdesc.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif static CStringArray m_EditScript; static BOOL m_bEditScriptValid = FALSE; double CompareFunctions(FUNC_COMPARE_METHOD nMethod, CFuncDescFile *pFile1, int nFile1FuncNdx, CFuncDescFile *pFile2, int nFile2FuncNdx, BOOL bBuildEditScript) { CFuncDesc *pFunction1; CFuncDesc *pFunction2; CStringArray zFunc1; CStringArray zFunc2; double nRetVal = 0; CString strTemp; m_bEditScriptValid = FALSE; m_EditScript.RemoveAll(); if ((pFile1 == NULL) || (pFile2 == NULL)) return nRetVal; pFunction1 = pFile1->GetFunc(nFile1FuncNdx); pFunction2 = pFile2->GetFunc(nFile2FuncNdx); if ((pFunction1 == NULL) || (pFunction2 == NULL)) return nRetVal; pFunction1->ExportToDiff(zFunc1); pFunction2->ExportToDiff(zFunc2); if ((zFunc1.GetSize() == 0) || (zFunc2.GetSize() == 0)) return nRetVal; if ((bBuildEditScript) && (nMethod == FCM_DYNPROG_XDROP)) { // Note: XDROP Method currently doesn't support building // of edit scripts, so if caller wants to build an // edit script and has selected this method, replace // it with the next best method that does support // edit scripts: nMethod = FCM_DYNPROG_GREEDY; } switch (nMethod) { case FCM_DYNPROG_XDROP: { // // The following algorithm comes from the following source: // "A Greedy Algorithm for Aligning DNA Sequences" // <NAME>, <NAME>, <NAME>, and <NAME> // Journal of Computational Biology // Volume 7, Numbers 1/2, 2000 // <NAME>, Inc. // Pp. 203-214 // // p. 205 : Figure 2 : "A dynamic-programming X-drop algorithm" // // T' <- T <- S(0,0) <- 0 // k <- L <- U <- 0 // repeat { // k <- k + 1 // for i <- ceiling(L) to floor(U)+1 in steps of 1/2 do { // j <- k - i // if i is an integer then { // S(i, j) <- Max of: // S(i-1/2, j-1/2) + mat/2 if L <= i-1/2 <= U and a(i) = b(j) // S(i-1/2, j-1/2) + mis/2 if L <= i-1/2 <= U and a(i) != b(j) // S(i, j-1) + ind if i <= U // S(i-1, j) + ind if L <= i-1 // } else { // S(i, j) <- S(i-1/2, j-1/2) // + mat/2 if a(i+1/2) = b(j+1/2) // + mis/2 if a(i+1/2) != b(j+1/2) // } // T' <- max{T', S(i, j)} // if S(i, j) < (T - X) then S(i, j) <- -oo // } // L <- min{i : S(i, k-i) > -oo } // U <- max{i : S(i, k-i) > -oo } // L <- max{L, k+1-N} <<< Should be: L <- max{L, k+1/2-N} // U <- min{U, M-1} <<< Should be: U <- min(U, M-1/2} // T <- T' // } until L > U+1 // report T' // // Given: // arrays: a(1..M), b(1..N) containing the two strings to compare // mat : >0 : Weighting of a match // mis : <0 : Weighting of a mismatch // ind : <0 : Weighting of an insertion/deletion // X = Clipping level : If scoring falls more than X below the // best computed score thus far, then we don't consider // additional extensions for that alignment. Should // be >= 0 or -1 for infinity. // // Returning: // T' = Composite similarity score // // For programmatic efficiency, all S indexes have been changed from // 0, 1/2 to even/odd and the i loop runs as integers of even/odd // instead of 1/2 increments: // // Testing has also been done and it has been proven that the order of // the two arrays has no effect on the outcome. // // In the following, we will define oo as DBL_MAX and -oo as -DBL_MAX. // // To hold to the non-Generalized Greedy Algorithm requirements, set // ind = mis - mat/2 // CStringArray &a = zFunc1; CStringArray &b = zFunc2; double Tp, T; double **S; int i, j, k, L, U; double nTemp; int M = a.GetSize(); int N = b.GetSize(); const double mat = 2; const double mis = -2; const double ind = -3; const double X = -1; // Allocate Memory: S = new double*[((M+1)*2)]; if (S == NULL) { AfxThrowMemoryException(); return nRetVal; } for (i=0; i<((M+1)*2); i++) { S[i] = new double[((N+1)*2)]; if (S[i] == NULL) AfxThrowMemoryException(); } // Initialize: for (i=0; i<((M+1)*2); i++) { for (j=0; j<((N+1)*2); j++) { S[i][j] = -DBL_MAX; } } // Algorithm: Tp = T = S[0][0] = 0; k = L = U = 0; do { k = k + 2; for (i = L+((L & 0x1) ? 1 : 0); i <= (U - ((U & 0x1) ? 1 : 0) + 2); i++) { j = k - i; ASSERT(i >= 0); ASSERT(i < ((M+1)*2)); ASSERT(j >= 0); ASSERT(j < ((N+1)*2)); if ((i&1) == 0) { nTemp = -DBL_MAX; if ((L <= (i-1)) && ((i-1) <= U)) { // TODO : Improve A/B Comparison: if (a.GetAt((i/2)-1).CompareNoCase(b.GetAt((j/2)-1)) == 0) { nTemp = __max(nTemp, S[i-1][j-1] + mat/2); } else { nTemp = __max(nTemp, S[i-1][j-1] + mis/2); } } if (i <= U) { nTemp = __max(nTemp, S[i][j-2] + ind); } if (L <= (i-2)) { nTemp = __max(nTemp, S[i-2][j] + ind); } S[i][j] = nTemp; } else { // TODO : Improve A/B Comparison: if (a.GetAt(((i+1)/2)-1).CompareNoCase(b.GetAt(((j+1)/2)-1)) == 0) { S[i][j] = S[i-1][j-1] + mat/2; } else { S[i][j] = S[i-1][j-1] + mis/2; } } Tp = __max(Tp, S[i][j]); if ((X>=0) && (S[i][j] < (T-X))) S[i][j] = -DBL_MAX; } for (L = 0; L < ((M+1)*2); L++) { if ((k - L) < 0) continue; if ((k - L) >= ((N+1)*2)) continue; if (S[L][k-L] > -DBL_MAX) break; } if (L == ((M+1)*2)) L=INT_MAX; for (U=((M+1)*2)-1; U>=0; U--) { if ((k - U) < 0) continue; if ((k - U) >= ((N+1)*2)) continue; if (S[U][k-U] > -DBL_MAX) break; } if (U == -1) U=INT_MIN; L = __max(L, k + 1 - (N*2)); U = __min(U, (M*2) - 1); T = Tp; } while (L <= U+2); // If the two PrimaryLabels at the function's address don't match, decrement match by 1*mat. // This helps if there are two are more functions that the user has labeled that // are identical except for the labels: if (pFile1->GetPrimaryLabel(pFunction1->GetMainAddress()).CompareNoCase( pFile2->GetPrimaryLabel(pFunction2->GetMainAddress())) != 0) Tp = __max(0, Tp - mat); // Normalize it: nRetVal = Tp/(__max(M,N)*mat); // Deallocate Memory: for (i=0; i<((M+1)*2); i++) delete[] (S[i]); delete[] S; } break; case FCM_DYNPROG_GREEDY: { // // The following algorithm comes from the following source: // "A Greedy Algorithm for Aligning DNA Sequences" // <NAME>, <NAME>, <NAME>, and <NAME> // Journal of Computational Biology // Volume 7, Numbers 1/2, 2000 // <NAME>, Inc. // Pp. 203-214 // // p. 209 : Figure 4 : "Greedy algorithm that is equivalent to the algorithm // of Figure 2 if ind = mis - mat/2." // // i <- 0 // while i < min{M, N} and a(i+1) = b(i+1) do i <- i + 1 // R(0, 0) <- i // T' <- T[0] <- S'(i+i, 0) // d <- L <- U <- 0 // repeat // d <- d + 1 // d' <- d - floor( (X + mat/2)/(mat - mis) ) - 1 // for k <- L - 1 to U + 1 do // i <- max of: // R(d-1, k-1) + 1 if L < k // R(d-1, k) + 1 if L <= k <= U // R(d-1, k+1) if k < U // j <- i - k // if i > -oo and S'(i+j, d) >= T[d'] - X then // while i<M, j<N, and a(i+1) = b(j+1) do // i <- i + 1; j <- j + 1 // R(d, k) <- i // T' <- max{T', S'(i+j, d)} // else R(d, k) <- -oo // T[d] <- T' // L <- min{k : R(d, k) > -oo} // U <- max{k : R(d, k) > -oo} // L <- max{L, max{k : R(d, k) = N + k} + 2} <<< Should be: L <- max{L, max{k : R(d, k) = N + k} + 1} // U <- min{U, min{k : R(d, k) = M } - 2} <<< Should be: U <- min{U, min{k : R(d, k) = M } - 1} // until L > U + 2 // report T' // // Given: // arrays: a(1..M), b(1..N) containing the two strings to compare // mat : >0 : Weighting of a match // mis : <0 : Weighting of a mismatch // ind : <0 : Weighting of an insertion/deletion // (Satisfying: ind = mis - mat/2) // X = Clipping level : If scoring falls more than X below the // best computed score thus far, then we don't consider // additional extensions for that alignment. Should // be >= 0 or -1 for infinity. // S'(i+j, d) = (i+j)*mat/2 - d*(mat-mis) // or S'(k, d) = k*mat/2 - d*(mat-mis) // // Returning: // T' = Composite similarity score // // Testing has also been done and it has been proven that the order of // the two arrays has no effect on the outcome. // // In the following it will be assumed that the number of mismatches // (i.e. array bounds) can't exceed M+N since the absolute maximum // edit script to go from an array of M objects to an array of N // objects is to perform M deletions and N insertions. However, // these differences can be tracked either forward or backward, so // the memory will be allocated for the full search field. // // We are also going to define -oo as being -2 since no index can be // lower than 0. The reason for the -2 instead of -1 is to allow // for the i=R(d,k)+1 calculations to still be below 0. That is // to say so that -oo + 1 = -oo // CStringArray &a = zFunc1; CStringArray &b = zFunc2; double Tp; // T' = Overall max for entire comparison double Tpp; // T'' = Overall max for current d value double *T; double nTemp; int **Rm; int *Rvisitmin; // Minimum k-index of R visited for a particular d (for speed) int *Rvisitmax; // Maximum k-index of R visited for a particular k (for speed) int i, j, k, L, U; int d, dp; int dbest, kbest; int M = a.GetSize(); int N = b.GetSize(); const int dmax = ((M+N)*2)+1; const int kmax = (M+N+1); const int rksize = (kmax*2)+1; const double mat = 2; const double mis = -2; const double X = -1; const int floored_d_offset = (int)((X+(mat/2))/(mat-mis)); #define Sp(x, y) ((double)((x)*(mat/2) - ((y)*(mat-mis)))) #define R(x, y) (Rm[(x)][(y)+kmax]) // Allocate Memory: T = new double[dmax]; if (T == NULL) { AfxThrowMemoryException(); return nRetVal; } Rvisitmin = new int[dmax]; if (Rvisitmin == NULL) { AfxThrowMemoryException(); delete T; return nRetVal; } Rvisitmax = new int[dmax]; if (Rvisitmax == NULL) { AfxThrowMemoryException(); delete T; delete Rvisitmin; return nRetVal; } Rm = new int*[dmax]; if (Rm == NULL) { AfxThrowMemoryException(); delete T; delete Rvisitmin; delete Rvisitmax; return nRetVal; } for (i=0; i<dmax; i++) { Rm[i] = new int[rksize]; if (Rm[i] == NULL) AfxThrowMemoryException(); } // Initialize: for (i=0; i<dmax; i++) { T[i] = 0; Rvisitmin[i] = kmax+1; Rvisitmax[i] = -kmax-1; for (j=0; j<rksize; j++) { Rm[i][j] = -2; } } // Algorithm: i=0; // TODO : Improve A/B Comparison: while ((i<__min(M, N)) && (a.GetAt(i).CompareNoCase(b.GetAt(i)) == 0)) i++; R(0, 0) = i; dbest = kbest = 0; Tp = T[0] = Sp(i+i, 0); d = L = U = 0; Rvisitmin[0] = 0; Rvisitmax[0] = 0; /* printf("\n"); */ if ((i != M) || (i != N)) { do { d++; dp = d - floored_d_offset - 1; Tpp = -DBL_MAX; for (k=(L-1); k<=(U+1); k++) { ASSERT(d > 0); ASSERT(d < dmax); ASSERT(abs(k) <= kmax); i = -2; if (L < k) i = __max(i, R(d-1, k-1)+1); if ((L <= k) && (k <= U)) i = __max(i, R(d-1, k)+1); if (k < U) i = __max(i, R(d-1, k+1)); j = i - k; if ((i >= 0) && (j >= 0) && ((X<0) || (Sp(i+j, d) >= (((dp >= 0) ? T[dp] : 0) - X)))) { // TODO : Improve A/B Comparison: while ((i<M) && (j<N) && (a.GetAt(i).CompareNoCase(b.GetAt(j)) == 0)) { i++; j++; } R(d, k) = i; if (Rvisitmin[d] > k) Rvisitmin[d] = k; if (Rvisitmax[d] < k) Rvisitmax[d] = k; nTemp = Sp(i+j, d); Tp = __max(Tp, nTemp); /* printf("d=%2ld : k=%2ld, i=%2ld, j=%2ld, M=%2ld, N=%2ld, T=%2ld, Tp=%2ld, Tpp=%2ld", d, k, i, j, M, N, (int)nTemp, (int)Tp, (int)Tpp); */ if (nTemp > Tpp) { Tpp = nTemp; /* printf(" * Best (%2ld)", (int)Tpp); */ dbest = d; kbest = k; // Account for hitting the max M or N boundaries: if ((i != M) || (j != N)) { if (j > N) { kbest++; /* printf(" >>>>>> k++ j shift"); */ } else { if (i > M) { kbest--; /* printf(" <<<<<< k-- i shift"); */ } } } } /* printf("\n"); */ } else { R(d, k) = -2; if (Rvisitmin[d] == k) Rvisitmin[d]++; if (Rvisitmax[d] >= k) Rvisitmax[d] = k-1; } } T[d] = Tp; L = Rvisitmin[d]; U = Rvisitmax[d]; for (k=Rvisitmax[d]; k>=Rvisitmin[d]; k--) if (R(d, k) == (N+k)) break; if (k<Rvisitmin[d]) k = INT_MIN; L = __max(L, k+1); for (k=Rvisitmin[d]; k<=Rvisitmax[d]; k++) if (R(d, k) == M) break; if (k>Rvisitmax[d]) k = INT_MAX; U = __min(U, k-1); } while (L <= U+2); } // If the two PrimaryLabels at the function's address don't match, decrement match by 1*mat. // This helps if there are two are more functions that the user has labeled that // are identical except for the labels: if (pFile1->GetPrimaryLabel(pFunction1->GetMainAddress()).CompareNoCase( pFile2->GetPrimaryLabel(pFunction2->GetMainAddress())) != 0) Tp = __max(0, Tp - mat); // Normalize it: nRetVal = Tp/(__max(M,N)*mat); // Build Edit Script: if (bBuildEditScript) { int last_i, last_j; int cur_i, cur_j; int k_rest; if (dbest > 0) { m_EditScript.SetSize(dbest); k = kbest; last_i = M+1; last_j = N+1; /* printf("\n%s with %s:\n", LPCTSTR(pFunction1->GetMainName()), LPCTSTR(pFunction2->GetMainName())); */ for (d=dbest-1; d>=0; d--) { i = __max((R(d, k-1) + 1), __max((R(d, k) + 1), (R(d, k+1)))); /* printf("(%3ld, %3ld) : %3ld(%5ld), %3ld(%5ld), %3ld(%5ld) :", d, k, (R(d, k-1) + 1), (int)Sp((R(d, k-1))*2-k+1, d), (R(d, k) + 1), (int)Sp((R(d, k))*2-k, d), (R(d, k+1)), (int)Sp((R(d, k+1))*2-k-1, d)); for (j=Rvisitmin[dbest-1]; j<=Rvisitmax[dbest-1]; j++) { if (j == k-1) printf("("); else printf(" "); if (R(d,j)<0) printf(" "); else printf("%3ld", R(d, j)); if (j == k+1) printf(")"); else printf(" "); } printf("\n"); */ j = i-k; if (i == (R(d, k-1) + 1)) { strTemp.Format("%ld>%ld", i-1, j); cur_i = i-1; cur_j = j; k--; k_rest = 1; } else { if (i == (R(d, k+1))) { strTemp.Format("%ld<%ld", i, j-1); cur_i = i; cur_j = j-1; k++; k_rest = -1; } else { // if (i == (R(d, k) + 1)) strTemp.Format("%ld-%ld", i-1, j-1); cur_i = i-1; cur_j = j-1; // k=k; k_rest = 0; } } m_EditScript.SetAt(d, strTemp); // The following test is needed since our insertion/deletion indexes are // one greater than the stored i and/or j values from the R matrix. // It is possible that the previous comparison added some extra // entries to the R matrix than what was really needed. This will // cause extra erroneous entries to appear in the edit script. // However, since the indexes should be always increasing, we simply // filter out extra entries added to the end that don't satisfy // this condition: if ((k_rest == 0) && ((cur_i == last_i) && (cur_j == last_j))) { m_EditScript.RemoveAt(d); } last_i = cur_i; last_j = cur_j; } } // Note: if the two are identical, array stays empty: m_bEditScriptValid = TRUE; } // Deallocate Memory: delete[] T; delete[] Rvisitmin; delete[] Rvisitmax; for (i=0; i<dmax; i++) delete[] (Rm[i]); delete[] Rm; } break; } return nRetVal; } BOOL GetLastEditScript(CStringArray &anArray) { int i; anArray.RemoveAll(); if (!m_bEditScriptValid) return FALSE; anArray.SetSize(m_EditScript.GetSize()); for (i=0; i<m_EditScript.GetSize(); i++) anArray.SetAt(i, m_EditScript.GetAt(i)); return TRUE; } CString DiffFunctions(FUNC_COMPARE_METHOD nMethod, CFuncDescFile *pFile1, int nFile1FuncNdx, CFuncDescFile *pFile2, int nFile2FuncNdx, DWORD nOutputOptions, double &nMatchPercent, CSymbolMap *pSymbolMap) { CString strRetVal = ""; CString strEntry; CString strTemp; CStringArray oes; CStringArray Func1Lines; CStringArray Func2Lines; CFuncDesc *pFunction1; CFuncDesc *pFunction2; CFuncObject *pFuncObj; int i; int nLeftMax; int nRightMax; int nLeftIndex; int nRightIndex; int nLeftPos; int nRightPos; int nPos; if ((pFile1 == NULL) || (pFile2 == NULL)) return strRetVal; pFunction1 = pFile1->GetFunc(nFile1FuncNdx); pFunction2 = pFile2->GetFunc(nFile2FuncNdx); if ((pFunction1 == NULL) || (pFunction2 == NULL)) return strRetVal; nMatchPercent = CompareFunctions(nMethod, pFile1, nFile1FuncNdx, pFile2, nFile2FuncNdx, TRUE); if (!GetLastEditScript(oes)) return strRetVal; /* // The following is for special debugging only: for (i=0; i<oes.GetSize(); i++) { strRetVal += " " + oes.GetAt(i) + "\n"; } // return strRetVal; strRetVal += "\n"; */ nLeftMax = 0; for (i=0; i<pFunction1->GetSize(); i++) { pFuncObj = pFunction1->GetAt(i); if (pFuncObj == NULL) { Func1Lines.Add(""); continue; } strTemp = pFuncObj->CreateOutputLine(nOutputOptions); nLeftMax = __max(nLeftMax, strTemp.GetLength()); Func1Lines.Add(strTemp); } nRightMax = 0; for (i=0; i<pFunction2->GetSize(); i++) { pFuncObj = pFunction2->GetAt(i); if (pFuncObj == NULL) { Func2Lines.Add(""); continue; } strTemp = pFuncObj->CreateOutputLine(nOutputOptions); nRightMax = __max(nRightMax, strTemp.GetLength()); Func2Lines.Add(strTemp); } strTemp = ""; for (i=0; i<((nLeftMax-pFunction1->GetMainName().GetLength())/2); i++) strTemp += ' '; strRetVal += PadString(strTemp + pFunction1->GetMainName(), nLeftMax); strRetVal += " "; strTemp = ""; for (i=0; i<((nRightMax-pFunction2->GetMainName().GetLength())/2); i++) strTemp += ' '; strRetVal += PadString(strTemp + pFunction2->GetMainName(), nRightMax); strRetVal += "\n"; for (i=0; i<nLeftMax; i++) strRetVal += '-'; strRetVal += " "; for (i=0; i<nRightMax; i++) strRetVal += '-'; strRetVal += "\n"; nLeftPos = 0; nRightPos = 0; for (i=0; i<oes.GetSize(); i++) { strEntry = oes.GetAt(i); nPos = strEntry.FindOneOf("<->"); if (nPos == -1) continue; nLeftIndex = strtoul(strEntry.Left(nPos), NULL, 0); nRightIndex = strtoul(strEntry.Mid(nPos+1), NULL, 0); for (; ((nLeftPos < nLeftIndex) && (nRightPos < nRightIndex)); nLeftPos++, nRightPos++) { strRetVal += PadString(Func1Lines.GetAt(nLeftPos), nLeftMax); if (pFunction1->GetAt(nLeftPos)->IsExactMatch(pFunction2->GetAt(nRightPos))) { strRetVal += " == "; } else { strRetVal += " -- "; } strRetVal += Func2Lines.GetAt(nRightPos) + "\n"; if (pSymbolMap) pSymbolMap->AddObjectMapping(*pFunction1->GetAt(nLeftPos), *pFunction2->GetAt(nRightPos)); } ASSERT(nLeftPos == nLeftIndex); ASSERT(nRightPos == nRightIndex); #ifdef _DEBUG // The following is for special debugging only: if (nLeftPos != nLeftIndex) { strTemp.Format("\n\n*** ERROR: nLeftPos = %ld, Expected = %ld\n\n", nLeftPos, nLeftIndex); strRetVal += strTemp; nLeftPos = nLeftIndex; } if (nRightPos != nRightIndex) { strTemp.Format("\n\n*** ERROR: nRightPos = %ld, Expected = %ld\n\n", nRightPos, nRightIndex); strRetVal += strTemp; nRightPos = nRightIndex; } #endif #ifdef _DEBUG switch (strEntry.GetAt(nPos)) { case '<': if (nRightPos >= Func2Lines.GetSize()) { strRetVal += "\n\n*** ERROR: Right-Side Index Out-Of-Range!\n\n"; return strRetVal; } break; case '-': if (nLeftPos >= Func1Lines.GetSize()) { strRetVal += "\n\n*** ERROR: Left-Side Index Out-Of-Range!\n\n"; if (nRightPos >= Func2Lines.GetSize()) { strRetVal += "\n\n*** ERROR: Right-Side Index Out-Of-Range!\n\n"; } return strRetVal; } if (nRightPos >= Func2Lines.GetSize()) { strRetVal += "\n\n*** ERROR: Right-Side Index Out-Of-Range!\n\n"; return strRetVal; } break; case '>': if (nLeftPos >= Func1Lines.GetSize()) { strRetVal += "\n\n*** ERROR: Left-Side Index Out-Of-Range!\n\n"; return strRetVal; } break; } #endif switch (strEntry.GetAt(nPos)) { case '<': // Insert in Left strRetVal += PadString("", nLeftMax) + " << " + Func2Lines.GetAt(nRightPos) + "\n"; nRightPos++; break; case '-': // Change strRetVal += PadString(Func1Lines.GetAt(nLeftPos), nLeftMax) + " -> " + Func2Lines.GetAt(nRightPos) + "\n"; if (pSymbolMap) pSymbolMap->AddObjectMapping(*pFunction1->GetAt(nLeftPos), *pFunction2->GetAt(nRightPos)); nLeftPos++; nRightPos++; break; case '>': // Insert in Right strRetVal += PadString(Func1Lines.GetAt(nLeftPos), nLeftMax) + " >> \n"; nLeftPos++; break; } } nLeftIndex = Func1Lines.GetSize(); nRightIndex = Func2Lines.GetSize(); for (; ((nLeftPos < nLeftIndex) && (nRightPos < nRightIndex)); nLeftPos++, nRightPos++) { strRetVal += PadString(Func1Lines.GetAt(nLeftPos), nLeftMax); if (pFunction1->GetAt(nLeftPos)->IsExactMatch(pFunction2->GetAt(nRightPos))) { strRetVal += " == "; } else { strRetVal += " -- "; } strRetVal += Func2Lines.GetAt(nRightPos) + "\n"; if (pSymbolMap) pSymbolMap->AddObjectMapping(*pFunction1->GetAt(nLeftPos), *pFunction2->GetAt(nRightPos)); } return strRetVal; } <file_sep>/programs/m6811dis/inteldfc.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* INTELDFC -- IntelHex DataFileConverter Class This is the C++ IntelHex DataFileConverter Object Class Header File. It is a child of the DFC Object class. Author: <NAME> Date: January 29, 1997 Written in: Borland C++ 4.52 Updated: June 23, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. */ #ifndef INTELDFC_H #define INTELDFC_H #include <iostream> #include "dfc.h" #include "memclass.h" #include "errmsgs.h" class TDFC_Intel : virtual public CDFCObject { public: virtual std::string GetLibraryName(void) const { return "intel"; } virtual std::string GetShortDescription(void) const { return "Intel Hex Data File Converter"; } virtual std::string GetDescription(void) const { return "Intel Hex Data File Converter"; } const char *DefaultExtension(void) const { return "hex"; } int RetrieveFileMapping(std::istream *aFile, unsigned long NewBase, TMemRange *aRange) const; int ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc) const; int WriteDataFile(std::ostream *aFile, TMemRange *aRange, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc, int UsePhysicalAddr, unsigned int FillMode) const; private: int _ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, TMemRange *aRange, unsigned char aDesc) const; }; #endif // INTELDFC_H <file_sep>/programs/funcanal/FuncView/FuncDiffEditView.h // FuncDiffEditView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncDiffEditView.h,v $ // Revision 1.1 2003/09/13 05:45:39 dewhisna // Initial Revision // // #if !defined(AFX_FUNCDIFFEDITVIEW_H__70724D9C_D78A_4475_AB58_24E1DA5853DC__INCLUDED_) #define AFX_FUNCDIFFEDITVIEW_H__70724D9C_D78A_4475_AB58_24E1DA5853DC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "FuncViewPrjDoc.h" ///////////////////////////////////////////////////////////////////////////// // CFuncDiffEditView view class CFuncDiffEditView : public CEditView { protected: CFuncDiffEditView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CFuncDiffEditView) // Attributes public: CFuncViewPrjDoc* GetDocument(); CString m_strMatchPercentage; protected: CFuncViewFuncRef m_LeftFunc; CFuncViewFuncRef m_RightFunc; CFont m_fntEditor; friend class CChildFrame2; // Operations public: protected: void DoDiff(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFuncDiffEditView) public: virtual void OnInitialUpdate(); protected: virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); //}}AFX_VIRTUAL // Implementation protected: virtual ~CFuncDiffEditView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(CFuncDiffEditView) afx_msg void OnSymbolsAdd(); afx_msg void OnUpdateSymbolsAdd(CCmdUI* pCmdUI); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in FuncDiffEditView.cpp inline CFuncViewPrjDoc* CFuncDiffEditView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FUNCDIFFEDITVIEW_H__70724D9C_D78A_4475_AB58_24E1DA5853DC__INCLUDED_) <file_sep>/programs/funcanal/FuncView/ChildFrm6.cpp // ChildFrm6.cpp : implementation file // // Frame Window for the CompDiffEdit Views // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm6.cpp,v $ // Revision 1.1 2003/09/13 05:45:35 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ChildFrm6.h" #include "CompDiffEditView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrame6 IMPLEMENT_DYNCREATE(CChildFrame6, CChildFrameBase) CChildFrame6::CChildFrame6() { } CChildFrame6::~CChildFrame6() { } BEGIN_MESSAGE_MAP(CChildFrame6, CChildFrameBase) //{{AFX_MSG_MAP(CChildFrame6) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame6 message handlers BOOL CChildFrame6::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { ASSERT(pContext != NULL); pContext->m_pNewViewClass = RUNTIME_CLASS(CCompDiffEditView); if (CreateView(pContext, AFX_IDW_PANE_FIRST) == NULL) return FALSE; return TRUE; // return CChildFrameBase::OnCreateClient(lpcs, pContext); } <file_sep>/support/ASxxxx/readme.txt avxv5pxx_6811_no_opt.patch: The avxv5pxx_6811_no_opt.patch patch file was created to remove the direct addressing mode optimization in the 6811 Assembler, as described in the M6811 Code-Seeking Disassembler documentation. To apply, unzip the av5p06.zip file: On Linux and Mac, use: unzip -L -a av5p06.zip From the folder you unzip to, run: patch -p1 < avxv5pxx_6811_no_opt.patch On Windows, use: unzip av5p06.zip From the folder you unzip to, run: patch -p1 < avxv5pxx_6811_no_opt_windows.patch This will update the AS6811 assembler to not optimize addresses in the 0x0000-0x00FF range to Direct (S_DIR) Addressing Mode unless they are preceded by the "*" symbol and instead keep them as Extended (S_EXT) Addressing Mode. This is needed to make sure that code generated by the M6811DIS program, when reassembled with the AS6811 assembler, will produce the same original binary that was disassembled. <file_sep>/programs/funcanal/funcdesc.cpp // funcdesc.cpp: implementation of the CFuncDesc, CFuncDescFile, and CFuncObject classes. // // $Log: funcdesc.cpp,v $ // Revision 1.4 2003/09/13 05:38:03 dewhisna // Added Read/Write File support. Added output options on output line creation // for function diff and added returning of match percentage. Added callback // function for read operation feedback. Enhanced symbol map manipulation. // // Revision 1.3 2003/02/09 06:59:56 dewhisna // Split comparison logic from Function File I/O // // Revision 1.2 2002/09/15 22:54:02 dewhisna // Added Symbol Table comparison support // // Revision 1.1 2002/07/01 05:50:00 dewhisna // Initial Revision // // // // Format of Function Output File: // // Any line beginning with a ";" is considered to be a commment line and is ignored // // Memory Mapping: // #type|addr|size // | | |____ Size of Mapped area (hex) // | |_________ Absolute Address of Mapped area (hex) // |______________ Type of Mapped area (One of following: ROM, RAM, IO) // // Label Definitions: // !addr|label // | |____ Label(s) for this address(comma separated) // |_________ Absolute Address (hex) // // Start of New Function: // @xxxx|name // | |____ Name(s) of Function (comma separated list) // |_________ Absolute Address of Function Start relative to overall file (hex) // // Mnemonic Line (inside function): // xxxx|xxxx|label|xxxxxxxxxx|xxxxxx|xxxx|DST|SRC|mnemonic|operands // | | | | | | | | | |____ Disassembled operand output (ascii) // | | | | | | | | |_____________ Disassembled mnemonic (ascii) // | | | | | | |___|___________________ See below for SRC/DST format // | | | | | |___________________________ Addressing/Data bytes from operand portion of instruction (hex) // | | | | |_________________________________ Opcode bytes from instruction (hex) // | | | |__________________________________________ All bytes from instruction (hex) // | | |___________________________________________________ Label(s) for this address (comma separated list) // | |________________________________________________________ Absolute address of instruction (hex) // |_____________________________________________________________ Relative address of instruction to the function (hex) // // Data Byte Line (inside function): // xxxx|xxxx|label|xx // | | | |____ Data Byte (hex) // | | |_________ Label(s) for this address (comma separated) // | |______________ Absolute address of data byte (hex) // |___________________ Relative address of data byte to the function (hex) // // SRC and DST entries: // #xxxx Immediate Data Value (xxxx=hex value) // C@xxxx Absolute Code Address (xxxx=hex address) // C^n(xxxx) Relative Code Address (n=signed offset in hex, xxxx=resolved absolute address in hex) // C&xx(r) Register Code Offset (xx=hex offset, r=register number or name), ex: jmp 2,x -> "C$02(x)" // D@xxxx Absolute Data Address (xxxx=hex address) // D^n(xxxx) Relative Data Address (n=signed offset in hex, xxxx=resolved absolute address in hex) // D&xx(r) Register Data Offset (xx=hex offset, r=register number or name), ex: ldaa 1,y -> "D$01(y)" // // If any of the above also includes a mask, then the following will be added: // ,Mxx Value mask (xx=hex mask value) // // Note: The address sizes are consistent with the particular process. For example, an HC11 will // use 16-bit addresses (or 4 hex digits). The size of immediate data entries, offsets, and masks will // reflect the actual value. A 16-bit immediate value, offset, or mask, will be outputted as 4 hex // digits, but an 8-bit immediate value, offset, or mask, will be outputted as only 2 hex digits. // #include "stdafx.h" //#include "funcanal.h" #include "funcdesc.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif const static char m_strUnexpectedError[] = "Unexpected Error"; const static char m_strSyntaxError[] = "Syntax Error or Unexpected Entry"; const static char m_strOutOfMemoryError[] = "Out of Memory or Object Creation Error"; ////////////////////////////////////////////////////////////////////// // Static Functions ////////////////////////////////////////////////////////////////////// // ParseLine : Parses a line from the file and returns an array of // items from the specified separator. static void ParseLine(LPCTSTR pszLine, TCHAR cSepChar, CStringArray &argv) { CString strLine = pszLine; CString strTemp; int pos; argv.RemoveAll(); strLine += cSepChar; while (!strLine.IsEmpty()) { pos = strLine.Find(cSepChar); if (pos != -1) { strTemp = strLine.Left(pos); strTemp.TrimLeft(); strTemp.TrimRight(); strLine = strLine.Mid(pos+1); } else { strTemp = strLine; strTemp.TrimLeft(); strTemp.TrimRight(); strLine = ""; } argv.Add(strTemp); } } // ReadFileString : Reads a line from an open CFile object and // fills in a CString object and returns a BOOL // of EOF status. Is basically identical to // the CStdioFile ReadString function, but can // be any CFile derived object: static BOOL ReadFileString(CFile &rFile, CString &rString) { if (rFile.IsKindOf(RUNTIME_CLASS(CStdioFile))) return ((CStdioFile&)rFile).ReadString(rString); rString.Empty(); TCHAR c = 0; UINT nBytesRead; while (((nBytesRead = rFile.Read(&c, sizeof(c))) != 0) && (c != 10)) { if (c != 10) rString += c; } if ((!rString.IsEmpty()) && (rString.GetAt(rString.GetLength()-1) == 13)) rString = rString.Left(rString.GetLength()-1); return ((nBytesRead != 0) || (!rString.IsEmpty())); } // WriteFileString : Writes a line to an open CFile object using // LF -> CRLF conversion as defined for text // files. Is basically identical to the // CStdioFile WriteString function, but can be // any CFile derived object: static void WriteFileString(CFile &rFile, LPCTSTR pszString) { if (rFile.IsKindOf(RUNTIME_CLASS(CStdioFile))) { ((CStdioFile&)rFile).WriteString(pszString); return; } CString strString = pszString; int pos; while ((pos = strString.Find('\n')) != -1) { if (pos != 0) rFile.Write(LPCTSTR(strString), pos); rFile.Write("\r\n", 2); strString = strString.Mid(pos+1); } if (!strString.IsEmpty()) rFile.Write(LPCTSTR(strString), strString.GetLength()); } ////////////////////////////////////////////////////////////////////// // Global Functions ////////////////////////////////////////////////////////////////////// // PadString : Pads a string with spaces up to the specified length. CString PadString(LPCTSTR pszString, int nWidth) { CString strRetVal = pszString; while (strRetVal.GetLength() < nWidth) strRetVal += ' '; return strRetVal; } ////////////////////////////////////////////////////////////////////// // CFuncObject Class ////////////////////////////////////////////////////////////////////// CFuncObject::CFuncObject(CFuncDescFile &ParentFuncFile, CFuncDesc &ParentFunc, CStringArray &argv) : m_ParentFuncFile(ParentFuncFile), m_ParentFunc(ParentFunc) { ASSERT(argv.GetSize() >= 4); CStringArray strarrLabels; int i; CString strTemp; if (argv.GetSize() >= 1) m_dwRelFuncAddress = strtoul(argv[0], NULL, 16); if (argv.GetSize() >= 2) m_dwAbsAddress = strtoul(argv[1], NULL, 16); if (argv.GetSize() >= 3) { ParseLine(argv[2], ',', strarrLabels); for (i=0; i<strarrLabels.GetSize(); i++) AddLabel(strarrLabels.GetAt(i)); } if (argv.GetSize() >= 4) { strTemp = argv[3]; for (i=0; i<strTemp.GetLength()/2; i++) m_Bytes.Add((BYTE)strtoul(strTemp.Mid(i*2, 2), NULL, 16)); } } CFuncObject::~CFuncObject() { } BOOL CFuncObject::IsExactMatch(CFuncObject *pObj) { int i; if (pObj == NULL) return FALSE; if (m_Bytes.GetSize() != pObj->m_Bytes.GetSize()) return FALSE; for (i=0; i<m_Bytes.GetSize(); i++) if (m_Bytes.GetAt(i) != pObj->m_Bytes.GetAt(i)) return FALSE; return TRUE; } BOOL CFuncObject::AddLabel(LPCTSTR pszLabel) { CString strTemp; int i; if (pszLabel == NULL) return FALSE; strTemp = pszLabel; if (strTemp.IsEmpty()) return FALSE; // If we have the label already, return: for (i=0; i<m_LabelTable.GetSize(); i++) { if (strTemp.CompareNoCase(m_LabelTable.GetAt(i)) == 0) return FALSE; } m_LabelTable.Add(strTemp); return TRUE; } DWORD CFuncObject::GetRelFuncAddress() { return m_dwRelFuncAddress; } DWORD CFuncObject::GetAbsAddress() { return m_dwAbsAddress; } int CFuncObject::GetLabelCount() { return m_LabelTable.GetSize(); } CString CFuncObject::GetLabel(int nIndex) { return m_LabelTable.GetAt(nIndex); } CString CFuncObject::GetBytes() { CString strRetVal = ""; CString strTemp; int i; for (i=0; i<m_Bytes.GetSize(); i++) { strTemp.Format("%02X", m_Bytes.GetAt(i)); strRetVal += strTemp; } return strRetVal; } int CFuncObject::GetByteCount() { return m_Bytes.GetSize(); } void CFuncObject::GetSymbols(CStringArray &aSymbolArray) { // // This function, and its override, fills in the passed in array as follows: // Lxxxxxx -- Label for THIS object, "xxxxxx = Label" // RSCxxxxxx -- Referenced by THIS object -- Source, Code, "xxxxxx = Label" // RSDxxxxxx -- Referenced by THIS object -- Source, Data, "xxxxxx = Label" // RDCxxxxxx -- Referenced by THIS object -- Destination, Code, "xxxxxx = Label" // RDDxxxxxx -- Referenced by THIS object -- Destination, Data, "xxxxxx = Label" // CString strTemp; aSymbolArray.RemoveAll(); if (m_ParentFuncFile.AddrHasLabel(m_dwAbsAddress)) { strTemp = m_ParentFuncFile.GetPrimaryLabel(m_dwAbsAddress); if (!strTemp.IsEmpty()) { aSymbolArray.Add("L" + strTemp); } } } int CFuncObject::GetFieldWidth(FIELD_CODE nFC) { switch (nFC) { case FC_ADDRESS: return CALC_FIELD_WIDTH(7); case FC_OPBYTES: return CALC_FIELD_WIDTH(11); case FC_LABEL: return CALC_FIELD_WIDTH(13); case FC_MNEMONIC: return CALC_FIELD_WIDTH(7); case FC_OPERANDS: return CALC_FIELD_WIDTH(21); case FC_COMMENT: return CALC_FIELD_WIDTH(60); } return 0; } ////////////////////////////////////////////////////////////////////// // CFuncAsmInstObject Class ////////////////////////////////////////////////////////////////////// CFuncAsmInstObject::CFuncAsmInstObject(CFuncDescFile &ParentFuncFile, CFuncDesc &ParentFunc, CStringArray &argv) : CFuncObject(ParentFuncFile, ParentFunc, argv) { ASSERT(argv.GetSize() >= 10); int i; CString strTemp; if (argv.GetSize() >= 5) { strTemp = argv[4]; for (i=0; i<strTemp.GetLength()/2; i++) m_OpCodeBytes.Add((BYTE)strtoul(strTemp.Mid(i*2, 2), NULL, 16)); } if (argv.GetSize() >= 6) { strTemp = argv[5]; for (i=0; i<strTemp.GetLength()/2; i++) m_OperandBytes.Add((BYTE)strtoul(strTemp.Mid(i*2, 2), NULL, 16)); } if (argv.GetSize() >= 7) m_strDstOperand = argv[6]; if (argv.GetSize() >= 8) m_strSrcOperand = argv[7]; if (argv.GetSize() >= 9) m_strOpCodeText = argv[8]; if (argv.GetSize() >= 10) m_strOperandText = argv[9]; } CFuncAsmInstObject::~CFuncAsmInstObject() { } CString CFuncAsmInstObject::ExportToDiff() { CString strRetVal; CString strTemp; CString strTemp2; int i; DWORD nFuncStartAddr = m_ParentFunc.GetMainAddress(); DWORD nFuncSize = m_ParentFunc.GetFuncSize(); DWORD dwTemp; signed long snTemp; TMemRange zFuncRange(nFuncStartAddr, nFuncSize, 0); int pos; strRetVal.Format("C|%ld|", GetByteCount()); strRetVal += GetOpCodeBytes(); for (i=0; i<2; i++) { switch (i) { case 0: strTemp = m_strDstOperand; break; case 1: strTemp = m_strSrcOperand; break; } if (strTemp.IsEmpty()) continue; strRetVal += "|"; switch (strTemp.GetAt(0)) { case '#': // Immediate Data strRetVal += strTemp; break; case 'C': // Code addressing if (strTemp.GetLength() < 2) continue; switch (strTemp.GetAt(1)) { case '@': // Absolute dwTemp = strtoul(strTemp.Mid(2), NULL, 16); if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: strRetVal += "C=" + m_ParentFuncFile.GetPrimaryLabel(dwTemp); } else { // If there isn't a label, see if this absolute address lies inside the function: if (zFuncRange.AddressInRange(dwTemp)) { // If so, convert and treat as a relative address: snTemp = dwTemp - (GetAbsAddress() + GetByteCount()); strTemp2.Format("C^%c%lX", ((snTemp != labs(snTemp)) ? '-' : '+'), labs(snTemp)); strRetVal += strTemp2; } else { // Otherwise, it is an outside reference to something unknown: strRetVal += "C?"; } } // If there is a mask (or other appendage) add it: pos = strTemp.Find(','); if (pos != -1) strRetVal += strTemp.Mid(pos); break; case '^': // Relative // Relative addressing is always relative to the "next byte" after the instruction: if (strTemp.GetLength() < 3) continue; pos = strTemp.Find('(', 3); if (pos != -1) { strTemp2 = strTemp.Mid(3, pos-3); pos = strTemp2.Find(')'); if (pos != -1) strTemp2 = strTemp2.Left(pos); } else { strTemp2 = strTemp.Mid(3); pos = strTemp2.Find(','); if (pos != -1) strTemp2 = strTemp2.Left(pos); } snTemp = strtoul(strTemp2, NULL, 16); if (strTemp.GetAt(2) == '-') snTemp = 0 - snTemp; dwTemp = GetAbsAddress() + GetByteCount() + snTemp; // Resolve address if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: strRetVal += "C=" + m_ParentFuncFile.GetPrimaryLabel(dwTemp); } else { // If there isn't a label, see if this relative address lies inside the function: if (zFuncRange.AddressInRange(dwTemp)) { // If so, continue to treat it as a relative address: strTemp2.Format("C^%c%lX", ((snTemp != labs(snTemp)) ? '-' : '+'), labs(snTemp)); strRetVal += strTemp2; } else { // Otherwise, it is an outside reference to something unknown: strRetVal += "C?"; } } // If there is a mask (or other appendage) add it: pos = strTemp.Find(','); if (pos != -1) strRetVal += strTemp.Mid(pos); break; case '&': // Reg. Offset strRetVal += strTemp; break; } break; case 'D': // Data addressing if (strTemp.GetLength() < 2) continue; switch (strTemp.GetAt(1)) { case '@': // Absolute dwTemp = strtoul(strTemp.Mid(2), NULL, 16); if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: strRetVal += "D=" + m_ParentFuncFile.GetPrimaryLabel(dwTemp); } else { // If there isn't a label, see if this absolute address lies inside the function: if (zFuncRange.AddressInRange(dwTemp)) { // If so, convert and treat as a relative address: snTemp = dwTemp - (GetAbsAddress() + GetByteCount()); strTemp2.Format("D^%c%lX", ((snTemp != labs(snTemp)) ? '-' : '+'), labs(snTemp)); strRetVal += strTemp2; } else { // See if it is an I/O or NON-ROM/RAM location: if ((m_ParentFuncFile.IsIOMemAddr(dwTemp)) || (!m_ParentFuncFile.IsROMMemAddr(dwTemp) && !m_ParentFuncFile.IsRAMMemAddr(dwTemp))) { // If so, treat create a label to reference it as it is significant: strTemp2.Format("D=L%04lX", dwTemp); strRetVal += strTemp2; } else { // Otherwise, it is an outside reference to something unknown in RAM/ROM // and is probably a variable in memory that can move: strRetVal += "D?"; } } } // If there is a mask (or other appendage) add it: pos = strTemp.Find(','); if (pos != -1) strRetVal += strTemp.Mid(pos); break; case '^': // Relative // Relative addressing is always relative to the "next byte" after the instruction: if (strTemp.GetLength() < 3) continue; pos = strTemp.Find('(', 3); if (pos != -1) { strTemp2 = strTemp.Mid(3, pos-3); pos = strTemp2.Find(')'); if (pos != -1) strTemp2 = strTemp2.Left(pos); } else { strTemp2 = strTemp.Mid(3); pos = strTemp2.Find(','); if (pos != -1) strTemp2 = strTemp2.Left(pos); } snTemp = strtoul(strTemp2, NULL, 16); if (strTemp.GetAt(2) == '-') snTemp = 0 - snTemp; dwTemp = GetAbsAddress() + GetByteCount() + snTemp; // Resolve address if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: strRetVal += "D=" + m_ParentFuncFile.GetPrimaryLabel(dwTemp); } else { // If there isn't a label, see if this relative address lies inside the function: if (zFuncRange.AddressInRange(dwTemp)) { // If so, continue to treat it as a relative address: strTemp2.Format("D^%c%lX", ((snTemp != labs(snTemp)) ? '-' : '+'), labs(snTemp)); strRetVal += strTemp2; } else { // See if it is an I/O or NON-ROM/RAM location: if ((m_ParentFuncFile.IsIOMemAddr(dwTemp)) || (!m_ParentFuncFile.IsROMMemAddr(dwTemp) && !m_ParentFuncFile.IsRAMMemAddr(dwTemp))) { // If so, treat create a label to reference it as it is significant: strTemp2.Format("D=L%04lX", dwTemp); strRetVal += strTemp2; } else { // Otherwise, it is an outside reference to something unknown in RAM/ROM // and is probably a variable in memory that can move: strRetVal += "D?"; } } } // If there is a mask (or other appendage) add it: pos = strTemp.Find(','); if (pos != -1) strRetVal += strTemp.Mid(pos); break; case '&': // Reg. Offset strRetVal += strTemp; break; } break; } } return strRetVal; } void CFuncAsmInstObject::ExportToDiff(CStringArray &anArray) { anArray.Add(ExportToDiff()); } CString CFuncAsmInstObject::CreateOutputLine(DWORD nOutputOptions) { CString strRetVal = ""; CString strTemp; if (nOutputOptions & OO_ADD_ADDRESS) { strTemp.Format("%04lX ", m_dwAbsAddress); strRetVal += PadString(strTemp, GetFieldWidth(FC_ADDRESS)); } strTemp = m_ParentFunc.GetPrimaryLabel(m_dwAbsAddress); strRetVal += PadString(strTemp + ((!strTemp.IsEmpty()) ? ": " : " "), GetFieldWidth(FC_LABEL)); strRetVal += PadString(m_strOpCodeText + " ", GetFieldWidth(FC_MNEMONIC)); strRetVal += PadString(m_strOperandText, GetFieldWidth(FC_OPERANDS)); return strRetVal; } void CFuncAsmInstObject::GetSymbols(CStringArray &aSymbolArray) { CString strTemp; CString strTemp2; CString strLabelPrefix; int i; DWORD dwTemp; signed long snTemp; int pos; // Call parent to build initial list: CFuncObject::GetSymbols(aSymbolArray); for (i=0; i<2; i++) { switch (i) { case 0: strTemp = m_strDstOperand; strLabelPrefix = "RD"; break; case 1: strTemp = m_strSrcOperand; strLabelPrefix = "RS"; break; } if (strTemp.IsEmpty()) continue; switch (strTemp.GetAt(0)) { case '#': // Immediate Data break; case 'C': // Code addressing if (strTemp.GetLength() < 2) continue; switch (strTemp.GetAt(1)) { case '@': // Absolute dwTemp = strtoul(strTemp.Mid(2), NULL, 16); if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: aSymbolArray.Add(strLabelPrefix + "C" + m_ParentFuncFile.GetPrimaryLabel(dwTemp)); } else { // Else, build a label: strTemp2.Format("L%04lX", dwTemp); aSymbolArray.Add(strLabelPrefix + "C" + strTemp2); } break; case '^': // Relative // Relative addressing is always relative to the "next byte" after the instruction: if (strTemp.GetLength() < 3) continue; pos = strTemp.Find('(', 3); if (pos != -1) { strTemp2 = strTemp.Mid(3, pos-3); pos = strTemp2.Find(')'); if (pos != -1) strTemp2 = strTemp2.Left(pos); } else { strTemp2 = strTemp.Mid(3); pos = strTemp2.Find(','); if (pos != -1) strTemp2 = strTemp2.Left(pos); } snTemp = strtoul(strTemp2, NULL, 16); if (strTemp.GetAt(2) == '-') snTemp = 0 - snTemp; dwTemp = GetAbsAddress() + GetByteCount() + snTemp; // Resolve address if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: aSymbolArray.Add(strLabelPrefix + "C" + m_ParentFuncFile.GetPrimaryLabel(dwTemp)); } else { // Else, build a label: strTemp2.Format("L%04lX", dwTemp); aSymbolArray.Add(strLabelPrefix + "C" + strTemp2); } break; case '&': // Reg. Offset break; } break; case 'D': // Data addressing if (strTemp.GetLength() < 2) continue; switch (strTemp.GetAt(1)) { case '@': // Absolute dwTemp = strtoul(strTemp.Mid(2), NULL, 16); if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: aSymbolArray.Add(strLabelPrefix + "D" + m_ParentFuncFile.GetPrimaryLabel(dwTemp)); } else { // Else, build a label: strTemp2.Format("L%04lX", dwTemp); aSymbolArray.Add(strLabelPrefix + "D" + strTemp2); } break; case '^': // Relative // Relative addressing is always relative to the "next byte" after the instruction: if (strTemp.GetLength() < 3) continue; pos = strTemp.Find('(', 3); if (pos != -1) { strTemp2 = strTemp.Mid(3, pos-3); pos = strTemp2.Find(')'); if (pos != -1) strTemp2 = strTemp2.Left(pos); } else { strTemp2 = strTemp.Mid(3); pos = strTemp2.Find(','); if (pos != -1) strTemp2 = strTemp2.Left(pos); } snTemp = strtoul(strTemp2, NULL, 16); if (strTemp.GetAt(2) == '-') snTemp = 0 - snTemp; dwTemp = GetAbsAddress() + GetByteCount() + snTemp; // Resolve address if (m_ParentFuncFile.AddrHasLabel(dwTemp)) { // If the address has a user-defined file-level label, use it instead: aSymbolArray.Add(strLabelPrefix + "D" + m_ParentFuncFile.GetPrimaryLabel(dwTemp)); } else { // Else, build a label: strTemp2.Format("L%04lX", dwTemp); aSymbolArray.Add(strLabelPrefix + "D" + strTemp2); } break; case '&': // Reg. Offset break; } break; } } } CString CFuncAsmInstObject::GetOpCodeBytes() { CString strRetVal = ""; CString strTemp; int i; for (i=0; i<m_OpCodeBytes.GetSize(); i++) { strTemp.Format("%02X", m_OpCodeBytes.GetAt(i)); strRetVal += strTemp; } return strRetVal; } int CFuncAsmInstObject::GetOpCodeByteCount() { return m_OpCodeBytes.GetSize(); } CString CFuncAsmInstObject::GetOperandBytes() { CString strRetVal = ""; CString strTemp; int i; for (i=0; i<m_OperandBytes.GetSize(); i++) { strTemp.Format("%02X", m_OperandBytes.GetAt(i)); strRetVal += strTemp; } return strRetVal; } int CFuncAsmInstObject::GetOperandByteCount() { return m_OperandBytes.GetSize(); } ////////////////////////////////////////////////////////////////////// // CFuncDataByteObject Class ////////////////////////////////////////////////////////////////////// CFuncDataByteObject::CFuncDataByteObject(CFuncDescFile &ParentFuncFile, CFuncDesc &ParentFunc, CStringArray &argv) : CFuncObject(ParentFuncFile, ParentFunc, argv) { } CFuncDataByteObject::~CFuncDataByteObject() { } CString CFuncDataByteObject::ExportToDiff() { CString strRetVal; strRetVal.Format("D|%ld|", GetByteCount()); strRetVal += GetBytes(); return strRetVal; } void CFuncDataByteObject::ExportToDiff(CStringArray &anArray) { anArray.Add(ExportToDiff()); } CString CFuncDataByteObject::CreateOutputLine(DWORD nOutputOptions) { CString strRetVal = ""; CString strTemp; CString strTemp2; int i; if (nOutputOptions & OO_ADD_ADDRESS) { strTemp.Format("%04lX ", m_dwAbsAddress); strRetVal += PadString(strTemp, GetFieldWidth(FC_ADDRESS)); } strTemp = m_ParentFunc.GetPrimaryLabel(m_dwAbsAddress); strRetVal += PadString(strTemp + ((!strTemp.IsEmpty()) ? ": " : " "), GetFieldWidth(FC_LABEL)); strRetVal += PadString(".data ", GetFieldWidth(FC_MNEMONIC)); strTemp2 = ""; for (i=0; i<m_Bytes.GetSize(); i++) { if (i!=0) { strTemp.Format(", 0x%02X", m_Bytes.GetAt(i)); } else { strTemp.Format("0x%02X", m_Bytes.GetAt(i)); } strTemp2 += strTemp; } strRetVal += PadString(strTemp2, GetFieldWidth(FC_OPERANDS)); return strRetVal; } ////////////////////////////////////////////////////////////////////// // CFuncDesc Class ////////////////////////////////////////////////////////////////////// CFuncDesc::CFuncDesc(DWORD nAddress, LPCTSTR pszNames) { CStringArray argv; int i; m_dwFunctionSize = 0; m_dwMainAddress = nAddress; ParseLine(pszNames, ',', argv); for (i=0; i<argv.GetSize(); i++) AddName(nAddress, argv[i]); } CFuncDesc::~CFuncDesc() { FreeAll(); } void CFuncDesc::FreeAll() { CFuncObject *pFuncObject; int i; POSITION pos; DWORD anAddress; CStringArray *asArray; // Release function objects: for (i=0; i<GetSize(); i++) { pFuncObject = GetAt(i); if (pFuncObject) delete pFuncObject; } RemoveAll(); // Release names table: pos = m_FuncNameTable.GetStartPosition(); while (pos) { m_FuncNameTable.GetNextAssoc(pos, anAddress, asArray); if (asArray != NULL) delete asArray; } m_FuncNameTable.RemoveAll(); // Release label table: pos = m_LabelTable.GetStartPosition(); while (pos) { m_LabelTable.GetNextAssoc(pos, anAddress, asArray); if (asArray != NULL) delete asArray; } m_LabelTable.RemoveAll(); } BOOL CFuncDesc::AddName(DWORD nAddress, LPCTSTR pszLabel) { CStringArray *pNameList; CString strTemp; int i; if (pszLabel == NULL) return FALSE; strTemp = pszLabel; if (strTemp.IsEmpty()) return FALSE; if (m_FuncNameTable.Lookup(nAddress, pNameList)) { if (pNameList == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return FALSE; } // If we have the label already, return: for (i=0; i<pNameList->GetSize(); i++) { if (strTemp.CompareNoCase(pNameList->GetAt(i)) == 0) return FALSE; } } else { pNameList = new CStringArray; if (pNameList == NULL) AfxThrowMemoryException(); m_FuncNameTable.SetAt(nAddress, pNameList); } ASSERT(pNameList != NULL); pNameList->Add(strTemp); return TRUE; } CString CFuncDesc::GetMainName() { CStringArray *pNameList; CString strRetVal; strRetVal.Format("L%0lX", m_dwMainAddress); if (m_FuncNameTable.Lookup(m_dwMainAddress, pNameList)) { if (pNameList == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return strRetVal; } if (pNameList->GetSize() < 1) return strRetVal; if (pNameList->GetAt(0).Compare("???") == 0) return strRetVal; return pNameList->GetAt(0); } return strRetVal; } DWORD CFuncDesc::GetMainAddress() { return m_dwMainAddress; } BOOL CFuncDesc::AddLabel(DWORD nAddress, LPCTSTR pszLabel) { CStringArray *pLabelList; CString strTemp; int i; if (pszLabel == NULL) return FALSE; strTemp = pszLabel; if (strTemp.IsEmpty()) return FALSE; if (m_LabelTable.Lookup(nAddress, pLabelList)) { if (pLabelList == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return FALSE; } // If we have the label already, return: for (i=0; i<pLabelList->GetSize(); i++) { if (strTemp.CompareNoCase(pLabelList->GetAt(i)) == 0) return FALSE; } } else { pLabelList = new CStringArray; if (pLabelList == NULL) AfxThrowMemoryException(); m_LabelTable.SetAt(nAddress, pLabelList); } ASSERT(pLabelList != NULL); pLabelList->Add(strTemp); return TRUE; } BOOL CFuncDesc::AddrHasLabel(DWORD nAddress) { CStringArray *pLabelList; if (m_LabelTable.Lookup(nAddress, pLabelList)) return TRUE; return FALSE; } CString CFuncDesc::GetPrimaryLabel(DWORD nAddress) { CStringArray *pLabelList; if (m_LabelTable.Lookup(nAddress, pLabelList)) { if (pLabelList == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return ""; } if (pLabelList->GetSize()<1) return ""; return pLabelList->GetAt(0); } return ""; } CStringArray *CFuncDesc::GetLabelList(DWORD nAddress) { CStringArray *pLabelList; if (m_LabelTable.Lookup(nAddress, pLabelList)) return pLabelList; return NULL; } DWORD CFuncDesc::GetFuncSize() { // CFuncObject *pFuncObject; // int i; // DWORD nRetVal; // // nRetVal = 0; // // // Add byte counts to get size: // for (i=0; i<GetSize(); i++) { // pFuncObject = GetAt(i); // if (pFuncObject) nRetVal += pFuncObject->GetByteCount(); // } // // return nRetVal; // For efficiency, the above has been replaced with the following: return m_dwFunctionSize; } CString CFuncDesc::ExportToDiff() { CFuncObject *pFuncObject; int i; CString strRetVal; strRetVal = ""; // Concatenate output from each member object to create composite: for (i=0; i<GetSize(); i++) { pFuncObject = GetAt(i); if (pFuncObject) strRetVal += pFuncObject->ExportToDiff() + "\n"; } return strRetVal; } void CFuncDesc::ExportToDiff(CStringArray &anArray) { CFuncObject *pFuncObject; int i; anArray.RemoveAll(); // Add each item to array to create overall: for (i=0; i<GetSize(); i++) { pFuncObject = GetAt(i); if (pFuncObject) pFuncObject->ExportToDiff(anArray); } } int CFuncDesc::Add(CFuncObject *anObj) { int i; DWORD nObjAddress; if (anObj) { nObjAddress = anObj->GetAbsAddress(); for (i=0; i<anObj->GetLabelCount(); i++) { AddLabel(nObjAddress, anObj->GetLabel(i)); } m_dwFunctionSize += anObj->GetByteCount(); return CTypedPtrArray<CObArray, CFuncObject *>::Add(anObj); } return -1; } ////////////////////////////////////////////////////////////////////// // CFuncDescFile Class ////////////////////////////////////////////////////////////////////// CFuncDescFile::CFuncDescFile() : m_ROMMemMap(0, 0, 0), m_RAMMemMap(0, 0, 0), m_IOMemMap(0, 0, 0) { ParseCmdsOP1.SetAt("ROM", 0); ParseCmdsOP1.SetAt("RAM", 1); ParseCmdsOP1.SetAt("IO", 2); m_pfnProgressCallback = NULL; m_lParamProgressCallback = 0; } CFuncDescFile::~CFuncDescFile() { FreeAll(); } void CFuncDescFile::FreeAll() { POSITION pos; DWORD anAddress; CStringArray *asArray; CFuncDesc *pFuncDesc; int i; // Release Functions: for (i=0; i<m_Functions.GetSize(); i++) { pFuncDesc = m_Functions.GetAt(i); if (pFuncDesc) delete pFuncDesc; } m_Functions.RemoveAll(); // Release label table: pos = m_LabelTable.GetStartPosition(); while (pos) { m_LabelTable.GetNextAssoc(pos, anAddress, asArray); if (asArray != NULL) delete asArray; } m_LabelTable.RemoveAll(); } BOOL CFuncDescFile::ReadFuncDescFile(CFile& inFile, CFile *msgFile, CFile *errFile, int nStartLineCount) { CString strLine; CString strTemp; int nLineCount = nStartLineCount; CFuncDesc *pCurrentFunction = NULL; CFuncObject *pFuncObj; BOOL bRetVal = TRUE; CString strError = m_strUnexpectedError; WORD nParseVal; DWORD nTemp; DWORD nAddress; DWORD nSize; BOOL bTemp; CStringArray argv; int i,j; TMemRange *pMemRange; CDWordArray SortedList; CStringArray *pStrArray; POSITION mpos; #define BUSY_CALLBACK_RATE 50 #define BUSY_CALLBACK_RATE2 10 if (msgFile) { strTemp = "Reading Function Definition File \"" + inFile.GetFileName() + "\"...\n"; WriteFileString(*msgFile, strTemp); } m_strFilePathName = inFile.GetFilePath(); m_strFileName = inFile.GetFileName(); while ((bRetVal) && (ReadFileString(inFile, strLine))) { nLineCount++; strLine.TrimLeft(); strLine.TrimRight(); if ((m_pfnProgressCallback) && ((nLineCount % BUSY_CALLBACK_RATE) == 0)) m_pfnProgressCallback(0, 1, FALSE, m_lParamProgressCallback); // Empty lines are ignored: if (strLine.IsEmpty()) continue; switch (strLine.GetAt(0)) { case ';': // Comments // Ignore comment lines: break; case '#': // Memory Mapping pCurrentFunction = NULL; ParseLine(strLine.Mid(1), '|', argv); if (argv.GetSize() != 3) { strError = m_strSyntaxError; bRetVal = FALSE; break; } if (!ParseCmdsOP1.Lookup(argv[0], nParseVal)) { strError = m_strSyntaxError; bRetVal = FALSE; break; } nAddress = strtoul(argv[1], NULL, 16); nSize = strtoul(argv[2], NULL, 16); switch (nParseVal) { case 0: // ROM m_ROMMemMap.AddRange(nAddress, nSize, 0); m_ROMMemMap.Compact(); m_ROMMemMap.RemoveOverlaps(); m_ROMMemMap.Sort(); bTemp = TRUE; if (errFile) { for (nTemp = nAddress; ((nTemp < (nAddress + nSize)) && (bTemp)); nTemp++) { if (m_RAMMemMap.AddressInRange(nTemp)) { bTemp = FALSE; WriteFileString(*errFile, "*** Warning: Specified ROM Mapping conflicts with RAM Mapping\n"); } else { if (m_IOMemMap.AddressInRange(nTemp)) { bTemp = FALSE; WriteFileString(*errFile, "*** Warning: Specified ROM Mapping conflicts with IO Mapping\n"); } } } } break; case 1: // RAM m_RAMMemMap.AddRange(nAddress, nSize, 0); m_RAMMemMap.Compact(); m_RAMMemMap.RemoveOverlaps(); m_RAMMemMap.Sort(); bTemp = TRUE; if (errFile) { for (nTemp = nAddress; ((nTemp < (nAddress + nSize)) && (bTemp)); nTemp++) { if (m_ROMMemMap.AddressInRange(nTemp)) { bTemp = FALSE; WriteFileString(*errFile, "*** Warning: Specified RAM Mapping conflicts with ROM Mapping\n"); } else { if (m_IOMemMap.AddressInRange(nTemp)) { bTemp = FALSE; WriteFileString(*errFile, "*** Warning: Specified RAM Mapping conflicts with IO Mapping\n"); } } } } break; case 2: // IO m_IOMemMap.AddRange(nAddress, nSize, 0); m_IOMemMap.Compact(); m_IOMemMap.RemoveOverlaps(); m_IOMemMap.Sort(); bTemp = TRUE; if (errFile) { for (nTemp = nAddress; ((nTemp < (nAddress + nSize)) && (bTemp)); nTemp++) { if (m_ROMMemMap.AddressInRange(nTemp)) { bTemp = FALSE; WriteFileString(*errFile, "*** Warning: Specified IO Mapping conflicts with ROM Mapping\n"); } else { if (m_RAMMemMap.AddressInRange(nTemp)) { bTemp = FALSE; WriteFileString(*errFile, "*** Warning: Specified IO Mapping conflicts with RAM Mapping\n"); } } } } break; } break; case '!': // Label pCurrentFunction = NULL; ParseLine(strLine.Mid(1), '|', argv); if (argv.GetSize() != 2) { strError = m_strSyntaxError; bRetVal = FALSE; break; } nAddress = strtoul(argv[0], NULL, 16); ParseLine(argv[1], ',', argv); for (i=0; i<argv.GetSize(); i++) { AddLabel(nAddress, argv[i]); } break; case '@': // New Function declaration: pCurrentFunction = NULL; ParseLine(strLine.Mid(1), '|', argv); if (argv.GetSize() != 2) { strError = m_strSyntaxError; bRetVal = FALSE; break; } nAddress = strtoul(argv[0], NULL, 16); pCurrentFunction = new CFuncDesc(nAddress, argv[1]); if (pCurrentFunction == NULL) { strError = m_strOutOfMemoryError; bRetVal = FALSE; break; } m_Functions.Add(pCurrentFunction); break; default: // See if we are in the middle of a function declaration: if (pCurrentFunction == NULL) { // If we aren't in a function, it's a syntax error: strError = m_strSyntaxError; bRetVal = FALSE; break; } // If we are in a function, parse entry: if (isxdigit(strLine.GetAt(0))) { ParseLine(strLine, '|', argv); if ((argv.GetSize() != 4) && (argv.GetSize() != 10)) { strError = m_strSyntaxError; bRetVal = FALSE; break; } pFuncObj = NULL; if (argv.GetSize() == 4) { pFuncObj = new CFuncDataByteObject(*this, *pCurrentFunction, argv); } else { pFuncObj = new CFuncAsmInstObject(*this, *pCurrentFunction, argv); } pCurrentFunction->Add(pFuncObj); } else { strError = m_strSyntaxError; bRetVal = FALSE; } break; } } if ((bRetVal) && (msgFile)) { WriteFileString(*msgFile, "\n"); WriteFileString(*msgFile, " Memory Mappings:\n"); WriteFileString(*msgFile, " ROM Memory Map:"); if (m_ROMMemMap.IsNullRange()) { WriteFileString(*msgFile, " <Not Defined>\n"); } else { WriteFileString(*msgFile, "\n"); pMemRange = &m_ROMMemMap; while (pMemRange) { strTemp.Format(" 0x%04lX - 0x%04lX (Size: 0x%04lX)\n", pMemRange->GetStartAddr(), pMemRange->GetStartAddr() + pMemRange->GetSize() - 1, pMemRange->GetSize()); WriteFileString(*msgFile, strTemp); pMemRange = pMemRange->GetNext(); } } WriteFileString(*msgFile, " RAM Memory Map:"); if (m_RAMMemMap.IsNullRange()) { WriteFileString(*msgFile, " <Not Defined>\n"); } else { WriteFileString(*msgFile, "\n"); pMemRange = &m_RAMMemMap; while (pMemRange) { strTemp.Format(" 0x%04lX - 0x%04lX (Size: 0x%04lX)\n", pMemRange->GetStartAddr(), pMemRange->GetStartAddr() + pMemRange->GetSize() - 1, pMemRange->GetSize()); WriteFileString(*msgFile, strTemp); pMemRange = pMemRange->GetNext(); } } WriteFileString(*msgFile, " IO Memory Map:"); if (m_IOMemMap.IsNullRange()) { WriteFileString(*msgFile, " <Not Defined>\n"); } else { WriteFileString(*msgFile, "\n"); pMemRange = &m_IOMemMap; while (pMemRange) { strTemp.Format(" 0x%04lX - 0x%04lX (Size: 0x%04lX)\n", pMemRange->GetStartAddr(), pMemRange->GetStartAddr() + pMemRange->GetSize() - 1, pMemRange->GetSize()); WriteFileString(*msgFile, strTemp); pMemRange = pMemRange->GetNext(); } } WriteFileString(*msgFile, "\n"); strTemp.Format(" %ld Function%s defined%s\n", m_Functions.GetSize(), ((m_Functions.GetSize() != 1) ? "s" : ""), ((m_Functions.GetSize() != 0) ? ":" : "")); WriteFileString(*msgFile, strTemp); for (i=0; i<m_Functions.GetSize(); i++) { strTemp.Format(" %04lX -> %s\n", m_Functions.GetAt(i)->GetMainAddress(), LPCTSTR(m_Functions.GetAt(i)->GetMainName())); WriteFileString(*msgFile, strTemp); if ((m_pfnProgressCallback) && ((i % BUSY_CALLBACK_RATE2) == 0)) m_pfnProgressCallback(0, 1, FALSE, m_lParamProgressCallback); } WriteFileString(*msgFile, "\n"); strTemp.Format(" %ld Unique Label%s Defined%s\n", m_LabelTable.GetCount(), ((m_LabelTable.GetCount() != 1) ? "s" : ""), ((m_LabelTable.GetCount() != 0) ? ":" : "")); WriteFileString(*msgFile, strTemp); SortedList.RemoveAll(); mpos = m_LabelTable.GetStartPosition(); while (mpos) { m_LabelTable.GetNextAssoc(mpos, nAddress, pStrArray); bTemp = FALSE; for (i=0; ((i<SortedList.GetSize()) && (bTemp == FALSE)); i++) { if (nAddress <= SortedList.GetAt(i)) { SortedList.InsertAt(i, nAddress); bTemp = TRUE; } } if (bTemp == FALSE) SortedList.Add(nAddress); } for (i=0; i<SortedList.GetSize(); i++) { m_LabelTable.Lookup(SortedList.GetAt(i), pStrArray); strTemp.Format(" 0x%04lX=", SortedList.GetAt(i)); WriteFileString(*msgFile, strTemp); if (pStrArray) { for (j=0; j<pStrArray->GetSize(); j++) { if (j != 0) WriteFileString(*msgFile, ","); WriteFileString(*msgFile, pStrArray->GetAt(j)); } } WriteFileString(*msgFile, "\n"); if ((m_pfnProgressCallback) && ((i % BUSY_CALLBACK_RATE2) == 0)) m_pfnProgressCallback(0, 1, FALSE, m_lParamProgressCallback); } WriteFileString(*msgFile, "\n"); } if ((bRetVal == FALSE) && (errFile)) { strTemp.Format("*** Error: %s : on line %ld of file\n \"%s\"\n", LPCTSTR(strError), nLineCount, LPCTSTR(inFile.GetFilePath())); WriteFileString(*errFile, strTemp); } return bRetVal; } BOOL CFuncDescFile::AddLabel(DWORD nAddress, LPCTSTR pszLabel) { CStringArray *pLabelList; CString strTemp; int i; if (pszLabel == NULL) return FALSE; strTemp = pszLabel; if (strTemp.IsEmpty()) return FALSE; if (m_LabelTable.Lookup(nAddress, pLabelList)) { if (pLabelList == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return FALSE; } // If we have the label already, return: for (i=0; i<pLabelList->GetSize(); i++) { if (strTemp.CompareNoCase(pLabelList->GetAt(i)) == 0) return FALSE; } } else { pLabelList = new CStringArray; if (pLabelList == NULL) AfxThrowMemoryException(); m_LabelTable.SetAt(nAddress, pLabelList); } ASSERT(pLabelList != NULL); pLabelList->Add(strTemp); return TRUE; } BOOL CFuncDescFile::AddrHasLabel(DWORD nAddress) { CStringArray *pLabelList; if (m_LabelTable.Lookup(nAddress, pLabelList)) return TRUE; return FALSE; } CString CFuncDescFile::GetPrimaryLabel(DWORD nAddress) { CStringArray *pLabelList; if (m_LabelTable.Lookup(nAddress, pLabelList)) { if (pLabelList == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return ""; } if (pLabelList->GetSize()<1) return ""; return pLabelList->GetAt(0); } return ""; } CStringArray *CFuncDescFile::GetLabelList(DWORD nAddress) { CStringArray *pLabelList; if (m_LabelTable.Lookup(nAddress, pLabelList)) return pLabelList; return NULL; } int CFuncDescFile::GetFuncCount() { return m_Functions.GetSize(); } CFuncDesc *CFuncDescFile::GetFunc(int nIndex) { return m_Functions.GetAt(nIndex); } CString CFuncDescFile::GetFuncPathName() { return m_strFilePathName; } CString CFuncDescFile::GetFuncFileName() { return m_strFileName; } BOOL CFuncDescFile::IsROMMemAddr(DWORD nAddress) { return m_ROMMemMap.AddressInRange(nAddress); } BOOL CFuncDescFile::IsRAMMemAddr(DWORD nAddress) { return m_RAMMemMap.AddressInRange(nAddress); } BOOL CFuncDescFile::IsIOMemAddr(DWORD nAddress) { return m_IOMemMap.AddressInRange(nAddress); } ////////////////////////////////////////////////////////////////////// // CFuncDescFileArray Class ////////////////////////////////////////////////////////////////////// CFuncDescFileArray::CFuncDescFileArray() { m_pfnProgressCallback = NULL; m_lParamProgressCallback = 0; } CFuncDescFileArray::~CFuncDescFileArray() { FreeAll(); } void CFuncDescFileArray::FreeAll() { CFuncDescFile *pFuncDescFileObj; int i; // Release function objects: for (i=0; i<GetSize(); i++) { pFuncDescFileObj = GetAt(i); if (pFuncDescFileObj) delete pFuncDescFileObj; } RemoveAll(); } int CFuncDescFileArray::GetFuncCount() { int nRetVal = 0; int i; CFuncDescFile *pFuncDescFile; for (i=0; i<GetSize(); i++) { pFuncDescFile = GetAt(i); if (pFuncDescFile == NULL) continue; nRetVal += pFuncDescFile->GetFuncCount(); } return nRetVal; } double CFuncDescFileArray::CompareFunctions(FUNC_COMPARE_METHOD nMethod, int nFile1Ndx, int nFile1FuncNdx, int nFile2Ndx, int nFile2FuncNdx, BOOL bBuildEditScript) { CFuncDescFile *pFuncDescFile1Obj; CFuncDescFile *pFuncDescFile2Obj; pFuncDescFile1Obj = GetAt(nFile1Ndx); pFuncDescFile2Obj = GetAt(nFile2Ndx); return ::CompareFunctions(nMethod, pFuncDescFile1Obj, nFile1FuncNdx, pFuncDescFile2Obj, nFile2FuncNdx, bBuildEditScript); } CString CFuncDescFileArray::DiffFunctions(FUNC_COMPARE_METHOD nMethod, int nFile1Ndx, int nFile1FuncNdx, int nFile2Ndx, int nFile2FuncNdx, DWORD nOutputOptions, double &nMatchPercent, CSymbolMap *pSymbolMap) { CFuncDescFile *pFuncDescFile1Obj; CFuncDescFile *pFuncDescFile2Obj; pFuncDescFile1Obj = GetAt(nFile1Ndx); pFuncDescFile2Obj = GetAt(nFile2Ndx); return ::DiffFunctions(nMethod, pFuncDescFile1Obj, nFile1FuncNdx, pFuncDescFile2Obj, nFile2FuncNdx, nOutputOptions, nMatchPercent, pSymbolMap); } ////////////////////////////////////////////////////////////////////// // CSymbolMap Class ////////////////////////////////////////////////////////////////////// CSymbolMap::CSymbolMap() { } CSymbolMap::~CSymbolMap() { FreeAll(); } void CSymbolMap::FreeAll() { CStringArray *pArray; CString strTemp; POSITION pos; pos = m_LeftSideCodeSymbols.GetStartPosition(); while (pos) { m_LeftSideCodeSymbols.GetNextAssoc(pos, strTemp, pArray); if (pArray != NULL) delete pArray; } m_LeftSideCodeSymbols.RemoveAll(); pos = m_RightSideCodeSymbols.GetStartPosition(); while (pos) { m_RightSideCodeSymbols.GetNextAssoc(pos, strTemp, pArray); if (pArray != NULL) delete pArray; } m_RightSideCodeSymbols.RemoveAll(); pos = m_LeftSideDataSymbols.GetStartPosition(); while (pos) { m_LeftSideDataSymbols.GetNextAssoc(pos, strTemp, pArray); if (pArray != NULL) delete pArray; } m_LeftSideDataSymbols.RemoveAll(); pos = m_RightSideDataSymbols.GetStartPosition(); while (pos) { m_RightSideDataSymbols.GetNextAssoc(pos, strTemp, pArray); if (pArray != NULL) delete pArray; } m_RightSideDataSymbols.RemoveAll(); } BOOL CSymbolMap::IsEmpty() { if (m_LeftSideCodeSymbols.GetCount() != 0) return FALSE; if (m_RightSideCodeSymbols.GetCount() != 0) return FALSE; if (m_LeftSideDataSymbols.GetCount() != 0) return FALSE; if (m_RightSideDataSymbols.GetCount() != 0) return FALSE; return TRUE; } void CSymbolMap::AddObjectMapping(CFuncObject &aLeftObject, CFuncObject &aRightObject) { CStringArray arrLeftSymbols; CStringArray arrRightSymbols; int i; int j; CString strTemp1; CString strTemp2; BOOL bFlag; BOOL bFlag2; int nMode; // 0 = Source, 1 = Destination int nType; // 0 = Code, 1 = Data aLeftObject.GetSymbols(arrLeftSymbols); aRightObject.GetSymbols(arrRightSymbols); // Since we are comparing functions, any "L" entries are automatically "Code" entries: for (i=0; i<arrLeftSymbols.GetSize(); i++) { strTemp1 = arrLeftSymbols.GetAt(i); if ((strTemp1.IsEmpty()) || (strTemp1.GetAt(0) != 'L')) continue; if (strTemp1.GetLength() < 2) continue; bFlag = FALSE; for (j=0; j<arrRightSymbols.GetSize(); j++) { strTemp2 = arrRightSymbols.GetAt(j); if ((strTemp2.IsEmpty()) || (strTemp2.GetAt(0) != 'L')) continue; if (strTemp2.GetLength() < 2) continue; AddLeftSideCodeSymbol(strTemp1.Mid(1), strTemp2.Mid(1)); bFlag = TRUE; } if (!bFlag) AddLeftSideCodeSymbol(strTemp1.Mid(1), ""); } for (i=0; i<arrRightSymbols.GetSize(); i++) { strTemp1 = arrRightSymbols.GetAt(i); if ((strTemp1.IsEmpty()) || (strTemp1.GetAt(0) != 'L')) continue; if (strTemp1.GetLength() < 2) continue; bFlag = FALSE; for (j=0; j<arrLeftSymbols.GetSize(); j++) { strTemp2 = arrLeftSymbols.GetAt(j); if ((strTemp2.IsEmpty()) || (strTemp2.GetAt(0) != 'L')) continue; if (strTemp2.GetLength() < 2) continue; AddRightSideCodeSymbol(strTemp1.Mid(1), strTemp2.Mid(1)); bFlag = TRUE; } if (!bFlag) AddRightSideCodeSymbol(strTemp1.Mid(1), ""); } // Add Left Source/Destination entries: for (i=0; i<arrLeftSymbols.GetSize(); i++) { strTemp1 = arrLeftSymbols.GetAt(i); if ((strTemp1.IsEmpty()) || (strTemp1.GetAt(0) != 'R')) continue; if (strTemp1.GetLength() < 4) continue; switch (strTemp1.GetAt(1)) { case 'S': nMode = 0; break; case 'D': nMode = 1; break; default: continue; } switch (strTemp1.GetAt(2)) { case 'C': nType = 0; break; case 'D': nType = 1; break; default: continue; } bFlag = FALSE; for (j=0; j<arrRightSymbols.GetSize(); j++) { strTemp2 = arrRightSymbols.GetAt(j); if ((strTemp2.IsEmpty()) || (strTemp2.GetAt(0) != 'R')) continue; if (strTemp2.GetLength() < 4) continue; bFlag2 = FALSE; switch (strTemp2.GetAt(1)) { case 'S': if (nMode == 0) { bFlag2 = TRUE; } break; case 'D': if (nMode == 1) { bFlag2 = TRUE; } break; default: continue; } if (bFlag2) { switch (strTemp2.GetAt(2)) { case 'C': if (nType == 0) { AddLeftSideCodeSymbol(strTemp1.Mid(3), strTemp2.Mid(3)); bFlag = TRUE; } break; case 'D': if (nType == 1) { AddLeftSideDataSymbol(strTemp1.Mid(3), strTemp2.Mid(3)); bFlag = TRUE; } break; default: continue; } } } if (!bFlag) { switch (nType) { case 0: AddLeftSideCodeSymbol(strTemp1.Mid(3), ""); break; case 1: AddLeftSideDataSymbol(strTemp1.Mid(3), ""); break; } } } // Add Right Source/Destination entries: for (i=0; i<arrRightSymbols.GetSize(); i++) { strTemp1 = arrRightSymbols.GetAt(i); if ((strTemp1.IsEmpty()) || (strTemp1.GetAt(0) != 'R')) continue; if (strTemp1.GetLength() < 4) continue; switch (strTemp1.GetAt(1)) { case 'S': nMode = 0; break; case 'D': nMode = 1; break; default: continue; } switch (strTemp1.GetAt(2)) { case 'C': nType = 0; break; case 'D': nType = 1; break; default: continue; } bFlag = FALSE; for (j=0; j<arrLeftSymbols.GetSize(); j++) { strTemp2 = arrLeftSymbols.GetAt(j); if ((strTemp2.IsEmpty()) || (strTemp2.GetAt(0) != 'R')) continue; if (strTemp2.GetLength() < 4) continue; bFlag2 = FALSE; switch (strTemp2.GetAt(1)) { case 'S': if (nMode == 0) { bFlag2 = TRUE; } break; case 'D': if (nMode == 1) { bFlag2 = TRUE; } break; default: continue; } if (bFlag2) { switch (strTemp2.GetAt(2)) { case 'C': if (nType == 0) { AddRightSideCodeSymbol(strTemp1.Mid(3), strTemp2.Mid(3)); bFlag = TRUE; } break; case 'D': if (nType == 1) { AddRightSideDataSymbol(strTemp1.Mid(3), strTemp2.Mid(3)); bFlag = TRUE; } break; default: continue; } } } if (!bFlag) { switch (nType) { case 0: AddRightSideCodeSymbol(strTemp1.Mid(3), ""); break; case 1: AddRightSideDataSymbol(strTemp1.Mid(3), ""); break; } } } } void CSymbolMap::GetLeftSideCodeSymbolList(CStringArray &anArray) { GetSymbolList(m_LeftSideCodeSymbols, anArray); } void CSymbolMap::GetRightSideCodeSymbolList(CStringArray &anArray) { GetSymbolList(m_RightSideCodeSymbols, anArray); } void CSymbolMap::GetLeftSideDataSymbolList(CStringArray &anArray) { GetSymbolList(m_LeftSideDataSymbols, anArray); } void CSymbolMap::GetRightSideDataSymbolList(CStringArray &anArray) { GetSymbolList(m_RightSideDataSymbols, anArray); } void CSymbolMap::GetSymbolList(CMap<CString, LPCTSTR, CStringArray*, CStringArray*> &mapSymbolArrays, CStringArray &anArray) { POSITION pos; CString strTemp; CStringArray *pArray; int i; anArray.RemoveAll(); pos = mapSymbolArrays.GetStartPosition(); while (pos) { mapSymbolArrays.GetNextAssoc(pos, strTemp, pArray); for (i=0; i<anArray.GetSize(); i++) { if (strTemp < anArray.GetAt(i)) break; } anArray.InsertAt(i, strTemp); } } DWORD CSymbolMap::GetLeftSideCodeHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray) { return GetHitList(m_LeftSideCodeSymbols, aSymbol, aSymbolArray, aHitCountArray); } DWORD CSymbolMap::GetRightSideCodeHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray) { return GetHitList(m_RightSideCodeSymbols, aSymbol, aSymbolArray, aHitCountArray); } DWORD CSymbolMap::GetLeftSideDataHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray) { return GetHitList(m_LeftSideDataSymbols, aSymbol, aSymbolArray, aHitCountArray); } DWORD CSymbolMap::GetRightSideDataHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray) { return GetHitList(m_RightSideDataSymbols, aSymbol, aSymbolArray, aHitCountArray); } DWORD CSymbolMap::GetHitList(CMap<CString, LPCTSTR, CStringArray*, CStringArray*> &mapSymbolArrays, LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray) { CStringArray *pArray; CMap<CString, LPCTSTR, DWORD, DWORD> mapSymbols; int i; CString strTemp; POSITION pos; DWORD nTemp; DWORD nTotal = 0; aSymbolArray.RemoveAll(); aHitCountArray.RemoveAll(); if (mapSymbolArrays.Lookup(aSymbol, pArray)) { if (pArray) { for (i=0; i<pArray->GetSize(); i++) { strTemp = pArray->GetAt(i); if (mapSymbols.Lookup(strTemp, nTemp)) { mapSymbols.SetAt(strTemp, nTemp+1); } else { mapSymbols.SetAt(strTemp, 1); } } pos = mapSymbols.GetStartPosition(); while (pos) { mapSymbols.GetNextAssoc(pos, strTemp, nTemp); for (i=0; i<aHitCountArray.GetSize(); i++) { if (nTemp > aHitCountArray.GetAt(i)) break; if (nTemp == aHitCountArray.GetAt(i)) { if (aSymbolArray.GetAt(i).IsEmpty()) break; if ((strTemp < aSymbolArray.GetAt(i)) && (!strTemp.IsEmpty())) break; } } aSymbolArray.InsertAt(i, strTemp); aHitCountArray.InsertAt(i, nTemp); } nTotal = pArray->GetSize(); } } return nTotal; } /* void CSymbolMap::SortStringArray(CStringArray &aStringArray) { // Sort an array of strings. Here, we'll just use bubble sorting // as the number of string entries should be relatively small: CString strTemp; int i; int j; for (i=0; i<aStringArray.GetSize()-1; i++) { for (j=i+1; j<aStringArray.GetSize(); j++) { if (aStringArray.GetAt(i).Compare(aStringArray.GetAt(j)) > 0) { strTemp = aStringArray.GetAt(j); aStringArray.SetAt(j, aStringArray.GetAt(i)); aStringArray.SetAt(i, strTemp); } } } } */ /* void CSymbolMap::SortStringDWordArray(CStringArray &aStringArray, CDWordArray &aDWordArray) { // Sort an array of strings along with an array of numbers. Since the numbers // are "hit counts", we want them to have precedence in the sort, so we will // sort but numbers and then by string. We'll just use bubble sorting // as the number of entries should be relatively small: CString strTemp; DWORD nTemp; int i; int j; ASSERT(aStringArray.GetSize() == aDWordArray.GetSize()); // The two arrays must have same number of elements! for (i=0; i<aStringArray.GetSize()-1; i++) { for (j=i+1; j<aStringArray.GetSize(); j++) { if ((aDWordArray.GetAt(i) < aDWordArray.GetAt(j)) || ((aDWordArray.GetAt(i) == aDWordArray.GetAt(j)) && ((aStringArray.GetAt(i).Compare(aStringArray.GetAt(j)) > 0) || (aStringArray.GetAt(i).IsEmpty())))) { strTemp = aStringArray.GetAt(j); aStringArray.SetAt(j, aStringArray.GetAt(i)); aStringArray.SetAt(i, strTemp); nTemp = aDWordArray.GetAt(j); aDWordArray.SetAt(j, aDWordArray.GetAt(i)); aDWordArray.SetAt(i, nTemp); } } } } */ void CSymbolMap::AddLeftSideCodeSymbol(LPCTSTR aLeftSymbol, LPCTSTR aRightSymbol) { CStringArray *pArray; if (m_LeftSideCodeSymbols.Lookup(aLeftSymbol, pArray)) { if (pArray == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return; } } else { pArray = new CStringArray; if (pArray == NULL) AfxThrowMemoryException(); m_LeftSideCodeSymbols.SetAt(aLeftSymbol, pArray); } ASSERT(pArray != NULL); pArray->Add(aRightSymbol); } void CSymbolMap::AddRightSideCodeSymbol(LPCTSTR aRightSymbol, LPCTSTR aLeftSymbol) { CStringArray *pArray; if (m_RightSideCodeSymbols.Lookup(aRightSymbol, pArray)) { if (pArray == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return; } } else { pArray = new CStringArray; if (pArray == NULL) AfxThrowMemoryException(); m_RightSideCodeSymbols.SetAt(aRightSymbol, pArray); } ASSERT(pArray != NULL); pArray->Add(aLeftSymbol); } void CSymbolMap::AddLeftSideDataSymbol(LPCTSTR aLeftSymbol, LPCTSTR aRightSymbol) { CStringArray *pArray; if (m_LeftSideDataSymbols.Lookup(aLeftSymbol, pArray)) { if (pArray == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return; } } else { pArray = new CStringArray; if (pArray == NULL) AfxThrowMemoryException(); m_LeftSideDataSymbols.SetAt(aLeftSymbol, pArray); } ASSERT(pArray != NULL); pArray->Add(aRightSymbol); } void CSymbolMap::AddRightSideDataSymbol(LPCTSTR aRightSymbol, LPCTSTR aLeftSymbol) { CStringArray *pArray; if (m_RightSideDataSymbols.Lookup(aRightSymbol, pArray)) { if (pArray == NULL) { ASSERT(FALSE); // We should never encounter a null entry -- check adding! return; } } else { pArray = new CStringArray; if (pArray == NULL) AfxThrowMemoryException(); m_RightSideDataSymbols.SetAt(aRightSymbol, pArray); } ASSERT(pArray != NULL); pArray->Add(aLeftSymbol); } <file_sep>/programs/funcanal/FuncView/ChildFrm4.cpp // ChildFrm4.cpp : implementation file // // Frame Window for the Output Views // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm4.cpp,v $ // Revision 1.1 2003/09/13 05:45:34 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ChildFrm4.h" #include "OutputView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrame4 IMPLEMENT_DYNCREATE(CChildFrame4, CChildFrameBase) CChildFrame4::CChildFrame4() { m_pOutputView = NULL; } CChildFrame4::~CChildFrame4() { } BEGIN_MESSAGE_MAP(CChildFrame4, CChildFrameBase) //{{AFX_MSG_MAP(CChildFrame4) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame4 message handlers BOOL CChildFrame4::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { ASSERT(pContext != NULL); pContext->m_pNewViewClass = RUNTIME_CLASS(COutputView); m_pOutputView = (COutputView *)CreateView(pContext, AFX_IDW_PANE_FIRST); if (m_pOutputView == NULL) return FALSE; return TRUE; // return CChildFrameBase::OnCreateClient(lpcs, pContext); } <file_sep>/programs/funcanal/FuncView/ChildFrm2.cpp // ChildFrm2.cpp : implementation file // // Frame Window for the Function Diff Views // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm2.cpp,v $ // Revision 1.1 2003/09/13 05:45:32 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ChildFrm2.h" #include "FuncListView.h" #include "FuncDiffEditView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_MATCH_PERCENT, }; ///////////////////////////////////////////////////////////////////////////// // CChildFrame2 IMPLEMENT_DYNCREATE(CChildFrame2, CChildFrameBase) CChildFrame2::CChildFrame2() { m_pLeftFuncList = NULL; m_pRightFuncList = NULL; m_pDiffView = NULL; } CChildFrame2::~CChildFrame2() { } BEGIN_MESSAGE_MAP(CChildFrame2, CChildFrameBase) //{{AFX_MSG_MAP(CChildFrame2) ON_WM_CREATE() ON_COMMAND(ID_SYMBOLS_ADD, OnSymbolsAdd) ON_UPDATE_COMMAND_UI(ID_SYMBOLS_ADD, OnUpdateSymbolsAdd) //}}AFX_MSG_MAP ON_UPDATE_COMMAND_UI(ID_INDICATOR_MATCH_PERCENT, OnUpdateMatchPercent) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame2 message handlers BOOL CChildFrame2::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { if (!m_wndSplitter.CreateStatic(this, 1, 3)) return FALSE; if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CFuncListView), CSize(230, 0), pContext)) return FALSE; if (!m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CFuncListView), CSize(230, 0), pContext)) return FALSE; if (!m_wndSplitter.CreateView(0, 2, RUNTIME_CLASS(CFuncDiffEditView), CSize(300, 0), pContext)) return FALSE; m_pLeftFuncList = (CFuncListView *)m_wndSplitter.GetPane(0, 0); m_pRightFuncList = (CFuncListView *)m_wndSplitter.GetPane(0, 1); m_pDiffView = (CFuncDiffEditView *)m_wndSplitter.GetPane(0, 2); return TRUE; // return CChildFrameBase::OnCreateClient(lpcs, pContext); } int CChildFrame2::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CChildFrameBase::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } return 0; } void CChildFrame2::OnUpdateMatchPercent(CCmdUI* pCmdUI) { if (m_pDiffView == NULL) { pCmdUI->SetText(""); } else { pCmdUI->SetText(m_pDiffView->m_strMatchPercentage); } } void CChildFrame2::OnSymbolsAdd() { // Pass on to diff view to handle: if (m_pDiffView) m_pDiffView->OnSymbolsAdd(); } void CChildFrame2::OnUpdateSymbolsAdd(CCmdUI* pCmdUI) { // Pass on to diff view to handle: if (m_pDiffView) { m_pDiffView->OnUpdateSymbolsAdd(pCmdUI); } else { pCmdUI->Enable(FALSE); } } <file_sep>/programs/funcanal/FuncView/ChildFrm2.h // ChildFrm2.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm2.h,v $ // Revision 1.1 2003/09/13 05:45:33 dewhisna // Initial Revision // // #if !defined(AFX_CHILDFRM2_H__31E158BD_BFD8_4AB8_B28B_361FE203A9DD__INCLUDED_) #define AFX_CHILDFRM2_H__31E158BD_BFD8_4AB8_B28B_361FE203A9DD__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ChildFrmBase.h" class CFuncListView; class CFuncDiffEditView; ///////////////////////////////////////////////////////////////////////////// // CChildFrame2 frame class CChildFrame2 : public CChildFrameBase { DECLARE_DYNCREATE(CChildFrame2) protected: CChildFrame2(); // protected constructor used by dynamic creation // Attributes public: CFuncListView *m_pLeftFuncList; CFuncListView *m_pRightFuncList; CFuncDiffEditView *m_pDiffView; protected: CSplitterWnd m_wndSplitter; CStatusBar m_wndStatusBar; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame2) protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation protected: virtual ~CChildFrame2(); // Generated message map functions //{{AFX_MSG(CChildFrame2) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnSymbolsAdd(); afx_msg void OnUpdateSymbolsAdd(CCmdUI* pCmdUI); //}}AFX_MSG afx_msg void OnUpdateMatchPercent(CCmdUI* pCmdUI); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDFRM2_H__31E158BD_BFD8_4AB8_B28B_361FE203A9DD__INCLUDED_) <file_sep>/programs/m6811dis/gdc.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // // // GDC.CPP -- Implementation for Generic Disassembly Class // // GDC is a generic means for defining a disassembly process that // processor independent. The functions here provide the processor independent // part of the code. These classes should be overriden as appropriate // to handle specific processors. // #include "gdc.h" #include "dfc.h" #include "stringhelp.h" #include "memclass.h" #include "errmsgs.h" #include <ctime> #include <ctype.h> #include <iomanip> #include <sstream> #include <assert.h> #define VERSION 0x200 // GDC Version number 2.00 // ---------------------------------------------------------------------------- // COpcodeEntry // ---------------------------------------------------------------------------- COpcodeEntry::COpcodeEntry() { m_OpcodeBytes.clear(); m_Group = 0; m_Control = 0; m_UserData = 0; m_Mnemonic = "<undefined>"; } COpcodeEntry::COpcodeEntry(int nNumBytes, unsigned char *Bytes, unsigned int nGroup, unsigned int nControl, const std::string & szMnemonic, unsigned int nUserData) { m_OpcodeBytes.clear(); for (int i=0; i<nNumBytes; ++i) { m_OpcodeBytes.push_back(Bytes[i]); } m_Group = nGroup; m_Control = nControl; m_UserData = nUserData; m_Mnemonic = szMnemonic; } COpcodeEntry::COpcodeEntry(const COpcodeEntry& aEntry) { CopyFrom(aEntry); } void COpcodeEntry::CopyFrom(const COpcodeEntry& aEntry) { m_OpcodeBytes.clear(); for (unsigned int i=0; i<aEntry.m_OpcodeBytes.size(); ++i) { m_OpcodeBytes.push_back(aEntry.m_OpcodeBytes.at(i)); } m_Group = aEntry.m_Group; m_Control = aEntry.m_Control; m_UserData = aEntry.m_UserData; m_Mnemonic = aEntry.m_Mnemonic; } COpcodeEntry &COpcodeEntry::operator=(const COpcodeEntry& aEntry) { CopyFrom(aEntry); return *this; } // ---------------------------------------------------------------------------- // COpcodeArray // ---------------------------------------------------------------------------- COpcodeArray::COpcodeArray() : std::vector<COpcodeEntry>() { } COpcodeArray::~COpcodeArray() { } // ---------------------------------------------------------------------------- // COpcodeTable // ---------------------------------------------------------------------------- COpcodeTable::COpcodeTable() { } COpcodeTable::~COpcodeTable() { } void COpcodeTable::AddOpcode(const COpcodeEntry& nOpcode) { if (nOpcode.m_OpcodeBytes.size() == 0) return; // MUST have an initial byte in the opcode! iterator itrArray = find(nOpcode.m_OpcodeBytes.at(0)); if (itrArray == end()) { COpcodeArray anArray; anArray.push_back(nOpcode); operator [](nOpcode.m_OpcodeBytes.at(0)) = anArray; } else { itrArray->second.push_back(nOpcode); } } // ---------------------------------------------------------------------------- // CDisassembler // ---------------------------------------------------------------------------- CDisassembler::CDisassembler() : m_ROMMemMap(0, 0, 0), m_RAMMemMap(0, 0, 0), m_IOMemMap(0, 0, 0) { // Get system time: m_StartTime = time(NULL); // Set output defaults: m_bAddrFlag = false; m_bOpcodeFlag = false; m_bAsciiFlag = false; m_bSpitFlag = false; m_bTabsFlag = true; m_bAsciiBytesFlag = true; m_bDataOpBytesFlag = false; m_nMaxNonPrint = 8; m_nMaxPrint = 40; m_nTabWidth = 4; m_nBase = 16; // See ReadControlFile function before changing these 3 here! m_sDefaultDFC = "binary"; m_sInputFilename = ""; m_nLoadAddress = 0; m_sOutputFilename = ""; m_sFunctionsFilename = ""; m_sInputFileList.clear(); m_sControlFileList.clear(); // Setup commands to parse: ParseCmds["ENTRY"] = 1; ParseCmds["LOAD"] = 2; ParseCmds["INPUT"] = 3; ParseCmds["OUTPUT"] = 4; ParseCmds["LABEL"] = 5; ParseCmds["ADDRESSES"] = 6; ParseCmds["INDIRECT"] = 7; ParseCmds["OPCODES"] = 8; ParseCmds["OPBYTES"] = 8; ParseCmds["ASCII"] = 9; ParseCmds["SPIT"] = 10; ParseCmds["BASE"] = 11; ParseCmds["MAXNONPRINT"] = 12; ParseCmds["MAXPRINT"] = 13; ParseCmds["DFC"] = 14; ParseCmds["TABS"] = 15; ParseCmds["TABWIDTH"] = 16; ParseCmds["ASCIIBYTES"] = 17; ParseCmds["DATAOPBYTES"] = 18; ParseCmds["EXITFUNCTION"] = 19; ParseCmds["MEMMAP"] = 20; ParseCmdsOP1["OFF"] = false; ParseCmdsOP1["ON"] = true; ParseCmdsOP1["FALSE"] = false; ParseCmdsOP1["TRUE"] = true; ParseCmdsOP1["NO"] = false; ParseCmdsOP1["YES"] = true; ParseCmdsOP2["OFF"] = 0; ParseCmdsOP2["NONE"] = 0; ParseCmdsOP2["0"] = 0; ParseCmdsOP2["BIN"] = 2; ParseCmdsOP2["BINARY"] = 2; ParseCmdsOP2["2"] = 2; ParseCmdsOP2["OCT"] = 8; ParseCmdsOP2["OCTAL"] = 8; ParseCmdsOP2["8"] = 8; ParseCmdsOP2["DEC"] = 10; ParseCmdsOP2["DECIMAL"] = 10; ParseCmdsOP2["10"] = 10; ParseCmdsOP2["HEX"] = 16; ParseCmdsOP2["HEXADECIMAL"] = 16; ParseCmdsOP2["16"] = 16; ParseCmdsOP3["CODE"] = 0; ParseCmdsOP3["DATA"] = 1; ParseCmdsOP4["ROM"] = 0; ParseCmdsOP4["RAM"] = 1; ParseCmdsOP4["IO"] = 2; ParseCmdsOP5["DISASSEMBLY"] = 0; ParseCmdsOP5["DISASSEMBLE"] = 0; ParseCmdsOP5["DISASSEM"] = 0; ParseCmdsOP5["DISASM"] = 0; ParseCmdsOP5["DIS"] = 0; ParseCmdsOP5["DASM"] = 0; ParseCmdsOP5["FUNCTION"] = 1; ParseCmdsOP5["FUNCTIONS"] = 1; ParseCmdsOP5["FUNC"] = 1; ParseCmdsOP5["FUNCT"] = 1; ParseCmdsOP5["FUNCTS"] = 1; m_Memory = NULL; m_nFilesLoaded = 0; m_PC = 0; LAdrDplyCnt=0; } CDisassembler::~CDisassembler() { ParseCmds.clear(); ParseCmdsOP1.clear(); ParseCmdsOP2.clear(); ParseCmdsOP3.clear(); ParseCmdsOP4.clear(); ParseCmdsOP5.clear(); m_sInputFileList.clear(); m_sControlFileList.clear(); m_EntryTable.clear(); m_FunctionsTable.clear(); m_FuncExitAddresses.clear(); m_BranchTable.clear(); m_LabelTable.clear(); m_LabelRefTable.clear(); m_CodeIndirectTable.clear(); m_DataIndirectTable.clear(); if (m_Memory) { delete m_Memory; m_Memory = NULL; } } unsigned int CDisassembler::GetVersionNumber() { return (VERSION << 16); } bool CDisassembler::ReadControlFile(ifstreamControlFile& inFile, bool bLastFile, std::ostream *msgFile, std::ostream *errFile, int nStartLineCount) { bool RetVal; std::string aLine; TStringArray args; unsigned int Address; unsigned int ResAddress; TDWordArray SortedList; TMemRange *pMemRange; // Note: m_nFilesLoaded must be properly set/reset prior to calling this function // This is typically done in the constructor -- but overrides, etc, doing // preloading of files should properly set it as well. // bLastFile causes this function to report the overall disassembly summary from // control files -- such as "at least one input file" and "output file must // be specified" type error messages and sets any default action that should // be taken with entries, etc. The reason for the boolean flag is to // allow processing of several control files prior to reporting the summary. // Typically, the last control file processed should be called with a "true" // and all prior control files processed should be called with a "FALSE". RetVal = true; m_sControlFileList.push_back(inFile.getFilename()); if (msgFile) { (*msgFile) << "Reading and Parsing Control File: \"" << inFile.getFilename() << "\"...\n"; } m_nBase = 16; // Reset the default base before starting new file.. Therefore, each file has same default! m_sDefaultDFC = "binary"; // Reset the default DFC format so every control file starts with same default! m_sInputFilename = ""; // Reset the Input Filename so we won't try to reload file from previous control file if this control doesn't specify one m_nCtrlLine = nStartLineCount; // In case several lines were read by outside process, it should pass in correct starting number so we display correct error messages! while (inFile.good()) { std::getline(inFile, aLine); m_nCtrlLine++; m_ParseError = "*** Error: Unknown error"; std::size_t pos = aLine.find(';'); if (pos != std::string::npos) aLine = aLine.substr(0, pos); // Trim off comments! trim(aLine); if (aLine.size() == 0) continue; // If it is a blank or null line or only a comment, keep going args.clear(); std::string Temp = aLine; while (Temp.size()) { pos = Temp.find_first_of("\x009\x00a\x00b\x00c\x00d\x020"); if (pos != std::string::npos) { args.push_back(Temp.substr(0, pos)); Temp = Temp.substr(pos+1); } else { args.push_back(Temp); Temp.clear(); } ltrim(Temp); } if (args.size() == 0) continue; // If we don't have any args, get next line (really shouldn't ever have no args here) if (ParseControlLine(aLine, args, msgFile, errFile) == false) { // Go parse it -- either internal or overrides if (errFile) { (*errFile) << m_ParseError; (*errFile) << " in Control File \"" << inFile.getFilename() << "\" line " << m_nCtrlLine << "\n"; } } } // If a Input File was specified by the control file, then open it and read it here: if (!m_sInputFilename.empty()) { ReadSourceFile(m_sInputFilename, m_nLoadAddress, m_sDefaultDFC, msgFile, errFile); } if (bLastFile) { if (m_nFilesLoaded == 0) { if (errFile) (*errFile) << "*** Error: At least one input file must be specified in the control file(s) and successfully loaded\n"; RetVal = false; } if (m_sOutputFilename.empty()) { if (errFile) (*errFile) << "*** Error: Disassembly Output file must be specified in the control file(s)\n"; RetVal = false; } if ((m_bSpitFlag == false) && (m_EntryTable.size() == 0) && (m_CodeIndirectTable.size() == 0)) { if (errFile) (*errFile) << "*** Error: No entry addresses or indirect code vectors have been specified in the control file(s)\n"; RetVal = false; } if (RetVal) { if (msgFile) { (*msgFile) << "\n"; (*msgFile) << " " << m_sInputFileList.size() << " Source File" << ((m_sInputFileList.size() != 1) ? "s" : "") << ((m_sInputFileList.size() != 0) ? ":" : ""); if (m_sInputFileList.size() == 1) { (*msgFile) << " " << m_sInputFileList.at(0) << "\n"; } else { for (unsigned int i=0; i<m_sInputFileList.size(); ++i) { (*msgFile) << " " << m_sInputFileList.at(i) << "\n"; } } (*msgFile) << "\n"; if (!m_sOutputFilename.empty()) { (*msgFile) << " Disassembly Output File: " << m_sOutputFilename << "\n\n"; } if (!m_sFunctionsFilename.empty()) { (*msgFile) << " Functions Output File: " << m_sFunctionsFilename << "\n\n"; } (*msgFile) << " Memory Mappings:\n"; (*msgFile) << " ROM Memory Map:"; if (m_ROMMemMap.IsNullRange()) { (*msgFile) << " <Not Defined>\n"; } else { (*msgFile) << "\n"; pMemRange = &m_ROMMemMap; while (pMemRange) { (*msgFile) << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ")\n"; pMemRange = pMemRange->GetNext(); } } (*msgFile) << " RAM Memory Map:"; if (m_RAMMemMap.IsNullRange()) { (*msgFile) << " <Not Defined>\n"; } else { (*msgFile) << "\n"; pMemRange = &m_RAMMemMap; while (pMemRange) { (*msgFile) << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ")\n"; pMemRange = pMemRange->GetNext(); } } (*msgFile) << " IO Memory Map:"; if (m_IOMemMap.IsNullRange()) { (*msgFile) << " <Not Defined>\n"; } else { (*msgFile) << "\n"; pMemRange = &m_IOMemMap; while (pMemRange) { (*msgFile) << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ")\n"; pMemRange = pMemRange->GetNext(); } } (*msgFile) << "\n"; (*msgFile) << " " << m_EntryTable.size() << " Entry Point" << ((m_EntryTable.size() != 1) ? "s" : "") << ((m_EntryTable.size() != 0) ? ":" : "") << "\n"; } SortedList.clear(); for (TAddressMap::const_iterator itrEntry = m_EntryTable.begin(); itrEntry != m_EntryTable.end(); ++itrEntry) { TDWordArray::iterator itrSorted; for (itrSorted = SortedList.begin(); itrSorted != SortedList.end(); ++itrSorted) { if (itrEntry->first <= *itrSorted) { break; } } SortedList.insert(itrSorted, itrEntry->first); } for (unsigned int i=0; i<SortedList.size(); ++i) { if (msgFile) { (*msgFile) << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << SortedList.at(i) << std::nouppercase << std::setbase(0) << "\n"; } if (IsAddressLoaded(SortedList.at(i), 1) == false) { if (errFile) { (*errFile) << " *** Warning: Entry Point Address " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << SortedList.at(i) << std::nouppercase << std::setbase(0) << " is outside of loaded source file(s)...\n"; } } } if (msgFile) { (*msgFile) << "\n"; (*msgFile) << " " << m_FuncExitAddresses.size() << " Exit Function" << ((m_FuncExitAddresses.size() != 1) ? "s" : "") << " Defined" << ((m_FuncExitAddresses.size() != 0) ? ":" : "") << "\n"; } SortedList.clear(); for (TAddressMap::const_iterator itrEntry = m_FuncExitAddresses.begin(); itrEntry != m_FuncExitAddresses.end(); ++itrEntry) { TDWordArray::iterator itrSorted; for (itrSorted = SortedList.begin(); itrSorted != SortedList.end(); ++itrSorted) { if (itrEntry->first <= *itrSorted) { break; } } SortedList.insert(itrSorted, itrEntry->first); } for (unsigned int i=0; i<SortedList.size(); ++i) { if (msgFile) { (*msgFile) << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << SortedList.at(i) << std::nouppercase << std::setbase(0) << "\n"; } if (IsAddressLoaded(SortedList.at(i), 1) == false) { if (errFile) { (*errFile) << " *** Warning: Exit Function Address " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << SortedList.at(i) << std::nouppercase << std::setbase(0) << " is outside of loaded source file(s)...\n"; } } } if (msgFile) { (*msgFile) << "\n"; (*msgFile) << " " << m_LabelTable.size() << " Unique Label" << ((m_LabelTable.size() != 1) ? "s" : "") << " Defined" << ((m_LabelTable.size() != 0) ? ":" : "") << "\n"; SortedList.clear(); for (TLabelTableMap::const_iterator itrEntry = m_LabelTable.begin(); itrEntry != m_LabelTable.end(); ++itrEntry) { TDWordArray::iterator itrSorted; for (itrSorted = SortedList.begin(); itrSorted != SortedList.end(); ++itrSorted) { if (itrEntry->first <= *itrSorted) { break; } } SortedList.insert(itrSorted, itrEntry->first); } for (unsigned int i=0; i<SortedList.size(); ++i) { TLabelTableMap::const_iterator itrLabelTable = m_LabelTable.find(SortedList.at(i)); assert(itrLabelTable != m_LabelTable.end()); (*msgFile) << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << SortedList.at(i) << std::nouppercase << std::setbase(0) << "="; for (unsigned int j=0; j<itrLabelTable->second.size(); ++j) { if (j != 0) (*msgFile) << ","; (*msgFile) << (itrLabelTable->second.at(j)); } (*msgFile) << "\n"; } (*msgFile) << "\n"; if (m_bAddrFlag) (*msgFile) << "Writing program counter addresses to disassembly file.\n"; if (m_bOpcodeFlag) (*msgFile) << "Writing opcode byte values to disassembly file.\n"; if (m_bAsciiFlag) (*msgFile) << "Writing printable data as ASCII in disassembly file.\n"; if (m_bSpitFlag) (*msgFile) << "Performing a code-dump (spit) disassembly instead of code-seeking.\n"; if (m_bTabsFlag) { (*msgFile) << "Using tab characters in disassembly file. Tab width set at: " << m_nTabWidth << "\n"; } if (m_bAsciiBytesFlag) (*msgFile) << "Writing byte value comments for ASCII data in disassembly file.\n"; if ((m_bOpcodeFlag) && (m_bDataOpBytesFlag)) (*msgFile) << "Writing OpBytes for data in disassembly file\n"; (*msgFile) << "\n"; } // Ok, now we resolve the indirect tables... This process should create the indirect // label name from the resolved address if the corresponding string in the hash table is "". // This process requires the purely virtual ResolveIndirect function from overrides... if (msgFile) (*msgFile) << "Compiling Indirect Code (branch) Table as specified in Control File...\n"; SortedList.clear(); for (TAddressLabelMap::const_iterator itrEntry = m_CodeIndirectTable.begin(); itrEntry != m_CodeIndirectTable.end(); ++itrEntry) { TDWordArray::iterator itrSorted; for (itrSorted = SortedList.begin(); itrSorted != SortedList.end(); ++itrSorted) { if (itrEntry->first <= *itrSorted) { break; } } SortedList.insert(itrSorted, itrEntry->first); } if (msgFile) { (*msgFile) << " " << SortedList.size() << " Indirect Code Vector" << ((SortedList.size() != 1) ? "s" : "") << ((SortedList.size() != 0) ? ":" : "") << "\n"; } for (unsigned int i=0; i<SortedList.size(); ++i) { Address = SortedList.at(i); TAddressLabelMap::const_iterator itrTable = m_CodeIndirectTable.find(Address); assert(itrTable != m_CodeIndirectTable.end()); if (msgFile) { (*msgFile) << " [" << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << Address << std::nouppercase << std::setbase(0) << "] -> "; } if (ResolveIndirect(Address, ResAddress, 0) == false) { if (msgFile) (*msgFile) << "ERROR\n"; if (errFile) { (*errFile) << " *** Warning: Vector Address " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << Address << std::nouppercase << std::setbase(0) << " is outside of loaded source file(s)...\n"; (*errFile) << " Or the vector location conflicted with other analyzed areas.\n"; } } else { if (msgFile) { (*msgFile) << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << ResAddress << std::nouppercase << std::setbase(0); } AddLabel(ResAddress, false, 0, itrTable->second); // Add label for resolved name. If NULL, add it so later we can resolve Lxxxx from it. m_FunctionsTable[ResAddress] = FUNCF_INDIRECT; // Resolved code indirects are also considered start-of functions if (AddBranch(ResAddress, true, Address) == false) { if (errFile) { (*errFile) << " *** Warning: Indirect Address [" << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << Address << std::nouppercase << std::setbase(0) << "] -> " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << ResAddress << std::nouppercase << std::setbase(0) << " is outside of loaded source file(s)...\n"; } if ((msgFile) && (msgFile != errFile)) { (*msgFile) << "\n"; } } else { if (msgFile) { (*msgFile) << "\n"; } } } } if (msgFile) (*msgFile) << "\n"; // Now, repeat for Data indirects: if (msgFile) (*msgFile) << "Compiling Indirect Data Table as specified in Control File...\n"; SortedList.clear(); for (TAddressLabelMap::const_iterator itrEntry = m_DataIndirectTable.begin(); itrEntry != m_DataIndirectTable.end(); ++itrEntry) { TDWordArray::iterator itrSorted; for (itrSorted = SortedList.begin(); itrSorted != SortedList.end(); ++itrSorted) { if (itrEntry->first <= *itrSorted) { break; } } SortedList.insert(itrSorted, itrEntry->first); } if (msgFile) { (*msgFile) << " " << SortedList.size() << " Indirect Data Vector" << ((SortedList.size() != 1) ? "s" : "") << ((SortedList.size() != 0) ? ":" : "") << "\n"; } for (unsigned int i=0; i<SortedList.size(); ++i) { Address = SortedList.at(i); TAddressLabelMap::const_iterator itrTable = m_DataIndirectTable.find(Address); assert(itrTable != m_DataIndirectTable.end()); if (msgFile) { (*msgFile) << " [" << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << Address << std::nouppercase << std::setbase(0) << "] -> "; } if (ResolveIndirect(Address, ResAddress, 1) == false) { if (msgFile) (*msgFile) << "ERROR\n"; if (errFile) { (*errFile) << " *** Warning: Vector Address " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << Address << std::nouppercase << std::setbase(0) << " is outside of loaded source file(s)...\n"; (*errFile) << " Or the vector location conflicted with other analyzed areas.\n"; } } else { if (msgFile) { (*msgFile) << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << ResAddress << std::nouppercase << std::setbase(0) << "\n"; } AddLabel(ResAddress, true, Address, itrTable->second); // Add label for resolved name. If NULL, add it so later we can resolve Lxxxx from it. } } if (msgFile) (*msgFile) << "\n"; } } return RetVal; } bool CDisassembler::ParseControlLine(const std::string & /* szLine */, TStringArray& argv, std::ostream *msgFile, std::ostream *errFile) { bool RetVal; std::string Cmd; unsigned int CmdIndex; unsigned int Address; unsigned int Size; std::string TempStr; std::string DfcLibrary; std::string FileName; unsigned int TempWord; unsigned int TempDWord; int ArgError; bool TempFlag; bool TempFlag2; assert(argv.size() != 0); if (argv.size() == 0) return false; RetVal = true; ArgError = 0; Cmd = argv[0]; makeUpper(Cmd); CmdIndex = -1; TParseCmdMap::const_iterator itrParse = ParseCmds.find(Cmd); if (itrParse != ParseCmds.end()) CmdIndex = itrParse->second; switch (CmdIndex) { case 1: // ENTRY <addr> [<name>] if (argv.size() < 2) { ArgError = 1; break; } if (argv.size() > 3) { ArgError = 2; break; } if (argv.size() == 3) { if (!ValidateLabelName(argv[2])) { ArgError = 3; break; } } Address = strtoul(argv[1].c_str(), NULL, m_nBase); if (m_EntryTable.find(Address) != m_EntryTable.end()) { RetVal = false; m_ParseError = "*** Warning: Duplicate entry address"; } m_EntryTable[Address] = true; // Add an entry to the entry table m_FunctionsTable[Address] = FUNCF_ENTRY; // Entries are also considered start-of functions if (argv.size() == 3) { if (AddLabel(Address, false, 0, argv[2]) == false) { RetVal = false; m_ParseError = "*** Warning: Duplicate label"; } } break; case 2: // LOAD <addr> | <addr> <filename> [<library>] { if (argv.size() == 2) { m_nLoadAddress = strtoul(argv[1].c_str(), NULL, m_nBase); break; } if (argv.size() < 3) { ArgError = 1; break; } if (argv.size() > 4) { ArgError = 2; break; } Address = strtoul(argv[1].c_str(), NULL, m_nBase); if (argv.size() == 4) { DfcLibrary = argv[3]; } else { DfcLibrary = m_sDefaultDFC; } FileName = argv[2]; ReadSourceFile(FileName, Address, DfcLibrary, msgFile, errFile); // We don't set RetVal to FALSE here if there is an error on ReadSource, // because errors have already been printed and are not in ParseError... break; } case 3: // INPUT <filename> if (argv.size() != 2) { ArgError = (argv.size() < 2) ? 1 : 2; break; } if (!m_sInputFilename.empty()) { RetVal = false; m_ParseError = "*** Warning: Input filename already defined"; } m_sInputFilename = argv[1]; break; case 4: // OUTPUT [DISASSEMBLY | FUNCTIONS] <filename> if ((argv.size() != 2) && (argv.size() != 3)) { ArgError = (argv.size() < 2) ? 1 : 2; break; } TempFlag = false; // TempFlag = FALSE if type not specified on line, true if it is if (argv.size() == 2) { // If type isn't specified, assume DISASSEMBLY TempWord = 0; } else { TempFlag = true; TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP5.find(TempStr); if (itrParse == ParseCmdsOP5.end()) { ArgError = 3; break; } else { TempWord = itrParse->second; } } switch (TempWord) { case 0: // DISASSEMBLY if (!m_sOutputFilename.empty()) { RetVal = false; m_ParseError = "*** Warning: Disassembly Output filename already defined"; } m_sOutputFilename = argv[((TempFlag) ? 2 : 1)]; break; case 1: // FUNCTIONS if (!m_sFunctionsFilename.empty()) { RetVal = false; m_ParseError = "*** Warning: Functions Output filename already defined"; } m_sFunctionsFilename = argv[((TempFlag) ? 2 : 1)]; break; } break; case 5: // LABEL <addr> <name> if (argv.size() != 3) { ArgError = (argv.size() < 3) ? 1 : 2; break; } if (!ValidateLabelName(argv[2])) { ArgError = 3; break; } Address = strtoul(argv[1].c_str(), NULL, m_nBase); if (AddLabel(Address, false, 0, argv[2]) == false) { RetVal = false; m_ParseError = "*** Warning: Duplicate label"; } break; case 6: // ADDRESSES [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bAddrFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bAddrFlag = itrParse->second; } else { ArgError = 3; } break; case 7: // INDIRECT [CODE | DATA] <addr> [<name>] if ((argv.size() != 2) && (argv.size() != 3) && (argv.size() != 4)) { ArgError = (argv.size() < 2) ? 1 : 2; break; } TempFlag = false; // TempFlag = FALSE if CODE/DATA not specified on line, true if it is TempFlag2 = false; // TempFlag2 = FALSE if <name> not specified on line, true if it is if (argv.size() == 2) { // If Code or Data isn't specified, assume code TempWord = 0; } else { TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP3.find(TempStr); if (itrParse == ParseCmdsOP3.end()) { if (argv.size() == 4) { // If all args was specified, error out if not valid ArgError = 3; break; } else { // If here, we assume we have <addr> and <name> since we are one arg short TempWord = 0; // Assume Code since it isn't specified TempFlag2 = true; // And we do have a <name> } } else { TempWord = itrParse->second; TempFlag = true; if (argv.size() == 4) { // If all args was specified, we have valid everything TempFlag2 = true; } } } // From the following point to the end of this case, TempStr = the Indirect <name> // If not specified, we set the name to "" so the Resolution function will // create it from the resolved address... if (TempFlag2) { TempStr = argv[2 + ((TempFlag) ? 1 : 0)]; if (!ValidateLabelName(TempStr)) { ArgError = 3; break; } } else { TempStr = ""; } Address = strtoul(argv[1 + ((TempFlag) ? 1 : 0)].c_str(), NULL, m_nBase); switch (TempWord) { case 0: if ((m_CodeIndirectTable.find(Address) != m_CodeIndirectTable.end()) || (m_DataIndirectTable.find(Address) != m_DataIndirectTable.end())) { RetVal = false; m_ParseError = "*** Warning: Duplicate indirect"; } m_CodeIndirectTable[Address] = TempStr; // Add a label to the code indirect table break; case 1: if ((m_DataIndirectTable.find(Address) != m_DataIndirectTable.end()) || (m_CodeIndirectTable.find(Address) != m_CodeIndirectTable.end())) { RetVal = false; m_ParseError = "*** Warning: Duplicate indirect"; } m_DataIndirectTable[Address] = TempStr; // Add a label to the data indirect table break; } break; case 8: // OPCODES [ON | OFF | TRUE | FALSE | YES | NO] // OPBYTES [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bOpcodeFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bOpcodeFlag = itrParse->second; } else { ArgError = 3; } break; case 9: // ASCII [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bAsciiFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bAsciiFlag = itrParse->second; } else { ArgError = 3; } break; case 10: // SPIT [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bSpitFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bSpitFlag = itrParse->second; } else { ArgError = 3; } break; case 11: // BASE [OFF | BIN | OCT | DEC | HEX] if (argv.size() < 2) { m_nBase = 0; // Default is OFF break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP2.find(TempStr); if (itrParse != ParseCmdsOP2.end()) { m_nBase = itrParse->second; } else { ArgError = 3; } break; case 12: // MAXNONPRINT <value> if (argv.size() != 2) { ArgError = (argv.size() < 2) ? 1 : 2; break; } m_nMaxNonPrint = strtoul(argv[1].c_str(), NULL, m_nBase); break; case 13: // MAXPRINT <value> if (argv.size() != 2) { ArgError = (argv.size() < 2) ? 1 : 2; break; } m_nMaxPrint = strtoul(argv[1].c_str(), NULL, m_nBase); break; case 14: // DFC <library> if (argv.size() != 2) { ArgError = (argv.size() < 2) ? 1 : 2; break; } m_sDefaultDFC = argv[1]; break; case 15: // TABS [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bTabsFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bTabsFlag = itrParse->second; } else{ ArgError = 3; } break; case 16: // TABWIDTH <value> if (argv.size() != 2) { ArgError = (argv.size() < 2) ? 1 : 2; break; } m_nTabWidth = strtoul(argv[1].c_str(), NULL, m_nBase); break; case 17: // ASCIIBYTES [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bAsciiBytesFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bAsciiBytesFlag = itrParse->second; } else { ArgError = 3; } break; case 18: // DATAOPBYTES [ON | OFF | TRUE | FALSE | YES | NO] if (argv.size() < 2) { m_bDataOpBytesFlag = true; // Default is ON break; } if (argv.size() > 2) { ArgError = 2; break; } TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP1.find(TempStr); if (itrParse != ParseCmdsOP1.end()) { m_bDataOpBytesFlag = itrParse->second; } else { ArgError = 3; } break; case 19: // EXITFUNCTION <addr> [<name>] if (argv.size() < 2) { ArgError = 1; break; } if (argv.size() > 3) { ArgError = 2; break; } if (argv.size() == 3) { if (!ValidateLabelName(argv[2])) { ArgError = 3; break; } } Address = strtoul(argv[1].c_str(), NULL, m_nBase); if (m_FuncExitAddresses.find(Address) != m_FuncExitAddresses.end()) { RetVal = false; m_ParseError = "*** Warning: Duplicate function exit address"; } m_FunctionsTable[Address] = FUNCF_ENTRY; // Exit Function Entry points are also considered start-of functions m_FuncExitAddresses[Address] = true; // Add function exit entry if (argv.size() == 3) { if (AddLabel(Address, false, 0, argv[2]) == false) { RetVal = false; m_ParseError = "*** Warning: Duplicate label"; } } break; case 20: // MEMMAP [ROM | RAM | IO] <addr> <size> if ((argv.size() != 3) && (argv.size() != 4)) { ArgError = (argv.size() < 3) ? 1 : 2; break; } TempFlag = false; // TempFlag = FALSE if ROM/RAM/IO not specified on line, true if it is if (argv.size() == 3) { // If ROM/RAM/IO not specified on line, assume ROM TempWord = 0; } else { TempStr = argv[1]; makeUpper(TempStr); itrParse = ParseCmdsOP4.find(TempStr); if (itrParse != ParseCmdsOP4.end()) { TempWord = itrParse->second; TempFlag = true; // If specified and valid, set flag } else { ArgError = 3; // Error out if type not valid but specified break; } } // Get address and size specified: Address = strtoul(argv[1 + ((TempFlag) ? 1 : 0)].c_str(), NULL, m_nBase); Size = strtoul(argv[2 + ((TempFlag) ? 1 : 0)].c_str(), NULL, m_nBase); switch (TempWord) { case 0: // ROM m_ROMMemMap.AddRange(Address, Size, 0); m_ROMMemMap.Compact(); m_ROMMemMap.RemoveOverlaps(); m_ROMMemMap.Sort(); for (TempDWord = Address; ((TempDWord < (Address + Size)) && (RetVal)); TempDWord++) { if (m_RAMMemMap.AddressInRange(TempDWord)) { RetVal = false; m_ParseError = "*** Warning: Specified ROM Mapping conflicts with RAM Mapping"; } else { if (m_IOMemMap.AddressInRange(TempDWord)) { RetVal = false; m_ParseError = "*** Warning: Specified ROM Mapping conflicts with IO Mapping"; } } } break; case 1: // RAM m_RAMMemMap.AddRange(Address, Size, 0); m_RAMMemMap.Compact(); m_RAMMemMap.RemoveOverlaps(); m_RAMMemMap.Sort(); for (TempDWord = Address; ((TempDWord < (Address + Size)) && (RetVal)); TempDWord++) { if (m_ROMMemMap.AddressInRange(TempDWord)) { RetVal = false; m_ParseError = "*** Warning: Specified RAM Mapping conflicts with ROM Mapping"; } else { if (m_IOMemMap.AddressInRange(TempDWord)) { RetVal = false; m_ParseError = "*** Warning: Specified RAM Mapping conflicts with IO Mapping"; } } } break; case 2: // IO m_IOMemMap.AddRange(Address, Size, 0); m_IOMemMap.Compact(); m_IOMemMap.RemoveOverlaps(); m_IOMemMap.Sort(); for (TempDWord = Address; ((TempDWord < (Address + Size)) && (RetVal)); TempDWord++) { if (m_ROMMemMap.AddressInRange(TempDWord)) { RetVal = false; m_ParseError = "*** Warning: Specified IO Mapping conflicts with ROM Mapping"; } else { if (m_RAMMemMap.AddressInRange(TempDWord)) { RetVal = false; m_ParseError = "*** Warning: Specified IO Mapping conflicts with RAM Mapping"; } } } break; } break; default: m_ParseError = "*** Error: Unknown command"; return false; } if (ArgError) { RetVal = false; switch (ArgError) { case 1: m_ParseError = "*** Error: Not enough arguments for '" + argv[0] + "' command"; break; case 2: m_ParseError = "*** Error: Too many arguments for '" + argv[0] + "' command"; break; case 3: m_ParseError = "*** Error: Illegal argument for '" + argv[0] + "' command"; break; } } return RetVal; } bool CDisassembler::ReadSourceFile(const std::string & szFilename, unsigned int nLoadAddress, const std::string & szDFCLibrary, std::ostream *msgFile, std::ostream *errFile) { if (szDFCLibrary.empty()) return false; if (szFilename.empty()) return false; std::fstream theFile; const CDFCObject *theDFC = CDFCArray::instance()->locateDFC(szDFCLibrary); bool RetVal = true; if (msgFile) { (*msgFile) << "Loading \"" << szFilename << "\" at offset " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << nLoadAddress << std::nouppercase << std::setbase(0) << " using " << szDFCLibrary << " library...\n"; } if (theDFC == NULL) { if (errFile) { (*errFile) << "*** Error: Can't open DFC Library \"" << szDFCLibrary << "\" to read \"" << szFilename << "\"\n"; } RetVal = false; } else { theFile.open(szFilename.c_str(), std::ios_base::in | std::ios_base::binary); if (theFile.is_open() == 0) { if (errFile) { (*errFile) << "*** Error: Can't open file \"" << szFilename << "\" for reading\n"; } RetVal = false; } else { int Status = 1; m_nFilesLoaded++; m_sInputFileList.push_back(szFilename); try { Status = theDFC->ReadDataFile(&theFile, nLoadAddress, m_Memory, DMEM_LOADED); } catch (const EXCEPTION_ERROR* aErr) { RetVal = false; m_nFilesLoaded--; m_sInputFileList.erase(m_sInputFileList.end()-1); switch (aErr->cause) { case EXCEPTION_ERROR::ERR_CHECKSUM: if (errFile) { (*errFile) << "*** Error: Checksum error reading file \"" << szFilename << "\"\n"; } break; case EXCEPTION_ERROR::ERR_UNEXPECTED_EOF: if (errFile) { (*errFile) << "*** Error: Unexpected end-of-file reading \"" << szFilename << "\"\n"; } break; case EXCEPTION_ERROR::ERR_OVERFLOW: if (errFile) { (*errFile) << "*** Error: Reading file \"" << szFilename << "\" extends past the defined memory limits of this processor\n"; } break; case EXCEPTION_ERROR::ERR_READFAILED: if (errFile) { (*errFile) << "*** Error: Reading file \"" << szFilename << "\"\n"; } break; default: if (errFile) { (*errFile) << "*** Error: Unknown DFC Error encountered while reading file \"" << szFilename << "\"\n"; } } } if (Status == 0) { RetVal = false; if (errFile) { (*errFile) << "*** Warning: Reading file \"" << szFilename << "\", overlaps previously loaded files\n"; } } theFile.close(); } } // Note, the DFC will unload when destructor is called upon exiting this routine return RetVal; } bool CDisassembler::ValidateLabelName(const std::string & aName) { if (aName.empty()) return false; // Must have a length if ((!isalpha(aName.at(0))) && (aName.at(0) != '_')) return false; // Must start with alpha or '_' for (unsigned int i=1; i<aName.size(); ++i) { if ((!isalnum(aName.at(i))) && (aName.at(i) != '_')) return false; // Each character must be alphanumeric or '_' } return true; } // bool CDisassembler::ResolveIndirect(unsigned int nAddress, unsigned int& nResAddress, int nType) = 0; // Purely Virtual! // NOTE: This function should set the m_Memory type code for the affected bytes to // either DMEM_CODEINDIRECT or DMEM_DATAINDIRECT!!!! It should set // nResAddress to the resolved address and return T/F -- True if indirect // vector word lies completely inside the loaded space. False if indirect // vector word (or part of it) is outside. This function is NOT to check // the destination for loaded status -- that is checked by the routine // calling this function... nType will be 0 for Code and 1 for Data... // Typically nType can be added to DMEM_CODEINDIRECT to determine the correct // code to store. This is because the DMEM enumeration was created with // this expansion and uniformity in mind. // It is also good for this function to check that all bytes of the indirect // vector itself have previously not been "looked at" or tagged. Routines // calling this function for previously tagged addresses should reset the // vector bytes to DMEM_LOADED. bool CDisassembler::IsAddressLoaded(unsigned int nAddress, int nSize) { bool RetVal = true; for (int i=0; ((i<nSize) && (RetVal)); ++i) { RetVal = RetVal && (m_Memory->GetDescriptor(nAddress + i) != DMEM_NOTLOADED); } return RetVal; } bool CDisassembler::AddLabel(unsigned int nAddress, bool bAddRef, unsigned int nRefAddress, const std::string & szLabel) { TLabelTableMap::iterator itrLabelTable = m_LabelTable.find(nAddress); TAddressTableMap::iterator itrRefTable = m_LabelRefTable.find(nAddress); if (itrLabelTable != m_LabelTable.end()) { if (itrRefTable == m_LabelRefTable.end()) { assert(false); // We should have an array for both label strings and addresses -- check adding! return false; } if (bAddRef) { // Search and add reference, even if we find the string bool bFound = false; for (unsigned int i=0; i<itrRefTable->second.size(); ++i) { if (itrRefTable->second.at(i) == nRefAddress) { bFound = true; break; } } if (!bFound) itrRefTable->second.push_back(nRefAddress); } for (unsigned int i=0; i<itrLabelTable->second.size(); ++i) { if (compareNoCase(szLabel, itrLabelTable->second.at(i)) == 0) return false; } } else { assert(itrRefTable == m_LabelRefTable.end()); // If we don't have an entry in the label tabel, we shouldn't have any reference label table m_LabelTable[nAddress] = TStringArray(); itrLabelTable = m_LabelTable.find(nAddress); m_LabelRefTable[nAddress] = TDWordArray(); itrRefTable = m_LabelRefTable.find(nAddress); if (bAddRef) { // If we are just now adding the label, we can add the ref without searching because it doesn't exist either itrRefTable->second.push_back(nRefAddress); } } if (itrLabelTable->second.size()) { if (!szLabel.empty()) { for (TStringArray::iterator itrLabels = itrLabelTable->second.begin(); itrLabels != itrLabelTable->second.end(); ++itrLabels) { if (itrLabels->empty()) { itrLabelTable->second.erase(itrLabels); break; // If adding a non-Lxxxx entry, remove previous Lxxxx entry if it exists! } } } else { return false; // Don't set Lxxxx entry if we already have at least 1 label! } } itrLabelTable->second.push_back(szLabel); return true; } bool CDisassembler::AddBranch(unsigned int nAddress, bool bAddRef, unsigned int nRefAddress) { TAddressTableMap::iterator itrRefList = m_BranchTable.find(nAddress); if (itrRefList == m_BranchTable.end()) { m_BranchTable[nAddress] = TDWordArray(); itrRefList = m_BranchTable.find(nAddress); } if (bAddRef) { // Search and add reference bool bFound = false; for (unsigned int i = 0; i < itrRefList->second.size(); ++i) { if (itrRefList->second.at(i) == nRefAddress) { bFound = true; break; } } if (!bFound) itrRefList->second.push_back(nRefAddress); } return IsAddressLoaded(nAddress, 1); } void CDisassembler::GenDataLabel(unsigned int nAddress, unsigned int nRefAddress, const std::string & /* szLabel */, std::ostream *msgFile, std::ostream * /* errFile */) { if (AddLabel(nAddress, true, nRefAddress)) OutputGenLabel(nAddress, msgFile); } void CDisassembler::GenAddrLabel(unsigned int nAddress, unsigned int nRefAddress, const std::string & /* szLabel */, std::ostream *msgFile, std::ostream *errFile) { if (AddLabel(nAddress, false, nRefAddress)) OutputGenLabel(nAddress, msgFile); if (AddBranch(nAddress, true, nRefAddress) == false) { if (errFile) { if ((errFile == msgFile) || (LAdrDplyCnt != 0)) { (*errFile) << "\n"; LAdrDplyCnt = 0; } (*errFile) << " *** Warning: Branch Ref: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << nAddress << std::nouppercase << std::setbase(0) << " is outside of Loaded Source File.\n"; } } } void CDisassembler::OutputGenLabel(unsigned int nAddress, std::ostream *msgFile) { std::string Temp; if (msgFile == NULL) return; Temp = GenLabel(nAddress); Temp += ' '; if (Temp.size() < 7) { Temp += " "; Temp = Temp.substr(0, 7); } if (LAdrDplyCnt >= 9) { std::size_t nPos = Temp.find(' '); if (nPos != std::string::npos) Temp = Temp.substr(0, nPos); Temp += '\n'; LAdrDplyCnt=0; } else { LAdrDplyCnt++; } (*msgFile) << Temp; } std::string CDisassembler::GenLabel(unsigned int nAddress) { std::ostringstream sstrTemp; sstrTemp << "L" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << nAddress; return sstrTemp.str(); } bool CDisassembler::ScanEntries(std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; unsigned int nCount = m_EntryTable.size(); if (m_bSpitFlag) { m_PC = 0; // In spit mode, we start at first address and just spit return FindCode(msgFile, errFile); } TAddressMap::const_iterator itrEntry = m_EntryTable.begin(); while (RetVal && (itrEntry != m_EntryTable.end())) { m_PC = itrEntry->first; ++itrEntry; RetVal = RetVal && FindCode(msgFile, errFile); if (nCount != m_EntryTable.size()) { nCount = m_EntryTable.size(); itrEntry = m_EntryTable.begin(); // If one gets added during the find process, our iterator gets invalidated and we must start over... } } return RetVal; } bool CDisassembler::ScanBranches(std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; unsigned int nCount = m_BranchTable.size(); if (m_bSpitFlag) return true; // Don't do anything in spit mode cause we did it in ScanEntries! TAddressTableMap::const_iterator itrEntry = m_BranchTable.begin(); while (RetVal && (itrEntry != m_BranchTable.end())) { m_PC = itrEntry->first; ++itrEntry; RetVal = RetVal && FindCode(msgFile, errFile); if (nCount != m_BranchTable.size()) { nCount = m_BranchTable.size(); itrEntry = m_BranchTable.begin(); // If one gets added during the find process, our iterator gets invalidated and we must start over... } } return RetVal; } bool CDisassembler::ScanData(const std::string & szExcludeChars, std::ostream * /* msgFile */, std::ostream * /* errFile */) { unsigned char c; // Note that we use an argument passed in so that the caller has a chance to change the // list passed in by the GetExcludedPrintChars function! for (m_PC=0; m_PC<m_Memory->GetMemSize(); m_PC++) { if (m_Memory->GetDescriptor(m_PC) != DMEM_LOADED) continue; // Only modify memory locations that have been loaded but not processed! c = m_Memory->GetByte(m_PC); if (isprint(c) && (szExcludeChars.find(c) == std::string::npos)) { m_Memory->SetDescriptor(m_PC, DMEM_PRINTDATA); } else { m_Memory->SetDescriptor(m_PC, DMEM_DATA); } } return true; } bool CDisassembler::FindCode(std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; bool TFlag = false; while (TFlag == false) { if (m_PC >= m_Memory->GetMemSize()) { TFlag = true; continue; } if ((m_Memory->GetDescriptor(m_PC) != DMEM_LOADED) && (m_bSpitFlag == false)) { TFlag = true; continue; // Exit when we hit an area we've already looked at } if (ReadNextObj(true, msgFile, errFile)) { // Read next opcode and tag memory since we are finding code here if (((m_CurrentOpcode.m_Control & OCTL_STOP) != 0) && (m_bSpitFlag == false)) TFlag = true; } // If the ReadNextObj returns false, that means we hit an illegal opcode byte. The ReadNextObj will have incremented the m_PC past that byte, so we'll keep processing } return RetVal; } bool CDisassembler::ReadNextObj(bool bTagMemory, std::ostream *msgFile, std::ostream *errFile) { // Here, we'll read the next object code from memory and flag the memory as being // code, unless an illegal opcode is encountered whereby it will be flagged as // illegal code. m_OpMemory is cleared and loaded with the memory bytes for the // opcode that was processed. m_CurrentOpcode will be also be set to the opcode // that corresponds to the one found. m_PC will also be incremented by the number // of bytes in the complete opcode and in the case of an illegal opcode, it will // increment only by 1 byte so we can then test the following byte to see if it // is legal to allow us to get back on track. This function will return True // if the opcode was correct and properly formed and fully existed in memory. It // will return false if the opcode was illegal or if the opcode crossed over the // bounds of loaded source memory. // If bTagMemory is false, then memory descriptors aren't changed! This is useful // if on-the-fly disassembly is desired without modifying the descriptors, such // as in pass 2 of the disassembly process. unsigned char FirstByte; unsigned int SavedPC; bool Flag; m_sFunctionalOpcode = ""; FirstByte = m_Memory->GetByte(m_PC++); m_OpMemory.clear(); m_OpMemory.push_back(FirstByte); if (IsAddressLoaded(m_PC-1, 1) == false) return false; COpcodeTable::const_iterator itrOpcode = m_Opcodes.find(FirstByte); Flag = false; if (itrOpcode != m_Opcodes.end()) { for (unsigned int ndx = 0; ((ndx < itrOpcode->second.size()) && (Flag == false)); ++ndx) { m_CurrentOpcode = itrOpcode->second.at(ndx); Flag = true; for (unsigned int i=1; ((i<m_CurrentOpcode.m_OpcodeBytes.size()) && (Flag)); ++i) { if (m_CurrentOpcode.m_OpcodeBytes.at(i) != m_Memory->GetByte(m_PC+i-1)) Flag = false; } } } if ((Flag == false) || (IsAddressLoaded(m_PC, m_CurrentOpcode.m_OpcodeBytes.size()-1) == false)) { if (bTagMemory) m_Memory->SetDescriptor(m_PC-1, DMEM_ILLEGALCODE); return false; } // If we get here, then we've found a valid matching opcode. m_CurrentOpcode has been set to the opcode value // so we must now finish copying to m_OpMemory, tag the bytes in memory, increment m_PC, and call CompleteObjRead // to handle the processor dependent stuff. If CompleteObjRead returns FALSE, then we'll have to undo everything // and return flagging an invalid opcode. SavedPC = m_PC; // Remember m_PC in case we have to undo things (remember, m_PC has already been incremented by 1) for (unsigned int i=1; i<m_CurrentOpcode.m_OpcodeBytes.size(); ++i) { // Finish copying opcode, but don't tag memory until dependent code is called successfully m_OpMemory.push_back(m_Memory->GetByte(m_PC++)); } if ((CompleteObjRead(true, msgFile, errFile) == false) || (IsAddressLoaded(SavedPC-1, m_OpMemory.size()) == false)) { // Undo things here: m_OpMemory.clear(); m_OpMemory.push_back(FirstByte); // Keep only the first byte in OpMemory for illegal opcode id m_PC = SavedPC; if (bTagMemory) m_Memory->SetDescriptor(m_PC-1, DMEM_ILLEGALCODE); return false; } // assert(CompleteObjRead(true, msgFile, errFile)); SavedPC--; for (unsigned int i=0; i<m_OpMemory.size(); ++i) { // CompleteObjRead will add bytes to OpMemory, so we simply have to flag memory for that many bytes. m_PC is already incremented by CompleteObjRead if (bTagMemory) m_Memory->SetDescriptor(SavedPC, DMEM_CODE); SavedPC++; } assert(SavedPC == m_PC); // If these aren't equal, something is wrong in the CompleteObjRead! m_PC should be incremented for every byte added to m_OpMemory by the complete routine! return true; } bool CDisassembler::Disassemble(std::ostream *msgFile, std::ostream *errFile, std::ostream *outFile) { bool RetVal = true; std::ostream *theOutput; std::fstream aOutput; std::string Temp; if (outFile) { theOutput = outFile; } else { aOutput.open(m_sOutputFilename.c_str(), std::ios_base::out | std::ios_base::trunc); if (!aOutput.is_open()) { if (errFile) { (*errFile) << "\n*** Error: Opening file \"" << m_sOutputFilename << "\" for writing...\n"; } return false; } theOutput = &aOutput; } while (1) { // Setup dummy endless loop so we can use the break if (msgFile) (*msgFile) << "\nPass 1 - Finding Code, Data, and Labels...\n"; RetVal = Pass1(*theOutput, msgFile, errFile); if (!RetVal) break; if (msgFile) { (*msgFile) << ((LAdrDplyCnt != 0) ? '\n' : ' ') << "\nPass 2 - Disassembling to Output File...\n"; } RetVal = Pass2(*theOutput, msgFile, errFile); if (!RetVal) break; if (!m_sFunctionsFilename.empty()) { if (*msgFile) { (*msgFile) << ((LAdrDplyCnt != 0) ? '\n' : ' ') << "\nPass 3 - Creating Functions Output File...\n"; } RetVal = Pass3(*theOutput, msgFile, errFile); if (!RetVal) break; } if (msgFile) { (*msgFile) << "\nDisassembly Complete\n"; } // Add additional Passes here and end this loop with a break break; } if (RetVal == false) { (*theOutput) << "\n*** Internal error encountered while disassembling.\n"; if (errFile) (*errFile) << "\n*** Internal error encountered while disassembling.\n"; } if (aOutput.is_open()) aOutput.close(); // Close the output file if we opened it return RetVal; } bool CDisassembler::Pass1(std::ostream& /* outFile */, std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; // Note that Short-Circuiting will keep following process stages from being called in the even of an error! RetVal = RetVal && ScanEntries(msgFile, errFile); RetVal = RetVal && ScanBranches(msgFile, errFile); RetVal = RetVal && ScanData(GetExcludedPrintChars(), msgFile, errFile); return RetVal; } bool CDisassembler::Pass2(std::ostream& outFile, std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; // Note that Short-Circuiting will keep following process stages from being called in the even of an error! RetVal = RetVal && WriteHeader(outFile, msgFile, errFile); RetVal = RetVal && WriteEquates(outFile, msgFile, errFile); RetVal = RetVal && WriteDisassembly(outFile, msgFile, errFile); return RetVal; } bool CDisassembler::Pass3(std::ostream& /* outFile */, std::ostream *msgFile, std::ostream *errFile) { bool RetVal = true; std::fstream aFunctionsFile; bool bInFunc; bool bLastFlag; bool bBranchOutFlag; unsigned int nFuncAddr = 0; unsigned int nSavedPC; TMemRange *pMemRange; bool bTempFlag; bool bTempFlag2; aFunctionsFile.open(m_sFunctionsFilename.c_str(), std::ios_base::out | std::ios_base::trunc); if (!aFunctionsFile.is_open()) { if (errFile) { (*errFile) << "\n*** Error: Opening file \"" << m_sFunctionsFilename << "\" for writing...\n"; } return false; } aFunctionsFile << ";\n"; aFunctionsFile << "; " << GetGDCLongName() << " Generated Function Information File\n"; aFunctionsFile << ";\n"; aFunctionsFile << "; Control File" << ((m_sControlFileList.size() > 1) ? "s:" : ": ") << " "; for (unsigned int i=0; i<m_sControlFileList.size(); ++i) { if (i==0) { aFunctionsFile << m_sControlFileList.at(i) << "\n"; } else { aFunctionsFile << "; " << m_sControlFileList.at(i) << "\n"; } } aFunctionsFile << "; Input File" << ((m_sInputFileList.size() > 1) ? "s:" : ": ") << " "; for (unsigned int i=0; i<m_sInputFileList.size(); ++i) { if (i==0) { aFunctionsFile << m_sInputFileList.at(i) << "\n"; } else { aFunctionsFile << "; " << m_sInputFileList.at(i) << "\n"; } } aFunctionsFile << "; Output File: " << m_sOutputFilename << "\n"; aFunctionsFile << "; Functions File: " << m_sFunctionsFilename << "\n"; aFunctionsFile << ";\n"; aFunctionsFile << "; Memory Mappings:"; aFunctionsFile << " ROM Memory Map: "; if (m_ROMMemMap.IsNullRange()) { aFunctionsFile << "<Not Defined>\n"; } else { aFunctionsFile << "\n"; pMemRange = &m_ROMMemMap; while (pMemRange) { aFunctionsFile << "; " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ")\n"; pMemRange = pMemRange->GetNext(); } } aFunctionsFile << "; RAM Memory Map: "; if (m_RAMMemMap.IsNullRange()) { aFunctionsFile << "<Not Defined>\n"; } else { aFunctionsFile << "\n"; pMemRange = &m_RAMMemMap; while (pMemRange) { aFunctionsFile << "; " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ")\n"; pMemRange = pMemRange->GetNext(); } } aFunctionsFile << "; IO Memory Map: "; if (m_IOMemMap.IsNullRange()) { aFunctionsFile << "<Not Defined>\n"; } else { aFunctionsFile << "\n"; pMemRange = &m_IOMemMap; while (pMemRange) { aFunctionsFile << "; " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ")\n"; pMemRange = pMemRange->GetNext(); } } aFunctionsFile << ";\n"; aFunctionsFile << "; Generated: " << std::ctime(&m_StartTime); // Note: std::ctime adds extra \n character, so no need to add our own aFunctionsFile << ";\n\n"; bTempFlag = false; if (!m_ROMMemMap.IsNullRange()) { pMemRange = &m_ROMMemMap; while (pMemRange) { std::ostringstream sstrTemp; sstrTemp << "#ROM|" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr(); sstrTemp << "|" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize(); sstrTemp << "\n"; m_sFunctionalOpcode = sstrTemp.str(); aFunctionsFile << m_sFunctionalOpcode; pMemRange = pMemRange->GetNext(); } bTempFlag = true; } if (!m_RAMMemMap.IsNullRange()) { pMemRange = &m_RAMMemMap; while (pMemRange) { std::ostringstream sstrTemp; sstrTemp << "#RAM|" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr(); sstrTemp << "|" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize(); sstrTemp << "\n"; m_sFunctionalOpcode = sstrTemp.str(); aFunctionsFile << m_sFunctionalOpcode; pMemRange = pMemRange->GetNext(); } bTempFlag = true; } if (!m_IOMemMap.IsNullRange()) { pMemRange = &m_IOMemMap; while (pMemRange) { std::ostringstream sstrTemp; sstrTemp << "#IO|" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr(); sstrTemp << "|" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize(); sstrTemp << "\n"; m_sFunctionalOpcode = sstrTemp.str(); aFunctionsFile << m_sFunctionalOpcode; pMemRange = pMemRange->GetNext(); } bTempFlag = true; } if (bTempFlag) aFunctionsFile << "\n"; bTempFlag = false; for (m_PC = 0; ((m_PC < m_Memory->GetMemSize()) && (RetVal)); m_PC++) { TLabelTableMap::const_iterator itrLabels = m_LabelTable.find(m_PC); if (itrLabels != m_LabelTable.end()) { std::ostringstream sstrTemp; bTempFlag2 = false; sstrTemp << "!" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << m_PC; sstrTemp << std::nouppercase << std::setbase(0) << "|"; for (unsigned int i = 0; i < itrLabels->second.size(); ++i) { if (bTempFlag2) sstrTemp << ","; if (!itrLabels->second.at(i).empty()) { sstrTemp << itrLabels->second.at(i); bTempFlag2 = true; } } sstrTemp << "\n"; m_sFunctionalOpcode = sstrTemp.str(); if (bTempFlag2) aFunctionsFile << m_sFunctionalOpcode; bTempFlag = true; } } if (bTempFlag) aFunctionsFile << "\n"; bInFunc = false; for (m_PC = 0; ((m_PC < m_Memory->GetMemSize()) && (RetVal)); ) { bLastFlag = false; bBranchOutFlag = false; // Check for function start/end flags: TAddressMap::const_iterator itrFunction = m_FunctionsTable.find(m_PC); if (itrFunction != m_FunctionsTable.end()) { switch (itrFunction->second) { case FUNCF_HARDSTOP: case FUNCF_EXITBRANCH: case FUNCF_SOFTSTOP: bInFunc = false; bLastFlag = true; break; case FUNCF_BRANCHOUT: bBranchOutFlag = true; break; case FUNCF_BRANCHIN: if (bInFunc) break; // Continue if already inside a function // Else, fall-through and setup for new function: case FUNCF_ENTRY: case FUNCF_INDIRECT: case FUNCF_CALL: { std::ostringstream sstrTemp; sstrTemp << "@" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << m_PC << "|"; m_sFunctionalOpcode = sstrTemp.str(); TLabelTableMap::const_iterator itrLabels = m_LabelTable.find(m_PC); if (itrLabels != m_LabelTable.end()) { for (unsigned int i = 0; i < itrLabels->second.size(); ++i) { if (i != 0) m_sFunctionalOpcode += ","; m_sFunctionalOpcode += FormatLabel(LC_REF, itrLabels->second.at(i), m_PC); } } else { m_sFunctionalOpcode += "???"; } aFunctionsFile << m_sFunctionalOpcode; aFunctionsFile << "\n"; nFuncAddr = m_PC; bInFunc = true; break; } default: assert(false); // Unexpected Function Flag!! Check Code!! RetVal = false; continue; } } nSavedPC = m_PC; m_sFunctionalOpcode = ""; switch (m_Memory->GetDescriptor(m_PC)) { case DMEM_NOTLOADED: m_PC++; bLastFlag = bInFunc; bInFunc = false; break; case DMEM_LOADED: assert(false); // WARNING! All loaded code should have been evaluated. Check override code! RetVal = false; m_PC++; break; case DMEM_DATA: case DMEM_PRINTDATA: case DMEM_CODEINDIRECT: case DMEM_DATAINDIRECT: case DMEM_ILLEGALCODE: { std::ostringstream sstrTemp; sstrTemp << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << m_PC << "|"; m_sFunctionalOpcode = sstrTemp.str(); TLabelTableMap::const_iterator itrLabels = m_LabelTable.find(m_PC); if (itrLabels != m_LabelTable.end()) { for (unsigned int i=0; i<itrLabels->second.size(); ++i) { if (i != 0) m_sFunctionalOpcode += ","; m_sFunctionalOpcode += FormatLabel(LC_REF, itrLabels->second.at(i), m_PC); } } sstrTemp.str(std::string()); sstrTemp << std::uppercase << std::setfill('0') << std::setw(2) << std::setbase(16) << m_Memory->GetByte(m_PC) << "|"; m_sFunctionalOpcode += sstrTemp.str(); m_PC++; break; } case DMEM_CODE: RetVal = ReadNextObj(false, msgFile, errFile); break; default: bInFunc = false; RetVal = false; break; } if (!m_sFunctionalOpcode.empty()) { std::ostringstream sstrTemp; sstrTemp << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (nSavedPC - nFuncAddr) << "|"; m_sFunctionalOpcode = sstrTemp.str() + m_sFunctionalOpcode; } if (bBranchOutFlag) { TAddressMap::const_iterator itrFunction = m_FunctionsTable.find(m_PC); if (itrFunction != m_FunctionsTable.end()) { switch (itrFunction->second) { case FUNCF_ENTRY: case FUNCF_INDIRECT: case FUNCF_CALL: bInFunc = false; bLastFlag = true; break; } } else { bInFunc = false; bLastFlag = true; } } if (bLastFlag) { TAddressMap::const_iterator itrFunction = m_FunctionsTable.find(m_PC); if (itrFunction != m_FunctionsTable.end()) { switch (itrFunction->second) { case FUNCF_BRANCHIN: bLastFlag = false; bInFunc = true; break; } } } if ((bInFunc) || (bLastFlag)) { if (!m_sFunctionalOpcode.empty()) { aFunctionsFile << m_sFunctionalOpcode; aFunctionsFile << "\n"; } if (bLastFlag) aFunctionsFile << "\n"; } } aFunctionsFile.close(); return RetVal; } std::string CDisassembler::FormatComments(MNEMONIC_CODE /* nMCCode */) // The default returns the reference comment string. { return FormatReferences(m_PC - m_OpMemory.size()); } std::string CDisassembler::FormatAddress(unsigned int nAddress) { std::ostringstream sstrTemp; sstrTemp << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << nAddress; return sstrTemp.str(); } std::string CDisassembler::FormatOpBytes() { std::ostringstream sstrTemp; for (unsigned int i=0; i<m_OpMemory.size(); ++i) { sstrTemp << std::uppercase << std::setfill('0') << std::setw(2) << std::setbase(16) << static_cast<unsigned int>(m_OpMemory.at(i)) << std::nouppercase << std::setbase(0); if (i < m_OpMemory.size()-1) sstrTemp << " "; } return sstrTemp.str(); } std::string CDisassembler::FormatLabel(LABEL_CODE /* nLC */, const std::string & szLabel, unsigned int nAddress) { std::ostringstream sstrTemp; if (szLabel.empty()) { sstrTemp << "L" << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << nAddress; } else { sstrTemp << szLabel; } return sstrTemp.str(); } std::string CDisassembler::FormatReferences(unsigned int nAddress) { std::string RetVal; bool Flag; RetVal = ""; Flag = false; TAddressTableMap::const_iterator itrBranches = m_BranchTable.find(nAddress); if (itrBranches != m_BranchTable.end()) { if (itrBranches->second.size() != 0) { RetVal += "CRef: "; Flag = true; for (unsigned int i=0; i<itrBranches->second.size(); ++i) { std::ostringstream sstrTemp; sstrTemp << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << itrBranches->second.at(i); RetVal += sstrTemp.str(); if (i < itrBranches->second.size()-1) RetVal += ","; } } } if (m_LabelTable.find(nAddress) != m_LabelTable.end()) { TAddressTableMap::const_iterator itrLabelRef = m_LabelRefTable.find(nAddress); if (itrLabelRef == m_LabelRefTable.end()) { assert(false); // Should also have a ref entry! return RetVal; } if (itrLabelRef->second.size() != 0) { if (Flag) RetVal += "; "; RetVal += "DRef: "; Flag = true; for (unsigned int i=0; i<itrLabelRef->second.size(); ++i) { std::ostringstream sstrTemp; sstrTemp << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << itrLabelRef->second.at(i); RetVal += sstrTemp.str(); if (i < itrLabelRef->second.size()-1) RetVal += ","; } } } return RetVal; } bool CDisassembler::WriteHeader(std::ostream& outFile, std::ostream * /* msgFile */, std::ostream * /* errFile */) { TStringArray OutLine; TMemRange *pMemRange; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(0); OutLine[FC_LABEL] = GetCommentStartDelim() + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim() + " " + GetGDCLongName() + " Generated Source Code " + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim() + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim() + " Control File"; OutLine[FC_LABEL] += ((m_sControlFileList.size() > 1) ? "s: " : ": "); for (unsigned int i=0; i<m_sControlFileList.size(); ++i) { if (i==0) { OutLine[FC_LABEL] += m_sControlFileList.at(i) + " " + GetCommentEndDelim() + "\n"; } else { OutLine[FC_LABEL] = GetCommentStartDelim() + " " + m_sControlFileList.at(i) + " " + GetCommentEndDelim() + "\n"; } outFile << MakeOutputLine(OutLine) << "\n"; } OutLine[FC_LABEL] = GetCommentStartDelim() + " Input File"; OutLine[FC_LABEL] += ((m_sInputFileList.size() > 1) ? "s: " : ": "); for (unsigned int i=0; i<m_sInputFileList.size(); ++i) { if (i==0) { OutLine[FC_LABEL] += m_sInputFileList.at(i) + " " + GetCommentEndDelim() + "\n"; } else { OutLine[FC_LABEL] = GetCommentStartDelim() + " " + m_sInputFileList.at(i) + " " + GetCommentEndDelim() + "\n"; } outFile << MakeOutputLine(OutLine) << "\n"; } OutLine[FC_LABEL] = GetCommentStartDelim() + " Output File: " + m_sOutputFilename + " " + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; if (!m_sFunctionsFilename.empty()) { OutLine[FC_LABEL] = GetCommentStartDelim() + " Functions File: " + m_sFunctionsFilename + " " + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; } OutLine[FC_LABEL] = GetCommentStartDelim() + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim() + " Memory Mappings:"; OutLine[FC_LABEL] += " ROM Memory Map: "; if (m_ROMMemMap.IsNullRange()) { OutLine[FC_LABEL] += "<Not Defined>" + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; } else { OutLine[FC_LABEL] += GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; pMemRange = &m_ROMMemMap; while (pMemRange) { std::ostringstream sstrTemp; sstrTemp << GetCommentStartDelim() << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ") " << GetCommentEndDelim() << "\n"; OutLine[FC_LABEL] = sstrTemp.str(); outFile << MakeOutputLine(OutLine) << "\n"; pMemRange = pMemRange->GetNext(); } } OutLine[FC_LABEL] = GetCommentStartDelim() + " RAM Memory Map: "; if (m_RAMMemMap.IsNullRange()) { OutLine[FC_LABEL] += "<Not Defined>" + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; } else { OutLine[FC_LABEL] += GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; pMemRange = &m_RAMMemMap; while (pMemRange) { std::ostringstream sstrTemp; sstrTemp << GetCommentStartDelim() << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ") " << GetCommentEndDelim() << "\n"; OutLine[FC_LABEL] = sstrTemp.str(); outFile << MakeOutputLine(OutLine) << "\n"; pMemRange = pMemRange->GetNext(); } } OutLine[FC_LABEL] = GetCommentStartDelim() + " IO Memory Map: "; if (m_IOMemMap.IsNullRange()) { OutLine[FC_LABEL] += "<Not Defined>" + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; } else { OutLine[FC_LABEL] += GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; pMemRange = &m_IOMemMap; while (pMemRange) { std::ostringstream sstrTemp; sstrTemp << GetCommentStartDelim() << " " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetStartAddr() << std::nouppercase << std::setbase(0) << " - " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << (pMemRange->GetStartAddr() + pMemRange->GetSize() - 1) << std::nouppercase << std::setbase(0) << " (Size: " << GetHexDelim() << std::uppercase << std::setfill('0') << std::setw(4) << std::setbase(16) << pMemRange->GetSize() << std::nouppercase << std::setbase(0) << ") " << GetCommentEndDelim() << "\n"; OutLine[FC_LABEL] = sstrTemp.str(); outFile << MakeOutputLine(OutLine) << "\n"; pMemRange = pMemRange->GetNext(); } } OutLine[FC_LABEL] = GetCommentStartDelim() + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim() + " Generated: "; OutLine[FC_LABEL] += std::ctime(&m_StartTime); OutLine[FC_LABEL].erase(OutLine[FC_LABEL].end()-1); // Note: std::ctime adds extra \n character OutLine[FC_LABEL] += GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim() + GetCommentEndDelim() + "\n"; outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL].clear(); outFile << MakeOutputLine(OutLine) << "\n"; outFile << MakeOutputLine(OutLine) << "\n"; return true; } bool CDisassembler::WritePreEquates(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default. { return true; } bool CDisassembler::WriteEquates(std::ostream& outFile, std::ostream *msgFile, std::ostream *errFile) { TStringArray OutLine; bool RetVal; m_OpMemory.clear(); // Remove bytes so all code will properly reference first and last PC addresses RetVal = false; if (WritePreEquates(outFile, msgFile, errFile)) { RetVal = true; ClearOutputLine(OutLine); for (m_PC = 0; m_PC < m_Memory->GetMemSize(); m_PC++) { assert(m_Memory->GetDescriptor(m_PC) != DMEM_LOADED); // Find Routines didn't find and analyze all memory!! Fix it! if (m_Memory->GetDescriptor(m_PC) != DMEM_NOTLOADED) continue; // Loaded addresses will get outputted during main part TLabelTableMap::const_iterator itrLabels = m_LabelTable.find(m_PC); if (itrLabels != m_LabelTable.end()) { OutLine[FC_ADDRESS] = FormatAddress(m_PC); for (unsigned int i=0; i<itrLabels->second.size(); ++i) { OutLine[FC_LABEL] = FormatLabel(LC_EQUATE, itrLabels->second.at(i), m_PC); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_EQUATE); OutLine[FC_OPERANDS] = FormatOperands(MC_EQUATE); OutLine[FC_COMMENT] = FormatComments(MC_EQUATE); outFile << MakeOutputLine(OutLine) << "\n"; } } } RetVal = RetVal && WritePostEquates(outFile, msgFile, errFile); } return RetVal; } bool CDisassembler::WritePostEquates(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WritePreDisassembly(std::ostream& outFile, std::ostream * /* msgFile */, std::ostream * /* errFile */) { TStringArray OutLine; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(0); outFile << MakeOutputLine(OutLine) << "\n"; outFile << MakeOutputLine(OutLine) << "\n"; return true; } bool CDisassembler::WriteDisassembly(std::ostream& outFile, std::ostream *msgFile, std::ostream *errFile) { bool RetVal; RetVal = false; if (WritePreDisassembly(outFile, msgFile, errFile)) { RetVal = true; for (m_PC = 0; ((m_PC < m_Memory->GetMemSize()) && (RetVal)); ) { // WARNING!! WriteSection MUST increment m_PC switch (m_Memory->GetDescriptor(m_PC)) { case DMEM_NOTLOADED: m_PC++; break; case DMEM_LOADED: assert(false); // WARNING! All loaded code should have been evaluated. Check override code! RetVal = false; m_PC++; break; case DMEM_DATA: case DMEM_PRINTDATA: case DMEM_CODEINDIRECT: case DMEM_DATAINDIRECT: case DMEM_CODE: case DMEM_ILLEGALCODE: RetVal = RetVal && WriteSection(outFile, msgFile, errFile); // WARNING!! WriteSection MUST properly increment m_PC!! break; } } RetVal = RetVal && WritePostDisassembly(outFile, msgFile, errFile); } return RetVal; } bool CDisassembler::WritePostDisassembly(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WritePreSection(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WriteSection(std::ostream& outFile, std::ostream *msgFile, std::ostream *errFile) { bool RetVal; bool Done; RetVal = false; if (WritePreSection(outFile, msgFile, errFile)) { RetVal = true; Done = false; while ((m_PC < m_Memory->GetMemSize()) && (Done == false) && (RetVal)) { // WARNING!! Write Data and Code section functions MUST properly increment m_PC!! switch (m_Memory->GetDescriptor(m_PC)) { case DMEM_DATA: case DMEM_PRINTDATA: case DMEM_CODEINDIRECT: case DMEM_DATAINDIRECT: RetVal = RetVal && WriteDataSection(outFile, msgFile, errFile); break; case DMEM_CODE: case DMEM_ILLEGALCODE: RetVal = RetVal && WriteCodeSection(outFile, msgFile, errFile); break; default: Done = true; break; } } RetVal = RetVal && WritePostSection(outFile, msgFile, errFile); } return RetVal; } bool CDisassembler::WritePostSection(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WritePreDataSection(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WriteDataSection(std::ostream& outFile, std::ostream *msgFile, std::ostream *errFile) { bool RetVal; TStringArray OutLine; bool Done; unsigned int SavedPC; int Count; bool Flag; MEM_DESC Code; std::string TempLabel; TByteArray TempOpMemory; ClearOutputLine(OutLine); RetVal = false; if (WritePreDataSection(outFile, msgFile, errFile)) { RetVal = true; Done = false; while ((m_PC < m_Memory->GetMemSize()) && (Done == false) && (RetVal)) { ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); TLabelTableMap::const_iterator itrLabels = m_LabelTable.find(m_PC); if (itrLabels != m_LabelTable.end()) { for (unsigned int i=1; i<itrLabels->second.size(); ++i) { OutLine[FC_LABEL] = FormatLabel(LC_DATA, itrLabels->second.at(i), m_PC); outFile << MakeOutputLine(OutLine) << "\n"; } if (itrLabels->second.size()) OutLine[FC_LABEL] = FormatLabel(LC_DATA, itrLabels->second.at(0), m_PC); } SavedPC = m_PC; // Keep a copy of the PC for this line because some calls will be incrementing our m_PC Code = (MEM_DESC)m_Memory->GetDescriptor(m_PC); if ((m_bAsciiFlag == false) && (Code == DMEM_PRINTDATA)) Code = DMEM_DATA; // If not doing ASCII, treat print data as data switch (Code) { case DMEM_DATA: Count = 0; m_OpMemory.clear(); Flag = false; while (Flag == false) { m_OpMemory.push_back(m_Memory->GetByte(m_PC++)); Count++; // Stop on this line when we've either run out of data, hit the specified line limit, or hit another label if (Count >= m_nMaxNonPrint) Flag = true; if (m_LabelTable.find(m_PC) != m_LabelTable.end()) Flag = true; Code = (MEM_DESC)m_Memory->GetDescriptor(m_PC); if ((m_bAsciiFlag == false) && (Code == DMEM_PRINTDATA)) Code = DMEM_DATA; // If not doing ASCII, treat print data as data if (Code != DMEM_DATA) Flag = true; } if (m_bDataOpBytesFlag) OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_DATABYTE); OutLine[FC_OPERANDS] = FormatOperands(MC_DATABYTE); OutLine[FC_COMMENT] = FormatComments(MC_DATABYTE); outFile << MakeOutputLine(OutLine) << "\n"; break; case DMEM_PRINTDATA: Count = 0; m_OpMemory.clear(); Flag = false; while (Flag == false) { m_OpMemory.push_back(m_Memory->GetByte(m_PC++)); Count++; // Stop on this line when we've either run out of data, hit the specified line limit, or hit another label if (Count >= m_nMaxPrint) Flag = true; if (m_LabelTable.find(m_PC) != m_LabelTable.end()) Flag = true; if (m_Memory->GetDescriptor(m_PC) != DMEM_PRINTDATA) Flag = true; } // First, print a line of the output bytes for reference: if (m_bAsciiBytesFlag) { TempLabel = OutLine[FC_LABEL]; TempOpMemory = m_OpMemory; Count = TempOpMemory.size(); while (Count) { m_OpMemory.clear(); for (int i=0; ((i<Count) && (i<m_nMaxNonPrint)); ++i) m_OpMemory.push_back(TempOpMemory.at(TempOpMemory.size()-Count+i)); OutLine[FC_LABEL] = GetCommentStartDelim() + " " + TempLabel + ((!TempLabel.empty()) ? " " : "") + FormatOperands(MC_DATABYTE) + " " + GetCommentEndDelim(); OutLine[FC_ADDRESS] = FormatAddress(m_PC-Count); OutLine[FC_MNEMONIC] = ""; OutLine[FC_OPERANDS] = ""; OutLine[FC_COMMENT] = ""; outFile << MakeOutputLine(OutLine) << "\n"; Count -= m_OpMemory.size(); } OutLine[FC_LABEL] = TempLabel; m_OpMemory = TempOpMemory; } // Then, print the line as it should be in the ASCII equivalent: OutLine[FC_ADDRESS] = FormatAddress(SavedPC); if (m_bDataOpBytesFlag) OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_ASCII); OutLine[FC_OPERANDS] = FormatOperands(MC_ASCII); OutLine[FC_COMMENT] = FormatComments(MC_ASCII); outFile << MakeOutputLine(OutLine) << "\n"; break; case DMEM_CODEINDIRECT: case DMEM_DATAINDIRECT: // If the following call returns false, that means that the user (or // special indirect detection logic) erroneously specified (or detected) // the indirect. So instead of throwing an error or causing problems, // we will treat it as a data byte instead: if (RetrieveIndirect(msgFile, errFile) == false) { // Bumps PC if (m_bDataOpBytesFlag) OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_DATABYTE); OutLine[FC_OPERANDS] = FormatOperands(MC_DATABYTE); OutLine[FC_COMMENT] = FormatComments(MC_DATABYTE) + " -- Erroneous Indirect Stub"; outFile << MakeOutputLine(OutLine) << "\n"; break; } if (m_bDataOpBytesFlag) OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_INDIRECT); OutLine[FC_OPERANDS] = FormatOperands(MC_INDIRECT); OutLine[FC_COMMENT] = FormatComments(MC_INDIRECT); outFile << MakeOutputLine(OutLine) << "\n"; break; default: Done = true; } } RetVal = RetVal && WritePostDataSection(outFile, msgFile, errFile); } return RetVal; } bool CDisassembler::WritePostDataSection(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WritePreCodeSection(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WriteCodeSection(std::ostream& outFile, std::ostream *msgFile, std::ostream *errFile) { bool RetVal; TStringArray OutLine; bool Done; unsigned int SavedPC; bool bInFunc; bool bLastFlag; bool bBranchOutFlag; ClearOutputLine(OutLine); RetVal = false; if (WritePreCodeSection(outFile, msgFile, errFile)) { RetVal = true; bInFunc = false; Done = false; while ((m_PC < m_Memory->GetMemSize()) && (Done == false) && (RetVal)) { bLastFlag = false; bBranchOutFlag = false; // Check for function start/end flags: TAddressMap::const_iterator itrFunction = m_FunctionsTable.find(m_PC); if (itrFunction != m_FunctionsTable.end()) { switch (itrFunction->second) { case FUNCF_HARDSTOP: case FUNCF_EXITBRANCH: case FUNCF_SOFTSTOP: bInFunc = false; bLastFlag = true; break; case FUNCF_BRANCHOUT: bBranchOutFlag = true; break; case FUNCF_BRANCHIN: if (bInFunc) { RetVal = RetVal && WriteIntraFunctionSep(outFile, msgFile, errFile); break; // Continue if already inside a function (after printing a soft-break) } // Else, fall-through and setup for new function: case FUNCF_ENTRY: case FUNCF_INDIRECT: case FUNCF_CALL: RetVal = RetVal && WritePreFunction(outFile, msgFile, errFile); bInFunc = true; break; default: assert(false); // Unexpected Function Flag!! Check Code!! RetVal = false; continue; } } ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); TLabelTableMap::const_iterator itrLabels = m_LabelTable.find(m_PC); if (itrLabels != m_LabelTable.end()) { for (unsigned int i=1; i<itrLabels->second.size(); ++i) { OutLine[FC_LABEL] = FormatLabel(LC_CODE, itrLabels->second.at(i), m_PC); outFile << MakeOutputLine(OutLine) << "\n"; } if (itrLabels->second.size()) OutLine[FC_LABEL] = FormatLabel(LC_CODE, itrLabels->second.at(0), m_PC); } SavedPC = m_PC; // Keep a copy of the PC for this line because some calls will be incrementing our m_PC switch (m_Memory->GetDescriptor(m_PC)) { case DMEM_ILLEGALCODE: m_OpMemory.clear(); m_OpMemory.push_back(m_Memory->GetByte(m_PC++)); OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_ILLOP); OutLine[FC_OPERANDS] = FormatOperands(MC_ILLOP); OutLine[FC_COMMENT] = FormatComments(MC_ILLOP); outFile << MakeOutputLine(OutLine) << "\n"; break; case DMEM_CODE: // If the following call returns false, that means that we erroneously // detected code in the first pass so instead of throwing an error or // causing problems, we will treat it as an illegal opcode: if (ReadNextObj(false, msgFile, errFile) == false) { // Bumps PC // Flag it as illegal and then process it as such: m_Memory->SetDescriptor(SavedPC, DMEM_ILLEGALCODE); OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_ILLOP); OutLine[FC_OPERANDS] = FormatOperands(MC_ILLOP); OutLine[FC_COMMENT] = FormatComments(MC_ILLOP); outFile << MakeOutputLine(OutLine) << "\n"; break; } OutLine[FC_OPBYTES] = FormatOpBytes(); OutLine[FC_MNEMONIC] = FormatMnemonic(MC_OPCODE); OutLine[FC_OPERANDS] = FormatOperands(MC_OPCODE); OutLine[FC_COMMENT] = FormatComments(MC_OPCODE); outFile << MakeOutputLine(OutLine) << "\n"; break; default: Done = true; } if (bBranchOutFlag) { itrFunction = m_FunctionsTable.find(m_PC); if (itrFunction != m_FunctionsTable.end()) { switch (itrFunction->second) { case FUNCF_ENTRY: case FUNCF_INDIRECT: case FUNCF_CALL: bInFunc = false; bLastFlag = true; break; } } else { bInFunc = false; bLastFlag = true; } } if (bLastFlag) { itrFunction = m_FunctionsTable.find(m_PC); if (itrFunction != m_FunctionsTable.end()) { switch (itrFunction->second) { case FUNCF_BRANCHIN: bLastFlag = false; bInFunc = true; break; } } } if (/*(bInFunc) || */ (bLastFlag)) { RetVal = RetVal & WritePostFunction(outFile, msgFile, errFile); } } RetVal = RetVal && WritePostCodeSection(outFile, msgFile, errFile); } return RetVal; } bool CDisassembler::WritePostCodeSection(std::ostream& /* outFile */, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Don't do anything by default { return true; } bool CDisassembler::WritePreFunction(std::ostream& outFile, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Default is separator bar { TStringArray OutLine; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); outFile << MakeOutputLine(OutLine) << "\n"; OutLine[FC_LABEL] = GetCommentStartDelim(); OutLine[FC_LABEL] += " "; for (int i=(GetFieldWidth(FC_LABEL)+ GetFieldWidth(FC_MNEMONIC)+ GetFieldWidth(FC_OPERANDS)); i; i--) OutLine[FC_LABEL] += "="; OutLine[FC_LABEL] += " "; OutLine[FC_LABEL] += GetCommentEndDelim(); outFile << MakeOutputLine(OutLine) << "\n"; return true; } bool CDisassembler::WriteIntraFunctionSep(std::ostream& outFile, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Default is separator bar { TStringArray OutLine; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); OutLine[FC_LABEL] = GetCommentStartDelim(); OutLine[FC_LABEL] += " "; for (int i=(GetFieldWidth(FC_LABEL)+ GetFieldWidth(FC_MNEMONIC)+ GetFieldWidth(FC_OPERANDS)); i; i--) OutLine[FC_LABEL] += "-"; OutLine[FC_LABEL] += " "; OutLine[FC_LABEL] += GetCommentEndDelim(); outFile << MakeOutputLine(OutLine) << "\n"; return true; } bool CDisassembler::WritePostFunction(std::ostream& outFile, std::ostream * /* msgFile */, std::ostream * /* errFile */) // Default is separator bar { TStringArray OutLine; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); OutLine[FC_LABEL] = GetCommentStartDelim(); OutLine[FC_LABEL] += " "; for (int i=(GetFieldWidth(FC_LABEL)+ GetFieldWidth(FC_MNEMONIC)+ GetFieldWidth(FC_OPERANDS)); i; i--) OutLine[FC_LABEL] += "="; OutLine[FC_LABEL] += " "; OutLine[FC_LABEL] += GetCommentEndDelim(); outFile << MakeOutputLine(OutLine) << "\n"; ClearOutputLine(OutLine); OutLine[FC_ADDRESS] = FormatAddress(m_PC); outFile << MakeOutputLine(OutLine) << "\n"; return true; } int CDisassembler::GetFieldWidth(FIELD_CODE nFC) { switch (nFC) { case FC_ADDRESS: return CALC_FIELD_WIDTH(8); case FC_OPBYTES: return CALC_FIELD_WIDTH(12); case FC_LABEL: return CALC_FIELD_WIDTH(14); case FC_MNEMONIC: return CALC_FIELD_WIDTH(8); case FC_OPERANDS: return CALC_FIELD_WIDTH(44); case FC_COMMENT: return CALC_FIELD_WIDTH(60); } return 0; } std::string CDisassembler::MakeOutputLine(TStringArray& saOutputData) { std::string OutputStr; std::string Temp,Temp2; std::string Item; std::size_t fw; std::size_t pos; std::size_t tfw; std::size_t TempPos; std::string OpBytePart; std::string CommentPart; TStringArray WrapSave; int Toss; bool LabelBreak; std::string SaveLabel; // This function will "wrap" the FC_OPBYTES and FC_COMMENT fields and create a // result that spans multiple lines if they are longer than the field width. // Wrapping is first attempted via white-space and/or one of ",;:.!?" symbols. If // that fails, the line is truncated at the specified length. All other // fields are not wrapped. Note that embedded tabs count as 1 character for the // wrapping mechanism! Also, a '\n' can be used in the FC_COMMENT field to force // a break. All other fields should NOT have a '\n' character! // // A '\v' (vertical tab or 0x0B) at the end of FC_LABEL will cause the label to // appear on a line by itself -- the '\v' for labels should appear only at the end // of the label -- not in the middle of it!. // OpBytePart = ""; CommentPart = ""; LabelBreak = false; OutputStr = ""; pos = 0; tfw = 0; fw = 0; for (unsigned int i=0; i<saOutputData.size(); ++i) { Item = saOutputData[i]; tfw += fw; fw = GetFieldWidth((FIELD_CODE) i); if ((m_bAddrFlag == false) && (i == FC_ADDRESS)) { pos += fw; continue; } if ((m_bOpcodeFlag == false) && (i == FC_OPBYTES)) { pos += fw; continue; } if (i == FC_LABEL) { // Check for Label Break: if (Item.find('\v') != std::string::npos) { while (Item.find('\v') != std::string::npos) { Item = Item.substr(0, Item.find('\v')) + Item.substr(Item.find('\v')+1); } SaveLabel = Item; Item.clear(); LabelBreak = true; } } if (i == FC_OPBYTES) { // Check OpBytes "wrap" if (Item.size() > fw) { Temp = Item.substr(0, fw); TempPos = Temp.find_last_of(" \t,;:.!?"); if (TempPos != std::string::npos) { Toss = ((Temp.find_last_of(" \t")==TempPos) ? 1 : 0); Temp = Item.substr(0, TempPos + 1 - Toss); // Throw ' ' and '\t' away OpBytePart = Item.substr(TempPos + Toss); Item = Temp; } else { OpBytePart = Item.substr(fw+1); Item = Item.substr(0, fw); } } } if (i == FC_COMMENT) { // Check comment "wrap" Temp = GetCommentStartDelim() + " " + Item + " " + GetCommentEndDelim(); Temp2 = GetCommentStartDelim() + " " + GetCommentEndDelim(); if ((Temp.size() > fw) || (Temp.find('\n') != std::string::npos)) { Temp = Item.substr(0, fw - Temp2.size()); TempPos = Temp.find_last_of(" \n\t,;:.!?"); if (TempPos != std::string::npos) { Toss = ((Temp.find_last_of(" \n\t")==TempPos) ? 1 : 0); Temp = Item.substr(0, TempPos + 1 - Toss); // Throw ' ' and '\t' away CommentPart = " " + Item.substr(TempPos+1 + Toss); Item = Temp; } else { CommentPart = " " + Item.substr(fw+1-Temp2.size()); Item = Item.substr(0, fw-Temp2.size()); } } } if (i == FC_COMMENT) { if (!Item.empty()) Item = GetCommentStartDelim() + " " + Item + " " + GetCommentEndDelim(); } if (m_bTabsFlag) { while (pos < tfw) { if (m_nTabWidth != 0) { while ((tfw - pos) % m_nTabWidth) { OutputStr += " "; pos++; } while ((tfw - pos) / m_nTabWidth) { OutputStr += "\t"; pos += m_nTabWidth; } } else { OutputStr += " "; pos++; } } OutputStr += Item; } else { Temp = ""; for (int j=0; j<m_nTabWidth; j++) Temp += " "; while (Item.find('\t') != std::string::npos) { TempPos = Item.find('\t'); Item = Item.substr(0, TempPos) + Temp + Item.substr(TempPos+1); } while (pos < tfw) { OutputStr += " "; pos++; } OutputStr += Item; } pos += Item.size(); if (pos >= (tfw+fw)) pos = tfw+fw-1; // Sub 1 to force at least 1 space between fields } // Remove all extra white space on right-hand side: rtrim(OutputStr); if ((!OpBytePart.empty()) || (!CommentPart.empty()) || (LabelBreak)) { // Save data: WrapSave = saOutputData; if (saOutputData.size() < NUM_FIELD_CODES) for (unsigned int i=saOutputData.size(); i<NUM_FIELD_CODES; ++i) saOutputData.push_back(std::string()); if (LabelBreak) { saOutputData[FC_OPBYTES] = ""; saOutputData[FC_LABEL] = SaveLabel; saOutputData[FC_MNEMONIC] = ""; saOutputData[FC_OPERANDS] = ""; saOutputData[FC_COMMENT] = ""; OutputStr = MakeOutputLine(saOutputData) + "\n" + OutputStr; // Call recursively } if ((!OpBytePart.empty()) || (!CommentPart.empty())) { saOutputData[FC_OPBYTES] = OpBytePart; saOutputData[FC_LABEL] = ""; saOutputData[FC_MNEMONIC] = ""; saOutputData[FC_OPERANDS] = ""; saOutputData[FC_COMMENT] = CommentPart; OutputStr += "\n"; OutputStr += MakeOutputLine(saOutputData); // Call recursively } // Restore data: saOutputData = WrapSave; } return OutputStr; } void CDisassembler::ClearOutputLine(TStringArray& saOutputData) { saOutputData.clear(); saOutputData.reserve(NUM_FIELD_CODES); for (unsigned int i=0; i<NUM_FIELD_CODES; ++i) saOutputData.push_back(std::string()); } <file_sep>/programs/funcanal/FuncView/OutputView.cpp // OutputView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: OutputView.cpp,v $ // Revision 1.1 2003/09/13 05:45:47 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "FuncViewPrjDoc.h" #include "OutputView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // COutputViewFile COutputViewFile::COutputViewFile(COutputView &rOutputView) : m_rOutputView(rOutputView), m_bEraseOnNextWrite(TRUE) { } COutputViewFile::~COutputViewFile() { } #ifdef _DEBUG void COutputViewFile::AssertValid() const { CFile::AssertValid(); } void COutputViewFile::Dump(CDumpContext& dc) const { CFile::Dump(dc); } #endif DWORD COutputViewFile::GetPosition() const { return 0; // Always a zero-length file } BOOL COutputViewFile::GetStatus(CFileStatus& rStatus) const { rStatus.m_ctime = 0; rStatus.m_mtime = 0; rStatus.m_atime = 0; rStatus.m_size = 0; rStatus.m_attribute = normal; rStatus.m_szFullName[0] = '\0'; return TRUE; } LONG COutputViewFile::Seek(LONG lOff, UINT nFrom) { return 0; // All offsets are legal, but we are zero length } void COutputViewFile::SetLength(DWORD dwNewLen) { // Do nothing } UINT COutputViewFile::Read(void* lpBuf, UINT nCount) { return 0; // This is an output only file } void COutputViewFile::Write(const void* lpBuf, UINT nCount) { CEdit &theEdit = m_rOutputView.GetEditCtrl(); if (m_bEraseOnNextWrite) { m_bEraseOnNextWrite = FALSE; theEdit.SetWindowText(""); } CString strTemp; LPTSTR pBuffer = strTemp.GetBuffer(nCount + 1); memcpy(pBuffer, lpBuf, nCount); strTemp.ReleaseBuffer(nCount); UINT nLen = m_rOutputView.GetBufferLength(); theEdit.SetSel(nLen, nLen, TRUE); theEdit.ReplaceSel(strTemp); nLen = m_rOutputView.GetBufferLength(); theEdit.SetSel(nLen, nLen, FALSE); } void COutputViewFile::Abort() { m_bEraseOnNextWrite = TRUE; } void COutputViewFile::Flush() { // Do nothing } void COutputViewFile::Close() { m_bEraseOnNextWrite = TRUE; } CFile* COutputViewFile::Duplicate() const { AfxThrowNotSupportedException(); return NULL; } void COutputViewFile::LockRange(DWORD dwPos, DWORD dwCount) { AfxThrowNotSupportedException(); } void COutputViewFile::UnlockRange(DWORD dwPos, DWORD dwCount) { AfxThrowNotSupportedException(); } ///////////////////////////////////////////////////////////////////////////// // COutputView IMPLEMENT_DYNCREATE(COutputView, CEditView) COutputView::COutputView() { m_pOutputViewFile = NULL; m_fntOutput.CreatePointFont(100, "Courier New"); } COutputView::~COutputView() { if (m_pOutputViewFile) { delete m_pOutputViewFile; m_pOutputViewFile = NULL; } } BEGIN_MESSAGE_MAP(COutputView, CEditView) //{{AFX_MSG_MAP(COutputView) ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // COutputView diagnostics #ifdef _DEBUG void COutputView::AssertValid() const { CEditView::AssertValid(); } void COutputView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } CFuncViewPrjDoc* COutputView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // COutputView message handlers void COutputView::OnInitialUpdate() { CEdit &theEdit = GetEditCtrl(); m_pOutputViewFile = new COutputViewFile(*this); theEdit.SetFont(&m_fntOutput); theEdit.SetReadOnly(); theEdit.SetWindowText(GetDocument()->GetOutputText()); UINT nLen = GetBufferLength(); theEdit.SetSel(nLen-1, nLen, FALSE); theEdit.SetSel(nLen, nLen, FALSE); CEditView::OnInitialUpdate(); } void COutputView::OnDestroy() { CEdit &theEdit = GetEditCtrl(); theEdit.GetWindowText(GetDocument()->GetOutputText()); CEditView::OnDestroy(); } <file_sep>/programs/funcanal/FuncView/CompDiffEditView.h // CompDiffEditView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: CompDiffEditView.h,v $ // Revision 1.1 2003/09/13 05:45:37 dewhisna // Initial Revision // // #if !defined(AFX_COMPDIFFEDITVIEW_H__1A399480_51DB_4106_8311_DE331ED9A3A0__INCLUDED_) #define AFX_COMPDIFFEDITVIEW_H__1A399480_51DB_4106_8311_DE331ED9A3A0__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "FuncViewPrjDoc.h" ///////////////////////////////////////////////////////////////////////////// // CCompDiffEditView view class CCompDiffEditView : public CEditView { protected: CCompDiffEditView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CCompDiffEditView) // Attributes public: CFuncViewPrjDoc* GetDocument(); protected: CFont m_fntEditor; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCompDiffEditView) public: virtual void OnInitialUpdate(); protected: virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); //}}AFX_VIRTUAL // Implementation protected: virtual ~CCompDiffEditView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(CCompDiffEditView) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in CompDiffEditView.cpp inline CFuncViewPrjDoc* CCompDiffEditView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_COMPDIFFEDITVIEW_H__1A399480_51DB_4106_8311_DE331ED9A3A0__INCLUDED_) <file_sep>/programs/funcanal/FuncView/ChildFrm3.h // ChildFrm3.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm3.h,v $ // Revision 1.1 2003/09/13 05:45:33 dewhisna // Initial Revision // // #if !defined(AFX_CHILDFRM3_H__A86FCD44_79E0_4642_8520_2C75C5B83EF6__INCLUDED_) #define AFX_CHILDFRM3_H__A86FCD44_79E0_4642_8520_2C75C5B83EF6__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ChildFrmBase.h" ///////////////////////////////////////////////////////////////////////////// // CChildFrame3 frame class CChildFrame3 : public CChildFrameBase { DECLARE_DYNCREATE(CChildFrame3) protected: CChildFrame3(); // protected constructor used by dynamic creation // Attributes public: protected: CSplitterWnd m_wndSplitter; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame3) protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation protected: virtual ~CChildFrame3(); // Generated message map functions //{{AFX_MSG(CChildFrame3) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDFRM3_H__A86FCD44_79E0_4642_8520_2C75C5B83EF6__INCLUDED_) <file_sep>/programs/funcanal/funcdesc.h // funcdesc.h: interface for the CFuncDesc, CFuncDescFile, and CFuncObject classes. // // $Log: funcdesc.h,v $ // Revision 1.4 2003/09/13 05:38:48 dewhisna // Added Read/Write File support. Added output options on output line creation // for function diff and added returning of match percentage. Added callback // function for read operation feedback. Enhanced symbol map manipulation. // // Revision 1.3 2003/02/09 06:59:57 dewhisna // Split comparison logic from Function File I/O // // Revision 1.2 2002/09/15 22:54:03 dewhisna // Added Symbol Table comparison support // // Revision 1.1 2002/07/01 05:50:01 dewhisna // Initial Revision // // #if !defined(AFX_FUNCDESC_H__E6CF1B55_6B17_4909_A17F_B572ED0ED0E6__INCLUDED_) #define AFX_FUNCDESC_H__E6CF1B55_6B17_4909_A17F_B572ED0ED0E6__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <MemClass.h> #include "funccomp.h" // Foward Declarations: class CFuncDesc; class CFuncDescFile; class CSymbolMap; #define CALC_FIELD_WIDTH(x) x ////////////////////////////////////////////////////////////////////// // Global Functions ////////////////////////////////////////////////////////////////////// extern CString PadString(LPCTSTR pszString, int nWidth); ////////////////////////////////////////////////////////////////////// // Callback Functions ////////////////////////////////////////////////////////////////////// // Function Analysis Progress Callback -- Used in functions that take // a while to do processing (like reading a file). Passes // current progress position, maximum progress value, a flag // indicating if the user/client can currently cancel operation, // and a client defined lParam. Returns True/False Cancel Status. // True=Cancel, False=Continue. If progress indexes aren't supported // then nProgressPos will always be 0 and nProgressMax always 1. typedef BOOL (CALLBACK * LPFUNCANALPROGRESSCALLBACK)(int nProgressPos, int nProgressMax, BOOL bAllowCancel, LPARAM lParam); ////////////////////////////////////////////////////////////////////// // CFuncObject Class ////////////////////////////////////////////////////////////////////// // This specifies a pure virtual base class for defining // Function Objects: class CFuncObject : public CObject { public: CFuncObject(CFuncDescFile &ParentFuncFile, CFuncDesc &ParentFunc, CStringArray &argv); virtual ~CFuncObject(); virtual BOOL IsExactMatch(CFuncObject *pObj); virtual BOOL AddLabel(LPCTSTR pszLabel); DWORD GetRelFuncAddress(); DWORD GetAbsAddress(); int GetLabelCount(); CString GetLabel(int nIndex); CString GetBytes(); int GetByteCount(); virtual CString ExportToDiff() = 0; virtual void ExportToDiff(CStringArray &anArray) = 0; virtual CString CreateOutputLine(DWORD nOutputOptions = 0) = 0; virtual void GetSymbols(CStringArray &aSymbolArray); // Returns specially encoded symbol array (see implementation comments) // The following define field positions for obtaining field widths from overrides. // Additional entries can be added on overrides, but this order should NOT change // in order to maintain backward compatibility at all times: #define NUM_FIELD_CODES 6 enum FIELD_CODE { FC_ADDRESS, FC_OPBYTES, FC_LABEL, FC_MNEMONIC, FC_OPERANDS, FC_COMMENT }; static int GetFieldWidth(FIELD_CODE nFC); protected: CFuncDescFile &m_ParentFuncFile; CFuncDesc &m_ParentFunc; DWORD m_dwRelFuncAddress; // Address of object relative to function start DWORD m_dwAbsAddress; // Absolute Address of object CStringArray m_LabelTable; // Labels assigned to this object CByteArray m_Bytes; // Array of bytes for this object }; ////////////////////////////////////////////////////////////////////// // CFuncAsmInstObject Class ////////////////////////////////////////////////////////////////////// // This class specifies an assembly instruction object class CFuncAsmInstObject : public CFuncObject { public: CFuncAsmInstObject(CFuncDescFile &ParentFuncFile, CFuncDesc &ParentFunc, CStringArray &argv); virtual ~CFuncAsmInstObject(); virtual CString ExportToDiff(); virtual void ExportToDiff(CStringArray &anArray); virtual CString CreateOutputLine(DWORD nOutputOptions = 0); virtual void GetSymbols(CStringArray &aSymbolArray); // Returns specially encoded symbol array (see implementation comments) CString GetOpCodeBytes(); int GetOpCodeByteCount(); CString GetOperandBytes(); int GetOperandByteCount(); protected: CByteArray m_OpCodeBytes; // Array of OpCode Bytes for this instruction CByteArray m_OperandBytes; // Array of Operand Bytes for ths instruction CString m_strDstOperand; // Encoded Destination Operand CString m_strSrcOperand; // Encoded Source Operand CString m_strOpCodeText; // Textual OpCode mnemonic CString m_strOperandText; // Textual Operands }; ////////////////////////////////////////////////////////////////////// // CFuncDataByteObject Class ////////////////////////////////////////////////////////////////////// // This class specifies a function embedded data byte object class CFuncDataByteObject : public CFuncObject { public: CFuncDataByteObject(CFuncDescFile &ParentFuncFile, CFuncDesc &ParentFunc, CStringArray &argv); virtual ~CFuncDataByteObject(); virtual CString ExportToDiff(); virtual void ExportToDiff(CStringArray &anArray); virtual CString CreateOutputLine(DWORD nOutputOptions = 0); }; ////////////////////////////////////////////////////////////////////// // CFuncDesc Class ////////////////////////////////////////////////////////////////////// // This specifies exactly one function as an array of CFuncObject // objects: class CFuncDesc : public CTypedPtrArray<CObArray, CFuncObject *> { public: CFuncDesc(DWORD nAddress, LPCTSTR pszNames); virtual ~CFuncDesc(); void FreeAll(); virtual BOOL AddName(DWORD nAddress, LPCTSTR pszLabel); virtual CString GetMainName(); virtual DWORD GetMainAddress(); virtual BOOL AddLabel(DWORD nAddress, LPCTSTR pszLabel); virtual BOOL AddrHasLabel(DWORD nAddress); virtual CString GetPrimaryLabel(DWORD nAddress); virtual CStringArray *GetLabelList(DWORD nAddress); virtual DWORD GetFuncSize(); // Returns size of function in byte counts (used for address calculation) virtual CString ExportToDiff(); virtual void ExportToDiff(CStringArray &anArray); int Add(CFuncObject *anObj); // Warning: This object supports ADDing only! Removing an item does NOT remove labels // that have been added nor decrement the function size! To modify a function // description, create a new function object with only the new elements desired!! // This has been done to improve speed efficiency! protected: DWORD m_dwMainAddress; // Main Address is the address defined at instantiation time. Additional relocated declarations might be defined in the name list DWORD m_dwFunctionSize; // Count of bytes in function -- used to calculate addressing inside the function // Note: The File's Label Table only contains those labels defined // internally in this function and may not directly // correspond to that of the file level. These might // contain 'L' labels. CMap<DWORD, DWORD, CStringArray*, CStringArray*> m_FuncNameTable; // Table of names for this function. First entry is typical default CMap<DWORD, DWORD, CStringArray*, CStringArray*> m_LabelTable; // Table of labels in this function. First entry is typical default }; ////////////////////////////////////////////////////////////////////// // CFuncDescFile Class ////////////////////////////////////////////////////////////////////// // This specifies all of the information from a single Func // Description File. It contains a CFuncDescArray of all of // the functions in the file, but also contains the file mapping // and label information: class CFuncDescFile : public CObject { public: CFuncDescFile(); virtual ~CFuncDescFile(); void FreeAll(); virtual BOOL ReadFuncDescFile(CFile& inFile, CFile *msgFile = NULL, CFile *errFile = NULL, int nStartLineCount = 0); // Read already open control file 'infile', outputs messages to 'msgFile' and errors to 'errFile', nStartLineCount = initial line counter value virtual BOOL AddLabel(DWORD nAddress, LPCTSTR pszLabel); virtual BOOL AddrHasLabel(DWORD nAddress); virtual CString GetPrimaryLabel(DWORD nAddress); virtual CStringArray *GetLabelList(DWORD nAddress); virtual int GetFuncCount(); virtual CFuncDesc *GetFunc(int nIndex); CString GetFuncPathName(); CString GetFuncFileName(); virtual BOOL IsROMMemAddr(DWORD nAddress); virtual BOOL IsRAMMemAddr(DWORD nAddress); virtual BOOL IsIOMemAddr(DWORD nAddress); virtual SetProgressCallback(LPFUNCANALPROGRESSCALLBACK pfnCallback, LPARAM lParam) { m_pfnProgressCallback = pfnCallback; m_lParamProgressCallback = lParam; } protected: CString m_strFilePathName; CString m_strFileName; TMemRange m_ROMMemMap; // Mapping of ROM memory TMemRange m_RAMMemMap; // Mapping of RAM memory TMemRange m_IOMemMap; // Mapping of memory mapped I/O LPFUNCANALPROGRESSCALLBACK m_pfnProgressCallback; LPARAM m_lParamProgressCallback; // Note: The File's Label Table only contains those labels defined // at the file level by "!" entries. NOT those down at the // individual function level. Specifically it doesn't // include 'L' names. CMap<DWORD, DWORD, CStringArray*, CStringArray*> m_LabelTable; // Table of labels. First entry is typical default CTypedPtrArray<CObArray, CFuncDesc*> m_Functions; // Array of functions in the file private: CMap<CString, LPCTSTR, WORD, WORD> ParseCmdsOP1; // Used internally to store control file commands }; ////////////////////////////////////////////////////////////////////// // CFuncDescFileArray Class ////////////////////////////////////////////////////////////////////// // This specifies a cluster of Func Definition Files as an array // of CFuncDescFile Objects. class CFuncDescFileArray : public CTypedPtrArray<CObArray, CFuncDescFile *> { public: CFuncDescFileArray(); virtual ~CFuncDescFileArray(); void FreeAll(); virtual int GetFuncCount(); virtual double CompareFunctions(FUNC_COMPARE_METHOD nMethod, int nFile1Ndx, int nFile1FuncNdx, int nFile2Ndx, int nFile2FuncNdx, BOOL bBuildEditScript); virtual CString DiffFunctions(FUNC_COMPARE_METHOD nMethod, int nFile1Ndx, int nFile1FuncNdx, int nFile2Ndx, int nFile2FuncNdx, DWORD nOutputOptions, double &nMatchPercent, CSymbolMap *pSymbolMap = NULL); virtual SetProgressCallback(LPFUNCANALPROGRESSCALLBACK pfnCallback, LPARAM lParam) { m_pfnProgressCallback = pfnCallback; m_lParamProgressCallback = lParam; } protected: LPFUNCANALPROGRESSCALLBACK m_pfnProgressCallback; LPARAM m_lParamProgressCallback; }; ////////////////////////////////////////////////////////////////////// // CSymbolMap Class ////////////////////////////////////////////////////////////////////// // This class stores mapping between two sets of functions by // hashing and storing address accesses and finding highest // hit matches. class CSymbolMap : public CObject { public: CSymbolMap(); virtual ~CSymbolMap(); void FreeAll(); BOOL IsEmpty(); void AddObjectMapping(CFuncObject &aLeftObject, CFuncObject &aRightObject); void GetLeftSideCodeSymbolList(CStringArray &anArray); // Returns sorted list of left-side code symbols void GetRightSideCodeSymbolList(CStringArray &anArray); // Returns sorted list of right-side code symbols void GetLeftSideDataSymbolList(CStringArray &anArray); // Returns sorted list of left-side data symbols void GetRightSideDataSymbolList(CStringArray &anArray); // Returns sorted list of right-side data symbols DWORD GetLeftSideCodeHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray); // Returns sorted array of target hit symbols and corresponding counts, function returns total hit count DWORD GetRightSideCodeHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray); // Returns sorted array of target hit symbols and corresponding counts, function returns total hit count DWORD GetLeftSideDataHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray); // Returns sorted array of target hit symbols and corresponding counts, function returns total hit count DWORD GetRightSideDataHitList(LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray); // Returns sorted array of target hit symbols and corresponding counts, function returns total hit count private: void GetSymbolList(CMap<CString, LPCTSTR, CStringArray*, CStringArray*> &mapSymbolArrays, CStringArray &anArray); DWORD GetHitList(CMap<CString, LPCTSTR, CStringArray*, CStringArray*> &mapSymbolArrays, LPCTSTR aSymbol, CStringArray &aSymbolArray, CDWordArray &aHitCountArray); // void SortStringArray(CStringArray &aStringArray); // void SortStringDWordArray(CStringArray &aStringArray, CDWordArray &aDWordArray); protected: void AddLeftSideCodeSymbol(LPCTSTR aLeftSymbol, LPCTSTR aRightSymbol); void AddRightSideCodeSymbol(LPCTSTR aRightSymbol, LPCTSTR aLeftSymbol); void AddLeftSideDataSymbol(LPCTSTR aLeftSymbol, LPCTSTR aRightSymbol); void AddRightSideDataSymbol(LPCTSTR aRightSymbol, LPCTSTR aLeftSymbol); CMap<CString, LPCTSTR, CStringArray*, CStringArray*> m_LeftSideCodeSymbols; CMap<CString, LPCTSTR, CStringArray*, CStringArray*> m_RightSideCodeSymbols; CMap<CString, LPCTSTR, CStringArray*, CStringArray*> m_LeftSideDataSymbols; CMap<CString, LPCTSTR, CStringArray*, CStringArray*> m_RightSideDataSymbols; }; #endif // !defined(AFX_FUNCDESC_H__E6CF1B55_6B17_4909_A17F_B572ED0ED0E6__INCLUDED_) <file_sep>/programs/funcanal/FuncView/SymbolMapTreeView.cpp // SymbolMapTreeView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: SymbolMapTreeView.cpp,v $ // Revision 1.1 2003/09/13 05:45:50 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "SymbolMapTreeView.h" #include "FuncViewPrjDoc.h" #include "../funcdesc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSymbolMapTreeView IMPLEMENT_DYNCREATE(CSymbolMapTreeView, CTreeView) CSymbolMapTreeView::CSymbolMapTreeView() { } CSymbolMapTreeView::~CSymbolMapTreeView() { } BEGIN_MESSAGE_MAP(CSymbolMapTreeView, CTreeView) //{{AFX_MSG_MAP(CSymbolMapTreeView) ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnSelchanged) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSymbolMapTreeView diagnostics #ifdef _DEBUG void CSymbolMapTreeView::AssertValid() const { CTreeView::AssertValid(); } void CSymbolMapTreeView::Dump(CDumpContext& dc) const { CTreeView::Dump(dc); } CFuncViewPrjDoc* CSymbolMapTreeView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSymbolMapTreeView message handlers void CSymbolMapTreeView::OnInitialUpdate() { CTreeCtrl &theTree = GetTreeCtrl(); theTree.ModifyStyle(0, TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_SHOWSELALWAYS, SWP_NOACTIVATE); // Call default which will call OnUpdate which will call FillSymbolMapList: CTreeView::OnInitialUpdate(); } void CSymbolMapTreeView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; switch (lHint) { case 0: // Normal Update FillSymbolMapList(); break; case SYMBOL_MAP_ALL: FillSymbolMapList(); break; case SYMBOL_MAP_LEFT_CODE: case SYMBOL_MAP_RIGHT_CODE: case SYMBOL_MAP_LEFT_DATA: case SYMBOL_MAP_RIGHT_DATA: break; } if ((lHint >= FILESET_TYPE_BASE) && (lHint <= FILESET_TYPE_LAST)) { // FILESET_TYPE_BASE+nFileSet = Document Fileset Function update (pHint = &CFuncViewFuncRef) } if ((lHint >= SYMBOL_MAP_TYPE_BASE) && (lHint <= SYMBOL_MAP_TYPE_LAST)) { // SYMBOL_MAP_TYPE_BASE+nSymbolMapType = Symbol Map update (pHint = &LPCTSTR) } } void CSymbolMapTreeView::FillSymbolMapList() { CTreeCtrl &theTree = GetTreeCtrl(); theTree.DeleteAllItems(); CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; HTREEITEM hLeftCode = theTree.InsertItem("Left-Side Code Symbols"); HTREEITEM hRightCode = theTree.InsertItem("Right-Side Code Symbols"); HTREEITEM hLeftData = theTree.InsertItem("Left-Side Data Symbols"); HTREEITEM hRightData = theTree.InsertItem("Right-Side Data Symbols"); if ((hLeftCode == NULL) || (hRightCode == NULL) || (hLeftData == NULL) || (hRightData == NULL)) return; theTree.SetItemData(hLeftCode, 1); theTree.SetItemData(hRightCode, 2); theTree.SetItemData(hLeftData, 3); theTree.SetItemData(hRightData, 4); CStringArray anArr; CSymbolMap &theSymbols = pDoc->GetSymbolMap(); anArr.RemoveAll(); theSymbols.GetLeftSideCodeSymbolList(anArr); FillSymbolMapSubList(hLeftCode, anArr, SYMBOL_MAP_LEFT_CODE); anArr.RemoveAll(); theSymbols.GetRightSideCodeSymbolList(anArr); FillSymbolMapSubList(hRightCode, anArr, SYMBOL_MAP_RIGHT_CODE); anArr.RemoveAll(); theSymbols.GetLeftSideDataSymbolList(anArr); FillSymbolMapSubList(hLeftData, anArr, SYMBOL_MAP_LEFT_DATA); anArr.RemoveAll(); theSymbols.GetRightSideDataSymbolList(anArr); FillSymbolMapSubList(hRightData, anArr, SYMBOL_MAP_RIGHT_DATA); } void CSymbolMapTreeView::FillSymbolMapSubList(HTREEITEM hParent, CStringArray &aSymbolList, DWORD nItemData) { int i; HTREEITEM hSymbol; CTreeCtrl &theTree = GetTreeCtrl(); for (i=0; i<aSymbolList.GetSize(); i++) { hSymbol = theTree.InsertItem(aSymbolList.GetAt(i), hParent); if (hSymbol == NULL) continue; theTree.SetItemData(hSymbol, nItemData); } theTree.Expand(hParent, TVE_EXPAND); } void CSymbolMapTreeView::OnSelchanged(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; *pResult = 0; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; CTreeCtrl &theTree = GetTreeCtrl(); HTREEITEM hSel = theTree.GetSelectedItem(); DWORD nSelType = 0; CString strSelSymbol; if (hSel) { nSelType = theTree.GetItemData(hSel); strSelSymbol = theTree.GetItemText(hSel); } if (nSelType >= SYMBOL_MAP_TYPE_BASE) { pDoc->UpdateAllViews(this, (LPARAM)nSelType, (!strSelSymbol.IsEmpty() ? (CObject*)LPCTSTR(strSelSymbol) : NULL)); } else { if (nSelType == 0) { pDoc->UpdateAllViews(this, (LPARAM)SYMBOL_MAP_ALL, NULL); } else { pDoc->UpdateAllViews(this, (LPARAM)(SYMBOL_MAP_TYPE_BASE + nSelType), NULL); } } } <file_sep>/programs/m6811dis/dfc.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* DFC -- DataFileConverter Class This is the C++ object definition for a Data File Converter Object. The Data File Converter object is an object that must be overriden by inherited classes to perform the task of reading and writing a data file. This class allows the flexibility of file independacy for file converter programs, disassemblers, etc. Author: <NAME> Date: January 29, 1997 Written in: Borland C++ 4.52 Updated: June 22, 1997 to work with both MS Visual C++ 4.0/5.0 as well as Borland C++. Description: Each Data File Converter is simply a Read function and a Write function, as defined here: */ #include <iostream> #include "dfc.h" #include "stringhelp.h" #include "memclass.h" #include "errmsgs.h" #include "bindfc.h" #include "inteldfc.h" #include "sfiledfc.h" ///////////////////////////////////////////////////////////////////////////// // CDFCObject Implementation CDFCObject::CDFCObject() { } CDFCObject::~CDFCObject() { } int CDFCObject::RetrieveFileMapping(std::istream * /*aFile*/, unsigned long NewBase, TMemRange *aRange) const { if (aRange) { aRange->PurgeRange(); aRange->SetStartAddr(NewBase); aRange->SetSize(0); } return(1); } ///////////////////////////////////////////////////////////////////////////// // CDFCArray Implementation CDFCArray *CDFCArray::instance() { static CDFCArray DFCs; return &DFCs; } CDFCArray::CDFCArray() : std::vector<CDFCObject *>() { static TDFC_Binary binDFC; static TDFC_Intel hexDFC; static TDFC_SFile motDFC; push_back(&binDFC); push_back(&hexDFC); push_back(&motDFC); } CDFCArray::~CDFCArray() { } const CDFCObject *CDFCArray::locateDFC(const std::string &strLibraryName) const { for (unsigned int ndx = 0; ndx < size(); ++ndx) { if (compareNoCase(strLibraryName, at(ndx)->GetLibraryName()) == 0) return at(ndx); } return NULL; } <file_sep>/programs/funcanal/FuncView/CompMatrixView.h // CompMatrixView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: CompMatrixView.h,v $ // Revision 1.1 2003/09/13 05:45:38 dewhisna // Initial Revision // // #if !defined(AFX_COMPMATRIXVIEW_H__ECF95B71_7B54_4A0D_95E0_C871FC74DD2F__INCLUDED_) #define AFX_COMPMATRIXVIEW_H__ECF95B71_7B54_4A0D_95E0_C871FC74DD2F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "GridCtrl.h" class CFuncViewPrjDoc; ///////////////////////////////////////////////////////////////////////////// // CCompMatrixView view class CCompMatrixView : public CView { protected: CCompMatrixView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CCompMatrixView) // Attributes public: CFuncViewPrjDoc* GetDocument(); protected: CGridCtrl *m_pGridCtrl; // Operations public: protected: void FillMatrixHeaders(); void FillMatrixData(int nSingleRow = -1, int nSingleCol = -1); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCompMatrixView) public: virtual void OnInitialUpdate(); virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo); protected: virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnDraw(CDC* pDC); //}}AFX_VIRTUAL // Implementation protected: virtual ~CCompMatrixView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(CCompMatrixView) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnSymbolsAdd(); afx_msg void OnUpdateSymbolsAdd(CCmdUI* pCmdUI); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in CompMatrixView.cpp inline CFuncViewPrjDoc* CCompMatrixView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_COMPMATRIXVIEW_H__ECF95B71_7B54_4A0D_95E0_C871FC74DD2F__INCLUDED_) <file_sep>/programs/m6811dis/errmsgs.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* * ERRMSGS * * This header file defines the acceptable "exception" messages for * errorcode handling. * * Author: <NAME> * Date: January 28, 1997 * * Rewrote on July 20, 1997 to handle better exception syntax. */ #ifndef ERRMSGS_H #define ERRMSGS_H #include <string> #define THROW_MEMORY_EXCEPTION_ERROR(code) \ { _OUT_OF_MEMORY_EXCEPTION.lcode = code; \ throw (&_OUT_OF_MEMORY_EXCEPTION); } #define THROW_EXCEPTION_ERROR(cause, code, name) \ { throw (new EXCEPTION_ERROR(1, cause, code, name)); } #define DELETE_EXCEPTION_ERROR(an_error) \ { if (an_error->delflag) \ delete an_error; } class EXCEPTION_ERROR { public: enum { ERR_NONE, ERR_OUT_OF_MEMORY, ERR_OUT_OF_RANGE, ERR_MAPPING_OVERLAP, ERR_OPENREAD, ERR_OPENWRITE, ERR_FILEEXISTS, ERR_CHECKSUM, ERR_UNEXPECTED_EOF, ERR_OVERFLOW, ERR_WRITEFAILED, ERR_READFAILED }; int delflag; // heap delete flag int cause; // Set to one of the above error codes by construction unsigned long lcode; // long extended code value, used for passing parameters std::string name_ex; // extended code name copied by constructor, useful for filenames, etc EXCEPTION_ERROR(); EXCEPTION_ERROR(EXCEPTION_ERROR& anException); EXCEPTION_ERROR(int adelflag, const int acause = EXCEPTION_ERROR::ERR_NONE, const unsigned long alcode = 0, const std::string &anexname = std::string()); }; extern EXCEPTION_ERROR _OUT_OF_MEMORY_EXCEPTION; // class ERR_OUT_OF_MEMORY {}; // class ERR_OUT_OF_RANGE {}; // class ERR_MAPPING_OVERLAP {}; // class ERR_OPENREAD { public: char *filename; }; // class ERR_OPENWRITE {public: char *filename; }; // class ERR_FILEEXISTS {}; // class ERR_CHECKSUM { public: int linenumber; }; // class ERR_UNEXPECTED_EOF {}; // class ERR_OVERFLOW {}; // class ERR_WRITEFAILED {}; #endif <file_sep>/programs/m6811dis/sfiledfc.cpp // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* SFileDFC This is the C++ Module that contains routines to read and write Motorola S-Files, by defining a new derived class DFC_SFILE from the base class DataFileConverter. This module makes use of the MEMCLASS type for memory interface. Author: <NAME> Date: February 10, 2000 Written in: MS Visual C++ 5.0 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include "sfiledfc.h" // Motorola format: // Sxccaa..aadd....kk // where: S is the record character "S" // x=record mode or type (See below) // cc=byte count after cc -- unlike Intel where the byte count is ONLY // the number of data bytes, this is the count of the // number of bytes in the address field, plus the number of // bytes in the data field, plus the 1 byte checksum // aa..aa=offset address -- Can be 2, 3, or 4 bytes depending on the 'x' type // dd....=data bytes // kk=checksum = 1's complement of the sum of all bytes in the record // starting with 'cc' through the last 'dd'... // Total sum (including checkbyte) should equal 0xFF // // Record mode/types: // 0 = Header character -- this is just a file signon that can contain // any desired data... GM PTP's, for example, use "HDR" in the // data field... The Address field is 2 bytes (4 characters) and // is usually 0000 except for Motorola DSP's where it indicates // the DSP Memory Space for the s-records that follow, where // 0001=X, 0002=Y, 0003=L, 0004=P, and 0005=E (DSP only!) // This field is optional // 1 = Data Record with a 2-byte address (aaaa = start address for data in this record) // 2 = Data Record with a 3-byte address (aaaaaa = start address for data in this record) // 3 = Data Record with a 4-byte address (aaaaaaaa = start address for data in this record) // 7 = EOF Record with a 4-byte address (aaaaaaaa = Executable start address for this s-file) // 8 = EOF Record with a 3-byte address (aaaaaa = Executable start address for this s-file) // 9 = EOF Record with a 2-byte address (aaaa = Executable start address for this s-file) // // Extensions: // S19 = 16-Bit addressing files (ones using S1 and S9 records) // S28 = 24-Bit addressing files (ones using S2 and S8 records) // S37 = 32-Bit addressing files (ones using S3 and S7 records) // // Intel format: // ccaaaammdd....kk // where: cc=byte count // aaaa=offset address // mm=mode byte // dd=date bytes (there are 'cc' many of 'dd' entries) // kk=checksum = sum of ALL hex pairs as bytes (including cc, aaaa, mm, and dd) // Sum (including checkbyte) should equal zero. // mm=00 -> normal line // mm=01 -> end of file // mm=02 -> SBA entry // RetrieveFileMapping: // // This function reads in an already opened text BINARY file pointed to by // 'aFile' and generates a TMemRange object that encapsulates the file's // contents, offsetted by 'NewBase' (allowing loading of different files // to different base addresses). // // Author: <NAME> // Date: June 28, 1997 int TDFC_SFile::RetrieveFileMapping(std::istream *aFile, unsigned long NewBase, TMemRange *aRange) const { int RetVal; try { RetVal = _ReadDataFile(aFile, NewBase, NULL, aRange, 0); } catch (EXCEPTION_ERROR*) { throw; } return RetVal; } // ReadDataFile: // // // Author: <NAME> // Date: January 29, 1997 int TDFC_SFile::ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc) const { int RetVal; try { RetVal = _ReadDataFile(aFile, NewBase, aMemory, NULL, aDesc); } catch (EXCEPTION_ERROR*) { throw; } return RetVal; } // _ReadDataFile: // // This function reads in an already opened text BINARY file pointed to by // 'aFile' into the MemObject pointed to by 'aMemory' offsetted by // 'NewBase' (allowing loading of different files to different base // address) and setting the corresponding Memory Descriptors to 'aDesc'... // // This function has been updated to a composite function that handles both // the reading of the file into memory and simply reading the Mapping. // This is a private function called by the regular ReadDataFile and // RetrieveFileMapping. If aMemory is null then memory is not filled. If // aRange is null, the mapping is not generated. If either or both is // non-null, then the corresponding operation is performed. // // Author: <NAME>isnant // Date: January 29, 1997 int TDFC_SFile::_ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, TMemRange *aRange, unsigned char aDesc) const { int RetVal; // Return Value int LineCount; // Line Counter char Buff[256]; // Line Buffer char *BufPtr; // Index into buffer unsigned int SBA; // Segment Base Address unsigned int NBytes; // Number of bytes supposed to be on line unsigned int OffsetAddr; // Offset Address read on line unsigned int i; // Loop counter unsigned int chksum; // Running Checksum unsigned long CurrAddr; // Current Memory Address unsigned int Mode; // Mode Byte unsigned int TempByte; // Hex to Decimal conversion storage int EndReached; // End reached Flag int FirstRange; // Flag for first range int NeedRangeUpdate; // Flag for needing to update the range capture int NeedToWriteRange; // Flag for needing to write the range unsigned long StartAddr; // Current StartAddr of the current Range unsigned long CurrSize; // Current Size of the current Range RetVal=1; SBA=0; LineCount=0; EndReached=0; aFile->seekg(0L, std::ios_base::beg); FirstRange = 1; NeedToWriteRange = 0; NeedRangeUpdate = 1; // Force the first update StartAddr = 0; CurrAddr = 0; CurrSize = 0; if (aRange!=NULL) { // Initialize the range and setup incase there are no real bytes aRange->PurgeRange(); aRange->SetStartAddr(0); aRange->SetSize(0); } while ((!aFile->eof()) && (aFile->peek() != EOF) && (!EndReached)) { aFile->getline(Buff, sizeof(Buff)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_UNEXPECTED_EOF, 0, ""); LineCount++; if (Buff[0]==':') { sscanf(&Buff[1], "%2X%4X%2X", &NBytes, &OffsetAddr, &Mode); chksum=NBytes+(OffsetAddr/256)+(OffsetAddr%256)+Mode; if (CurrAddr!=((((unsigned long)SBA)*16)+(unsigned long)OffsetAddr+NewBase)) NeedRangeUpdate=1; if (NeedRangeUpdate) { // If we need to update the Range do so, else only update the StartAddr if (NeedToWriteRange) { // If this is not the first range, add a range if ((aRange!=NULL) && (!FirstRange)) { try { aRange->AddRange(StartAddr, CurrSize); } catch (EXCEPTION_ERROR*) { throw; } } // Else, set the first range if ((aRange!=NULL) && (FirstRange)) { aRange->SetStartAddr(StartAddr); aRange->SetSize(CurrSize); FirstRange = 0; } // Signify we don't need to write it, since we just did NeedToWriteRange = 0; } // Set start of next range, and initialize variables StartAddr = (((unsigned long)SBA)*16)+(unsigned long)OffsetAddr+NewBase; CurrAddr = StartAddr; CurrSize = 0; NeedRangeUpdate=0; } BufPtr=&Buff[9]; switch (Mode) { case 0: for (i=0; i<NBytes; ++i) { sscanf(BufPtr, "%2X", &TempByte); chksum+=TempByte; if (aMemory) { if (!aMemory->SetByte(CurrAddr, (unsigned char)TempByte)) { THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_OVERFLOW, 0, ""); } if (aMemory->GetDescriptor(CurrAddr)!=0) RetVal=0; aMemory->SetDescriptor(CurrAddr, aDesc); } CurrAddr++; CurrSize++; BufPtr+=2; // Any time we add a byte, make sure the range gets updated NeedToWriteRange = 1; } break; case 1: EndReached=1; break; case 2: sscanf(BufPtr, "%4X", &SBA); chksum+=(SBA/256)+(SBA%256); BufPtr+=4; break; } sscanf(BufPtr, "%2X", &TempByte); chksum+=TempByte; if ((chksum%256)!=0) { THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_CHECKSUM, LineCount, ""); } } } // Make a final test to see if the range needs to be saved, // This is necessary to save the last range operated upon // in case a pre-mature EOF is encountered. if (NeedToWriteRange) { // If this is not the first range, add a range if ((aRange!=NULL) && (!FirstRange)) { try { aRange->AddRange(StartAddr, CurrSize); } catch (EXCEPTION_ERROR*) { throw; } } // Else, set the first range if ((aRange!=NULL) && (FirstRange)) { aRange->SetStartAddr(StartAddr); aRange->SetSize(CurrSize); FirstRange = 0; } } if (((aFile->eof()) || (aFile->peek() == EOF)) && (!EndReached)) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_UNEXPECTED_EOF, 0, ""); return(RetVal); } // WriteDataFile: // // This function writes to an already opened text BINARY file pointed to by // 'aFile' from the MemObject pointed to by 'aMemory' and whose Descriptor // has a match specified by 'aDesc'. Matching is done by 'anding' the // aDesc value with the descriptor in memory. If the result is non-zero, // the location is written. Unless, aDesc=0, in which case ALL locations // are written regardless of the actual descriptor. If the aDesc validator // computes out as false, then the data is filled according to the FillMode. // // Author: <NAME> // Date: January 29, 1997 int TDFC_SFile::WriteDataFile(std::ostream *aFile, TMemRange *aRange, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc, int UsePhysicalAddr, unsigned int FillMode) const { TMemRange *CurrRange; // Range Spanning variable int RetVal; // Return Value int LineCount; // Line Counter char TempStr[10]; // Temporary Conversion String char Buff[256]; // Line Buffer unsigned int SBA; // Segment Base Address unsigned int NBytes; // Number of bytes supposed to be on line unsigned int OffsetAddr = 0; // Offset Address read on line unsigned int i; // Loop counter unsigned int chksum; // Running Checksum unsigned long BytesLeft; // Remaining number of bytes to check/write unsigned long CurrAddr; // Current Logical Memory Address unsigned long RealAddr = 0; // Current Written Address equivalent unsigned int LowestOffset; // Lowest Load offset for the file unsigned int LowestFound; // Flag for finding lowest offset unsigned int TempByte; // Temp byte used for calculation int NeedNewOffset; // Flag for needing to write a new offset char WriteBuff[256]; // Used for printing to the output stream int NoFill; // Flag for no-byte and no-fill srand( (unsigned)time( NULL ) ); CurrRange=aRange; RetVal=1; SBA=0; LineCount=0; LowestOffset=0x0000; LowestFound=0; while (CurrRange!=NULL) { CurrAddr=CurrRange->GetStartAddr(); BytesLeft=CurrRange->GetSize(); while (BytesLeft) { strcpy(Buff, ""); NBytes=0; chksum=0; NeedNewOffset=1; while ((BytesLeft) && (NeedNewOffset)) { // Find first location to write next if ((aDesc==0) || (aDesc & aMemory->GetDescriptor(CurrAddr)) || ((FillMode!=DFC_FILL_TYPE(NO_FILL)) && (FillMode!=DFC_FILL_TYPE(CONDITIONAL_FILL_WITH)) && (FillMode!=DFC_FILL_TYPE(CONDITIONAL_FILL_WITH_RANDOM)))) { if (UsePhysicalAddr) { RealAddr=aMemory->GetPhysicalAddr(CurrAddr)+NewBase; } else { RealAddr=CurrAddr+NewBase; } OffsetAddr=(unsigned int)(RealAddr&0xFFFF); if (!LowestFound) { LowestOffset=OffsetAddr; LowestFound=1; } if (((RealAddr/65536UL)*0x1000UL)!=SBA) { SBA=(unsigned int)((RealAddr/65536UL)*0x1000UL); if (((RealAddr/65536UL)*0x1000UL)!=(unsigned long)(SBA)) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_OVERFLOW, 0, ""); TempByte=(256-(((SBA/256)+(SBA%256)+4)%256))%256; sprintf(WriteBuff, ":02000002%04X%02X\r\n", SBA, TempByte); aFile->write(WriteBuff, strlen(WriteBuff)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0 ,""); LineCount++; } NeedNewOffset=0; } else { BytesLeft--; CurrAddr++; } } for (i=0; ((i<32) && (!NeedNewOffset) && (BytesLeft)); ++i) { if ((aDesc==0) || (aDesc & aMemory->GetDescriptor(CurrAddr))) { TempByte=aMemory->GetByte(CurrAddr); NoFill=0; // Fill, cause we have a byte } else { NoFill=0; // Default to Fill switch GET_DFC_FILL_TYPE(FillMode) { case DFC_FILL_TYPE(ALWAYS_FILL_WITH): TempByte=GET_DFC_FILL_BYTE(FillMode); break; case DFC_FILL_TYPE(ALWAYS_FILL_WITH_RANDOM): TempByte=(unsigned char)(rand()%256); break; default: TempByte=0x00; NoFill=1; // No-Fill break; } } if (!NoFill) { // If we have a byte, use it sprintf(TempStr, "%02X", TempByte); strcat(Buff, TempStr); chksum+=TempByte; NBytes++; } BytesLeft--; CurrAddr++; RealAddr++; if ((aDesc==0) || (aDesc & aMemory->GetDescriptor(CurrAddr)) || ((FillMode!=DFC_FILL_TYPE(NO_FILL)) && (FillMode!=DFC_FILL_TYPE(CONDITIONAL_FILL_WITH)) && (FillMode!=DFC_FILL_TYPE(CONDITIONAL_FILL_WITH_RANDOM)))) { if (UsePhysicalAddr) { if (RealAddr!=(aMemory->GetPhysicalAddr(CurrAddr)+NewBase)) { NeedNewOffset=1; } } if (((RealAddr/65536UL)*0x1000UL)!=SBA) { NeedNewOffset=1; } else { if ((RealAddr&0xFFFF)==0) NeedNewOffset=1; } } else { NeedNewOffset=1; } } if (NBytes!=0) { chksum+=NBytes; chksum+=(OffsetAddr/256)+(OffsetAddr%256); chksum=(256-(chksum%256))%256; sprintf(WriteBuff, ":%02X%04X00%s%02X\r\n", NBytes, OffsetAddr, Buff, chksum); aFile->write(WriteBuff, strlen(WriteBuff)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0 ,""); LineCount++; } } CurrRange=CurrRange->GetNext(); } TempByte=(256-(((LowestOffset/256)+(LowestOffset%256)+1)%256))%256; sprintf(WriteBuff, ":00%04X01%02X\r\n", LowestOffset, TempByte); aFile->write(WriteBuff, strlen(WriteBuff)); if (!aFile->good()) THROW_EXCEPTION_ERROR(EXCEPTION_ERROR::ERR_WRITEFAILED, 0 ,""); return(RetVal); } <file_sep>/programs/m6811dis/sfiledfc.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // /* SFileDFC -- Motorola S-File DataFileConverter Class This is the C++ Motorola S-File DataFileConverter Object Class Header File. It is a child of the DFC Object class. Author: <NAME> Date: February 10, 2000 Written in: MS Visual C++ 5.0 */ #ifndef SFILEDFC_H #define SFILEDFC_H #include <iostream> #include "dfc.h" #include "memclass.h" #include "errmsgs.h" class TDFC_SFile : virtual public CDFCObject { public: virtual std::string GetLibraryName(void) const { return "motorola"; } virtual std::string GetShortDescription(void) const { return "Motorola Hex Data File Converter"; } virtual std::string GetDescription(void) const { return "Motorola Hex Data File Converter"; } const char *DefaultExtension(void) const { return "s19"; /* Could use "mot" */ } int RetrieveFileMapping(std::istream *aFile, unsigned long NewBase, TMemRange *aRange) const; int ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc) const; int WriteDataFile(std::ostream *aFile, TMemRange *aRange, unsigned long NewBase, TMemObject *aMemory, unsigned char aDesc, int UsePhysicalAddr, unsigned int FillMode) const; private: int _ReadDataFile(std::istream *aFile, unsigned long NewBase, TMemObject *aMemory, TMemRange *aRange, unsigned char aDesc) const; }; #endif // SFILEDFC_H <file_sep>/programs/funcanal/FuncView/ChildFrm5.cpp // ChildFrm5.cpp : implementation file // // Frame Window for the CompMatrix Views // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm5.cpp,v $ // Revision 1.1 2003/09/13 05:45:35 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ChildFrm5.h" #include "CompMatrixView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrame5 IMPLEMENT_DYNCREATE(CChildFrame5, CChildFrameBase) CChildFrame5::CChildFrame5() { } CChildFrame5::~CChildFrame5() { } BEGIN_MESSAGE_MAP(CChildFrame5, CChildFrameBase) //{{AFX_MSG_MAP(CChildFrame5) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame5 message handlers BOOL CChildFrame5::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { ASSERT(pContext != NULL); pContext->m_pNewViewClass = RUNTIME_CLASS(CCompMatrixView); if (CreateView(pContext, AFX_IDW_PANE_FIRST) == NULL) return FALSE; return TRUE; // return CChildFrameBase::OnCreateClient(lpcs, pContext); } <file_sep>/programs/m6811dis/gdc.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // // // Header for GDC -- Generic Disassembly Class // #ifndef _GDC_H_ #define _GDC_H_ #include "memclass.h" #include <time.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> // ============================================================================ class ifstreamControlFile : public std::ifstream { public: ifstreamControlFile(const std::string &strFilename) : std::ifstream(), m_strFilename(strFilename) { open(strFilename.c_str(), std::ios_base::in); } std::string getFilename() const { return m_strFilename; } private: std::string m_strFilename; }; // ============================================================================ typedef std::vector<std::string> TStringArray; typedef std::vector<unsigned char> TByteArray; typedef std::vector<unsigned int> TWordArray; typedef std::vector<unsigned int> TDWordArray; typedef std::map<unsigned int, unsigned int> TAddressMap; typedef std::map<unsigned int, TDWordArray> TAddressTableMap; typedef std::map<unsigned int, TStringArray> TLabelTableMap; typedef std::map<unsigned int, std::string> TAddressLabelMap; // The following macro provides an easy method for GetFieldWidth to round field widths to the next tab-stop to prevent tab/space mixture #define CALC_FIELD_WIDTH(n) (((m_nTabWidth != 0) && (m_bTabsFlag)) ? ((n/m_nTabWidth)+(((n%m_nTabWidth)!=0) ? 1 : 0))*m_nTabWidth : n) // Forward declarations class COpcodeEntry; class COpcodeArray; class COpcodeTable; class CDisassembler; // The following bit-mask definitions define the bits in the m_Control field // of each COpcodeEntry object that are processor independent and must be // properly used in each opcode defined by all overrides (GDC's). This is // because these are used to control the overall disassembly operation. // All other bit-fields in m_Control can be defined and used as needed by // each override. You will notice that the bit-fields in these definitions // start on the upper-bit of the upper-byte in the 32-bit m_Control DWord. // It is recommended that processor specific additions are made starting // at the other end -- that is the lower-bit of the lower-byte... This // will allow the insertion of additional processor independent bits at the // top of the DWord in future updates and releases without necessarily // running into and conflicting with those defined by overrides. It is // futher suggested that the entire upper-word be reserved for processor // independent functions and the entire lower-word be reserved for // dependent functions. Also note that the usage need not be bit-by-bit // only, but can be numerical values occupying certain bit positions -- with // proper "and/or" masks and bit-shifting these can easily be converted to/from // bit-field equivalents. (Names use OCTL_xxxx form) #define OCTL_STOP 0x80000000ul // Discontinue Disassembly - Upper-bit = 1 // Currently, all m_Group entries are used exclusively by processor // dependent functions. But, it too should follow the guidelines above // so that in the future, if the group field is needed by the processor // independent functions, then they can be added in without changing // anything. (Names use OGRP_xxxx form) // COpcodeEntry // This specifies exactly one opcode for the target processor. class COpcodeEntry { public: COpcodeEntry(); COpcodeEntry(int nNumBytes, unsigned char *Bytes, unsigned int nGroup, unsigned int nControl, const std::string & szMnemonic, unsigned int nUserData = 0); COpcodeEntry(const COpcodeEntry& aEntry); virtual void CopyFrom(const COpcodeEntry& aEntry); TWordArray m_OpcodeBytes; // Array of opcodes for this entry unsigned int m_Group; // Group declaration unsigned int m_Control; // Flow control unsigned int m_UserData; // User defined addition data storage std::string m_Mnemonic; // Printed mnemonic virtual COpcodeEntry &operator=(const COpcodeEntry& aEntry); }; // COpcodeArray // This specifies an array of opcodes that have the SAME initial // byte. This class is exclusively a friend of COpcodeTable. // COpcodeTable controls the sorting and creating of these // arrays. When new opcodes are added, COpcodeTable will properly // create and sort (via hash maps) these arrays... class COpcodeArray : public std::vector<COpcodeEntry> { public: COpcodeArray(); virtual ~COpcodeArray(); }; // COpcodeTable // This function manages a single table of opcodes by properly // adding and maintaining opcode array's. This class is a // mapping of initial opcode bytes to an array of COpcodeArray. // When adding a new opcode, this function first checks to // see if an array exists, if not it creates it - then it adds // the opcode to the array. It also provides a "lookup" // function of "FindFirst" and "FindNext"... These work sort // of like the traditional GetFirstPosition and GetNextAssoc // routines, but here they find the "First" and "Next" opcodes // that have a SPECIFIC byte. The "First" function simply // returns the initial index position in the array +1 (0 = NOT Found) // The "Next" function updates the position and sets the // specified COpcodeEntry to the opcode entry value. Note that // since arrays are used, the First/Next operation returns back // the opcodes for a common byte in the SAME order they were // added. Currently, there is only an "Add" function and no remove! // It is also the users responsibility to not add duplicate or // conflicting opcodes! class COpcodeTable : public std::map<unsigned char, COpcodeArray> { public: COpcodeTable(); virtual ~COpcodeTable(); virtual void AddOpcode(const COpcodeEntry& nOpcode); }; // CDisassembler // This class describes a generic disassembler class to handle disassembly. // It contains no processor dependent information, therefore this class // must be overriden to handle processor dependent operations. It is also // setup to use the DFC converters and memory objects so that these // functions are not dependent on input file types. // // In the override, the constructor and destructor must be // defined to setup opcodes and memory for the target processor! // // The function "ReadControlFile" takes an already open CFile // object and reads in the control file. The base function calls the // function 'ParseControlLine' for every line in the input file (comment // lines are automatically removed). The override (if any) should // return TRUE if all is OK with the line being processed, otherwise, // it should set the m_ParseError with an error message and return FALSE. // The default message, if not set, for m_ParseError is "*** Error: Unknown error in line xxx". // The ReadControlFile routine will automatically output the control // file line number information for each m_ParseError message. // If default functionality is desired for the line, then the override // should call the CDisassembler::ParseControlLine function -- that way, // for the normally accepted options, the override doesn't have to worry // about processing them. Plus, it gives the override a chance to create // new behavior for each command. // // When branches are encountered, they are added to the m_BranchTable // map -- m_BranchTable is a map of arrays -- each array is a DWORD array that // contains every address that referenced the branch. So, when a new branch is // found, the array is created -- when a branch is re-encountered, the address // that referenced the branch is added... This is NEW to this disassembler from // the original! -- the original used only a simple table of branch addresses. // // NOTE: Code references are added to the m_BranchTable arrays and data references // are added to the m_LabelRefTable arrays!! This way, not only can we track // who referenced a particular address, but we can track how it was referenced. // All overrides should conform to this by making sure they add references to the // right place. AddBranch function handles code references and AddLabel handles // data references. When adding labels to code, add the reference using either // AddBranch and then call AddLabel without the refernece or just call // GenAddrLabel (which calls both AddBranch and AddLabel correctly). When adding // data references, use either AddLabel or call GenDataLabel (GenDataLabel also // handles outputting of generated labels). // class CDisassembler { public: // The following define the function identification flags: enum FUNC_FLAGS { // Entries <128 = Stops: FUNCF_HARDSTOP = 0, // Hard Stop = RTS or RTI encountered FUNCF_EXITBRANCH = 1, // Exit Branch = Branch to a specified exit address FUNCF_BRANCHOUT = 2, // Execution branched out (JMP, BRA, etc) FUNCF_SOFTSTOP = 3, // Soft Stop = Code execution flowed into another function definition // Entries >=128 = Starts: FUNCF_ENTRY = 128, // Entry Point Start FUNCF_INDIRECT = 129, // Indirect Code Entry Point Start FUNCF_CALL = 130, // Call Start Point (JSR, BSR, etc) FUNCF_BRANCHIN = 131 }; // Entry from a branch into (BEQ, BNE, etc) // The following define the memory descriptors for the disassembler memory. // 0 = The memory is unused/not-loaded // 10 = The memory is loaded, but hasn't been processed // 20 = The memory is loaded, has been processed, and found to be data, but not printable ASCII data // 21 = The memory is loaded, has been processed, and found to be printable ASCII data // 30 = The memory is loaded, has been processed, and is an indirect vector to Code // 31 = The memory is loaded, has been processed, and is an indirect vector to Data // 40 = The memory is loaded, has been processed, and found to be code // 41 = The memory is loaded, has been processed, and should be code, but was determined to be an illegal opcode // NOTE: These should not be changed -- enough room has been allowed for future expansion! enum MEM_DESC { DMEM_NOTLOADED = 0, DMEM_LOADED = 10, DMEM_DATA = 20, DMEM_PRINTDATA = 21, DMEM_CODEINDIRECT = 30, DMEM_DATAINDIRECT = 31, DMEM_CODE = 40, DMEM_ILLEGALCODE = 41 }; // The following define field positions for obtaining field widths from overrides. // Additional entries can be added on overrides, but this order should NOT change // in order to maintain backward compatibility at all times: #define NUM_FIELD_CODES 6 enum FIELD_CODE { FC_ADDRESS, FC_OPBYTES, FC_LABEL, FC_MNEMONIC, FC_OPERANDS, FC_COMMENT }; // The following define mnemonic codes for use with the FormatMnemonic pure virtual // function. These are used to specify the retrieving of "special mnemonics" for // things such as equates, data bytes, ascii text, etc. Additional entries can be // added on overrides, but this order should NOT change in order to maintain backward // compatibility at all times: enum MNEMONIC_CODE { MC_OPCODE, MC_ILLOP, MC_EQUATE, MC_DATABYTE, MC_ASCII, MC_INDIRECT }; // The following defines the label types when formating output. The are flags that // determine where the label is being referenced. It is used by the FormatLabel // function to determine what type of delimiter to add, if any. This enum can be // added to in overrides, but the existing entries should not be changed: enum LABEL_CODE { LC_EQUATE, LC_DATA, LC_CODE, LC_REF }; public: CDisassembler(); virtual ~CDisassembler(); virtual unsigned int GetVersionNumber(void); // Base function returns GDC version is most-significant word. Overrides should call this parent to get the GDC version and then set the least-significant word with the specific disassembler version. virtual std::string GetGDCLongName(void) = 0; // Pure virtual. Defines the long name for this disassembler virtual std::string GetGDCShortName(void) = 0; // Pure virtual. Defines the short name for this disassembler virtual bool ReadControlFile(ifstreamControlFile& inFile, bool bLastFile = true, std::ostream *msgFile = NULL, std::ostream *errFile = NULL, int nStartLineCount = 0); // Read already open control file 'infile', outputs messages to 'msgFile' and errors to 'errFile', nStartLineCount = initial m_nCtrlLine value virtual bool ParseControlLine(const std::string & szLine, TStringArray& argv, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Parses a line from the control file -- szLine is full line, argv is array of whitespace delimited args. Should return false ONLY if ReadControlFile should print the ParseError string to errFile with line info virtual bool ReadSourceFile(const std::string & szFilename, unsigned int nLoadAddress, const std::string & szDFCLibrary, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Reads source file named szFilename using DFC szDFCLibrary virtual bool ScanEntries(std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Scans through the entry list looking for code virtual bool ScanBranches(std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Scans through the branch lists looking for code virtual bool ScanData(const std::string & szExcludeChars, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Scans through the data that remains and tags it as printable or non-printable virtual bool Disassemble(std::ostream *msgFile = NULL, std::ostream *errFile = NULL, std::ostream *outFile = NULL); // Disassembles entire loaded memory and outputs info to outFile if non-NULL or opens and writes the file specified by m_sOutputFilename -- calls Pass1 and Pass2 to perform this processing virtual bool Pass1(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Performs Pass1 which finds code and data -- i.e. calls Scan functions virtual bool Pass2(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Performs Pass2 which is the actual disassemble stage virtual bool Pass3(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Performs Pass3 which creates the function output file virtual bool FindCode(std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Iterates through memory using m_PC finding and marking code. It should add branches and labels as necessary and return when it hits an end-of-code or runs into other code found virtual bool ReadNextObj(bool bTagMemory, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Procedure to read next object code from memory. The memory type is flagged as code (or illegal code). Returns True if current code legal, else False. OpMemory = object code from memory. CurrentOpcode = Copy of COpcodeEntry for the opcode located. PC is automatically advanced. virtual bool CompleteObjRead(bool bAddLabels = true, std::ostream *msgFile = NULL, std::ostream *errFile = NULL) = 0; // Pure Virtual that finishes the opcode reading process as is dependent on processor. It should increment m_PC and add bytes to m_OpMemory, but it should NOT flag memory descriptors! If the result produces an invalid opcode, the routine should return FALSE. The ReadNextObj func will tag the memory bytes based off of m_OpMemory! If bAddLabels = FALSE, then labels and branches aren't added -- disassemble only! virtual bool RetrieveIndirect(std::ostream *msgFile = NULL, std::ostream *errFile = NULL) = 0; // Pure Virtual. Retrieves the indirect address specified by m_PC and places it m_OpMemory for later formatting. It is a pure virtual because of length and indian notation differences virtual std::string FormatMnemonic(MNEMONIC_CODE nMCCode) = 0; // Pure Virtual. This function should provide the specified mnemonic. For normal opcodes, MC_OPCODE is used -- for which the override should return the mnemonic in the opcode table. This is done to provide the assembler/processor dependent module opportunity to change/set the case of the mnemonic and to provide special opcodes. virtual std::string FormatOperands(MNEMONIC_CODE nMCCode) = 0; // Pure Virtual. This function should create the operands for the current opcode if MC_OPCODE is issued. For others, it should format the data in m_OpMemory to the specified form! virtual std::string FormatComments(MNEMONIC_CODE nMCCode); // This function should create any needed comments for the disassembly output for the current opcode or other special MC_OPCODE function. This is where "undetermined branches" and "out of source branches" can get flagged by the specific disassembler. The built in function calls FormatReferences and creates the references in the comments. Overrides wishing to perform the same functionallity, should also call FormatReferences. virtual std::string FormatAddress(unsigned int nAddress); // This function creates the address field of the disassembly output. Default is "xxxx" hex value. Override for other formats. virtual std::string FormatOpBytes(void); // This function creates a opcode byte string from the bytes in m_OpMemory. If another format is desired, override it virtual std::string FormatLabel(LABEL_CODE nLC, const std::string & szLabel, unsigned int nAddress); // This function modifies the specified label to be in the Lxxxx format for the nAddress if szLabel is null. If szLabel is non-null no changes are made. This function should be overridden to add the correct suffix delimiters as needed! virtual std::string FormatReferences(unsigned int nAddress); // Makes a string to place in the comment field that contains all references for the specified address virtual int GetFieldWidth(FIELD_CODE nFC); // Defines the widths of each output field. Can be overridden to alter output formatting. To eliminate space/tab mixing, these should typically be a multiple of the tab width virtual std::string MakeOutputLine(TStringArray& saOutputData); // Formats the data in saOutputData, which should have indicies corresponding to FIELD_CODE enum, to a string that can be sent to the output file virtual void ClearOutputLine(TStringArray& saOutputData); virtual bool WriteHeader(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes the disassembly header comments to the output file. Override in subclasses for non-default header virtual bool WritePreEquates(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed in the disassembly file prior to the equates section. Default is do nothing. Override as needed virtual bool WriteEquates(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes the equates table to the disassembly file. virtual bool WritePostEquates(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed in the disassembly file after the equates section. Default is do nothing. Override as needed virtual bool WritePreDisassembly(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed in the disassembly file prior to the main disassembly section. Default writes several blank lines. Override as needed virtual bool WriteDisassembly(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes the disassembly to the output file. Default iterates through memory and calls correct functions. Override as needed. virtual bool WritePostDisassembly(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed in the disassembly file after the main disassembly section, such as ".end". Default is do nothing. Override as needed virtual bool WritePreSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed in the disassembly file prior to a new section. That is, a section that is loaded and analyzed. A part of memory containing "not_loaded" areas would cause a new section to be generated. This should be things like "org", etc. virtual bool WriteSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes the current section to the disassembly file. Override as needed. virtual bool WritePostSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed in the disassembly file after a new section. Default is do nothing, override as needed. virtual bool WritePreDataSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed prior to a data section -- that is a section that contains only DMEM_DATA directives. This would be things like "DSEG", etc. Default is do nothing. Override as needed. virtual bool WriteDataSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes a data section. virtual bool WritePostDataSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed after a data section. Default is do nothing. Typically this would be something like "ends" virtual bool WritePreCodeSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed prior to a code section -- such as "CSEG", etc. Default is do nothing. Override as needed. virtual bool WriteCodeSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes a code section. virtual bool WritePostCodeSection(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed after a code section. Default is do nothing. Typically this would be something like "ends" virtual bool WritePreFunction(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed prior to a new function -- such as "proc". The default simply writes a separator line "===". Override as needed virtual bool WriteIntraFunctionSep(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes a function's intra code separation. The default simply writes a separator line "---". Override as needed virtual bool WritePostFunction(std::ostream& outFile, std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Writes any info needed after a function -- such as "endp". The default simply writes a separator line "===". Override as needed virtual bool ValidateLabelName(const std::string & aName); // Parses a specified label to make sure it meets label rules virtual bool ResolveIndirect(unsigned int nAddress, unsigned int& nResAddress, int nType) = 0; // Pure Virtual that Resolves the indirect address specified by nAddress of type nType where nType = 0 for Code locations and 1 for Data locations. It returns the resolved address in nResAddress and T/F for mem load status virtual bool IsAddressLoaded(unsigned int nAddress, int nSize); // Checks to see if the nSize bytes starting at address nAddress are loaded. True only if all the bytes are loaded! virtual bool AddLabel(unsigned int nAddress, bool bAddRef = false, unsigned int nRefAddress = 0, const std::string & szLabel = std::string()); // Sets szLabel string as the label for nAddress. If nAddress is already set with that string, returns FALSE else returns TRUE or all OK. If address has a label and szLabel = NULL or zero length, nothing is added! If szLabel is NULL or zero length, a null string is added to later get resolved to Lxxxx form. If bAddRef, then nRefAddress is added to the reference list virtual bool AddBranch(unsigned int nAddress, bool bAddRef = false, unsigned int nRefAddress = 0); // Adds nAddress to the branch table with nRefAddress as the referring address. Returns T if all ok, F if branch address is outside of loaded space. If nAddRef is false, a branch is added without a reference virtual void GenDataLabel(unsigned int nAddress, unsigned int nRefAddress, const std::string & szLabel = std::string(), std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Calls AddLabel to create a label for nAddress -- unlike calling direct, this function outputs the new label to msgFile if specified... virtual void GenAddrLabel(unsigned int nAddress, unsigned int nRefAddress, const std::string & szLabel = std::string(), std::ostream *msgFile = NULL, std::ostream *errFile = NULL); // Calls AddLabel to create a label for nAddress, then calls AddBranch to add a branch address -- unlike calling direct, this function outputs the new label to msgFile if specified and displays "out of source" errors for the branches to errFile... virtual void OutputGenLabel(unsigned int nAddress, std::ostream *msgFile); // Outputs a generated label to the msgFile -- called by GenAddrLabel and GenDataLabel virtual std::string GenLabel(unsigned int nAddress); // Creates a default generated label. Base form is Lxxxx, but can be overridden in derived classes for other formats virtual std::string GetExcludedPrintChars(void) = 0; // Pure Virtual. Returns a list of characters excluded during datascan for printable scan virtual std::string GetHexDelim(void) = 0; // Pure Virtual. Returns hexadecimal delimiter for specific assembler. Typically "0x" or "$" virtual std::string GetCommentStartDelim(void) = 0; // Pure Virtual. Returns start of comment delimiter string virtual std::string GetCommentEndDelim(void) = 0; // Pure Virtual. Returns end of comment delimiter string // Output Flags and Control Values: bool m_bAddrFlag; // CmdFileToggle, TRUE = Write addresses on disassembly bool m_bOpcodeFlag; // CmdFileToggle, TRUE = Write opcode listing as comment in disassembly file bool m_bAsciiFlag; // CmdFileToggle, TRUE = Convert printable data to ASCII strings bool m_bSpitFlag; // CmdFileToggle, Code-Seeking/Code-Dump Mode, TRUE = Code-Dump, FALSE = Code-Seek bool m_bTabsFlag; // CmdFileToggle, TRUE = Use tabs in output file. Default is TRUE. bool m_bAsciiBytesFlag; // CmdFileToggle, TRUE = Outputs byte values of ASCII text as comment prior to ascii line (default) FALSE = ASCII line only bool m_bDataOpBytesFlag; // CmdFileToggle, TRUE = Outputs byte values for data fields in OpBytes field for both printable and non-printable data, FALSE = no opbytes -- Default is FALSE int m_nMaxNonPrint; // CmdFile Value, Maximum number of non-printable characters per line int m_nMaxPrint; // CmdFile Value, Maximum number of printable characters per line int m_nBase; // CmdFile Value, Default number base for control file input int m_nTabWidth; // CmdFile Value, Width of tabs for output, default is 4 std::string m_sDefaultDFC; // CmdFile Value, Default DFC Library -- used with single input file and on multi-file when not specified unsigned int m_nLoadAddress; // CmdFile Value, Load address for input file -- used only with single input file! std::string m_sInputFilename; // CmdFile Value, Filename for the input file -- used only with single input file! std::string m_sOutputFilename; // CmdFile Value, Filename for the disassembly output file std::string m_sFunctionsFilename; // CmdFile Value, Filename for the function output file TStringArray m_sControlFileList; // This list is appended with each control file read. The only purpose for this list is for generating comments in the output file TStringArray m_sInputFileList; // This list is appended with each source file read (even with the single input name). The only purpose for this list is for generating comments in the output file std::string m_sFunctionalOpcode; // Functions File export opcode. Cleared by ReadNextObj and set by CompleteObjRead. time_t m_StartTime; // Set to system time at instantiated protected: int m_nCtrlLine; // Line Count while processing control file int m_nFilesLoaded; // Count of number of files successfully loaded by the control file COpcodeTable m_Opcodes; // Table of opcodes for this disassembler std::string m_ParseError; // Set during the control file parsing to indicate error messages TAddressMap m_EntryTable; // Table of Entry values (start addresses) from control file TAddressMap m_FunctionsTable; // Table of start-of and end-of functions TAddressMap m_FuncExitAddresses; // Table of address that are equivalent to function exit like RTS or RTI. Any JMP or BRA or execution into one of these addresses will equate to a function exit TAddressTableMap m_BranchTable; // Table mapping branch addresses encountered with the address that referenced it in disassembly. TLabelTableMap m_LabelTable; // Table of labels both specified by the user and from disassembly. Entry is pointer to array of labels. A null entry equates back to Lxxxx. First entry is default for "Get" function. TAddressTableMap m_LabelRefTable; // Table of reference addresses for labels. User specified labels have no reference added. TAddressLabelMap m_CodeIndirectTable; // Table of indirect code vectors with labels specified by the user and from disassembly TAddressLabelMap m_DataIndirectTable; // Table of indirect data vectors with labels specified by the user and from disassembly TMemObject *m_Memory; // Memory object for the processor. Any overrides must define allocate/deallocate this appropriately unsigned int m_PC; // Program counter TByteArray m_OpMemory; // Array to hold the opcode currently being processed COpcodeEntry m_CurrentOpcode; // Copy of COpcodeEntry object of the opcode last located in the ReadNextObj function TMemRange m_ROMMemMap; // Mapping of ROM memory TMemRange m_RAMMemMap; // Mapping of RAM memory TMemRange m_IOMemMap; // Mapping of Memory Mapped I/O private: typedef std::map<std::string, unsigned int> TParseCmdMap; TParseCmdMap ParseCmds; // Used internally to store control file commands TParseCmdMap ParseCmdsOP1; // Used internally to store control file commands TParseCmdMap ParseCmdsOP2; // Used internally to store control file commands TParseCmdMap ParseCmdsOP3; // Used internally to store control file commands TParseCmdMap ParseCmdsOP4; // Used internally to store control file commands TParseCmdMap ParseCmdsOP5; // Used internally to store control file commands int LAdrDplyCnt; }; #endif // _GDC_H_ <file_sep>/programs/funcanal/FuncView/SymbolMapListView.h // SymbolMapListView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: SymbolMapListView.h,v $ // Revision 1.1 2003/09/13 05:45:50 dewhisna // Initial Revision // // #if !defined(AFX_SYMBOLMAPLISTVIEW_H__FAB9EBAB_755D_4BD3_AFE9_966D0A3BF19B__INCLUDED_) #define AFX_SYMBOLMAPLISTVIEW_H__FAB9EBAB_755D_4BD3_AFE9_966D0A3BF19B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CFuncViewPrjDoc; ///////////////////////////////////////////////////////////////////////////// // CSymbolMapListView view class CSymbolMapListView : public CListView { protected: CSymbolMapListView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(CSymbolMapListView) // Attributes public: CFuncViewPrjDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSymbolMapListView) public: virtual void OnInitialUpdate(); protected: virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); //}}AFX_VIRTUAL // Implementation protected: virtual ~CSymbolMapListView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: void FillSymbolMapList(DWORD nSource = 0, LPCTSTR pszSymbolName = NULL); // Generated message map functions protected: //{{AFX_MSG(CSymbolMapListView) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in SymbolMapListView.cpp inline CFuncViewPrjDoc* CSymbolMapListView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SYMBOLMAPLISTVIEW_H__FAB9EBAB_755D_4BD3_AFE9_966D0A3BF19B__INCLUDED_) <file_sep>/programs/funcanal/FuncView/ChildFrmBase.cpp // ChildFrmBase.cpp : implementation of the CChildFrameBase class // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrmBase.cpp,v $ // Revision 1.1 2003/09/13 05:45:36 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "ChildFrmBase.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrameBase IMPLEMENT_DYNCREATE(CChildFrameBase, CMDIChildWnd) BEGIN_MESSAGE_MAP(CChildFrameBase, CMDIChildWnd) //{{AFX_MSG_MAP(CChildFrameBase) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrameBase construction/destruction CChildFrameBase::CChildFrameBase() { m_strFrameTitle = ""; } CChildFrameBase::~CChildFrameBase() { } BOOL CChildFrameBase::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs m_strFrameTitle = cs.lpszName; return CMDIChildWnd::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CChildFrameBase diagnostics #ifdef _DEBUG void CChildFrameBase::AssertValid() const { CMDIChildWnd::AssertValid(); } void CChildFrameBase::Dump(CDumpContext& dc) const { CMDIChildWnd::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CChildFrameBaes message handlers void CChildFrameBase::OnUpdateFrameTitle(BOOL bAddToTitle) { // update our parent window first GetMDIFrame()->OnUpdateFrameTitle(bAddToTitle); CDocument* pDocument = GetActiveDocument(); if (bAddToTitle) { TCHAR szText[256+_MAX_PATH]; if (pDocument == NULL) { lstrcpy(szText, m_strTitle); } else { lstrcpy(szText, pDocument->GetTitle()); if (!m_strFrameTitle.IsEmpty()) lstrcat(szText, " - "); lstrcat(szText, m_strFrameTitle); } if (m_nWindow > 0) wsprintf(szText + lstrlen(szText), _T(":%d"), m_nWindow); // set title if changed, but don't remove completely SetWindowText(szText); } } <file_sep>/programs/m6811dis/stringhelp.h // // Motorola 6811 Disassembler // Copyright(c)1996 - 2014 by <NAME> // #ifndef STRING_HELP_H #define STRING_HELP_H #include <string> #include <algorithm> #include <functional> #include <cctype> #include <locale> // ============================================================================ // trim from start static inline std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // trim from both ends static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); } static inline std::string &makeUpper(std::string &s) { std::transform(s.begin(), s.end(), s.begin(), ::toupper); return s; } static inline int compareNoCase(const std::string &s1, const std::string &s2) { std::string strUpper1 = s1; makeUpper(strUpper1); std::string strUpper2 = s2; makeUpper(strUpper2); return ((strUpper1 < strUpper2) ? -1 : ((strUpper1 > strUpper2) ? 1 : 0)); } // ============================================================================ #endif // STRING_HELP_H <file_sep>/programs/funcanal/FuncView/OutputView.h // OutputView.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: OutputView.h,v $ // Revision 1.1 2003/09/13 05:45:47 dewhisna // Initial Revision // // #if !defined(AFX_OUTPUTVIEW_H__F016EE3C_8F7F_4B35_A9C2_E54F1F80B97B__INCLUDED_) #define AFX_OUTPUTVIEW_H__F016EE3C_8F7F_4B35_A9C2_E54F1F80B97B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CFuncViewPrjDoc; ///////////////////////////////////////////////////////////////////////////// // COutputViewFile class COutputView; class COutputViewFile : public CFile { public: // Constructors COutputViewFile(COutputView &rOutputView); virtual ~COutputViewFile(); #ifdef _DEBUG public: virtual void Dump(CDumpContext& dc) const; virtual void AssertValid() const; #endif // Implementation: protected: COutputView &m_rOutputView; BOOL m_bEraseOnNextWrite; public: virtual DWORD GetPosition() const; BOOL GetStatus(CFileStatus& rStatus) const; virtual LONG Seek(LONG lOff, UINT nFrom); virtual void SetLength(DWORD dwNewLen); virtual UINT Read(void* lpBuf, UINT nCount); virtual void Write(const void* lpBuf, UINT nCount); virtual void Abort(); virtual void Flush(); virtual void Close(); // Unsupported APIs virtual CFile* Duplicate() const; virtual void LockRange(DWORD dwPos, DWORD dwCount); virtual void UnlockRange(DWORD dwPos, DWORD dwCount); }; ///////////////////////////////////////////////////////////////////////////// // COutputView view class COutputView : public CEditView { protected: COutputView(); // protected constructor used by dynamic creation DECLARE_DYNCREATE(COutputView) // Attributes public: CFuncViewPrjDoc* GetDocument(); inline COutputViewFile *GetOutputFile() const { return m_pOutputViewFile; } protected: COutputViewFile *m_pOutputViewFile; CFont m_fntOutput; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COutputView) public: virtual void OnInitialUpdate(); //}}AFX_VIRTUAL // Implementation protected: virtual ~COutputView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: //{{AFX_MSG(COutputView) afx_msg void OnDestroy(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in OutputView.cpp inline CFuncViewPrjDoc* COutputView::GetDocument() { return (CFuncViewPrjDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_OUTPUTVIEW_H__F016EE3C_8F7F_4B35_A9C2_E54F1F80B97B__INCLUDED_) <file_sep>/programs/funcanal/FuncView/ChildFrm4.h // ChildFrm4.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm4.h,v $ // Revision 1.1 2003/09/13 05:45:34 dewhisna // Initial Revision // // #if !defined(AFX_CHILDFRM4_H__852AB5AF_96B1_4F85_ABF2_00FE3BEB96DD__INCLUDED_) #define AFX_CHILDFRM4_H__852AB5AF_96B1_4F85_ABF2_00FE3BEB96DD__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ChildFrmBase.h" class COutputView; ///////////////////////////////////////////////////////////////////////////// // CChildFrame4 frame class CChildFrame4 : public CChildFrameBase { DECLARE_DYNCREATE(CChildFrame4) protected: CChildFrame4(); // protected constructor used by dynamic creation // Attributes public: COutputView *m_pOutputView; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame4) protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation protected: virtual ~CChildFrame4(); // Generated message map functions //{{AFX_MSG(CChildFrame4) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDFRM4_H__852AB5AF_96B1_4F85_ABF2_00FE3BEB96DD__INCLUDED_) <file_sep>/programs/funcanal/FuncView/ChildFrm6.h // ChildFrm6.h : header file // ///////////////////////////////////////////////////////////////////////////// // // $Log: ChildFrm6.h,v $ // Revision 1.1 2003/09/13 05:45:36 dewhisna // Initial Revision // // #if !defined(AFX_CHILDFRM6_H__92F9AA21_0C5F_4C43_BA72_95EF6BD85F4A__INCLUDED_) #define AFX_CHILDFRM6_H__92F9AA21_0C5F_4C43_BA72_95EF6BD85F4A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ChildFrmBase.h" ///////////////////////////////////////////////////////////////////////////// // CChildFrame6 frame class CChildFrame6 : public CChildFrameBase { DECLARE_DYNCREATE(CChildFrame6) protected: CChildFrame6(); // protected constructor used by dynamic creation // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildFrame6) protected: virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext); //}}AFX_VIRTUAL // Implementation protected: virtual ~CChildFrame6(); // Generated message map functions //{{AFX_MSG(CChildFrame6) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDFRM6_H__92F9AA21_0C5F_4C43_BA72_95EF6BD85F4A__INCLUDED_) <file_sep>/programs/funcanal/FuncView/FuncViewPrjVw.cpp // FuncViewPrjVw.cpp : implementation of the CFuncViewPrjView class // ///////////////////////////////////////////////////////////////////////////// // // $Log: FuncViewPrjVw.cpp,v $ // Revision 1.1 2003/09/13 05:45:45 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "FuncViewPrjDoc.h" #include "FuncViewPrjVw.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjView IMPLEMENT_DYNCREATE(CFuncViewPrjView, CTreeView) BEGIN_MESSAGE_MAP(CFuncViewPrjView, CTreeView) //{{AFX_MSG_MAP(CFuncViewPrjView) ON_COMMAND(ID_EDIT_CLEAR, OnEditClear) ON_UPDATE_COMMAND_UI(ID_EDIT_CLEAR, OnUpdateEditClear) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CTreeView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CTreeView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CTreeView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjView construction/destruction CFuncViewPrjView::CFuncViewPrjView() { m_hMatrixBaseNode = NULL; } CFuncViewPrjView::~CFuncViewPrjView() { } BOOL CFuncViewPrjView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CTreeView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjView printing BOOL CFuncViewPrjView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CFuncViewPrjView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CFuncViewPrjView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjView diagnostics #ifdef _DEBUG void CFuncViewPrjView::AssertValid() const { CTreeView::AssertValid(); } void CFuncViewPrjView::Dump(CDumpContext& dc) const { CTreeView::Dump(dc); } CFuncViewPrjDoc* CFuncViewPrjView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CFuncViewPrjView message handlers void CFuncViewPrjView::OnInitialUpdate() { CTreeCtrl &theTree = GetTreeCtrl(); theTree.ModifyStyle(0, TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_SHOWSELALWAYS, SWP_NOACTIVATE); // Call default which will call OnUpdate which will call FillFileLists: CTreeView::OnInitialUpdate(); } void CFuncViewPrjView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; switch (lHint) { case 0: // Normal Update FillFileLists(); FillMatrixLists(); break; case MATRIX_TYPE_BASE: // Matrix list only update FillMatrixLists(); break; } if ((lHint >= FILESET_TYPE_BASE) && (lHint <= FILESET_TYPE_LAST)) { // FILESET_TYPE_BASE+nFileSet = Document Fileset Function update (pHint = &CFuncViewFuncRef) } if ((lHint >= SYMBOL_MAP_TYPE_BASE) && (lHint <= SYMBOL_MAP_TYPE_LAST)) { // SYMBOL_MAP_TYPE_BASE+nSymbolMapType = Symbol Map update (pHint = &LPCTSTR) } } void CFuncViewPrjView::FillFileLists() { CTreeCtrl &theTree = GetTreeCtrl(); theTree.DeleteAllItems(); m_hMatrixBaseNode = NULL; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; HTREEITEM hBase = theTree.InsertItem(pDoc->GetPathName() /* GetTitle() */); if (hBase == NULL) return; theTree.SetItemData(hBase, 0); // Root document title is 0 int i, j; HTREEITEM hFileSet; HTREEITEM hFileEntry; for (i=0; i<pDoc->GetFileSetCount(); i++) { hFileSet = theTree.InsertItem(pDoc->GetFileSetDescription(i), hBase); if (hFileSet == NULL) continue; theTree.SetItemData(hFileSet, FILESET_TYPE_BASE + (i*2)); // FileSet bases are even-numbers above FILESET_TYPE_BASE for (j=0; j<pDoc->GetFileCount(i); j++) { hFileEntry = theTree.InsertItem(pDoc->GetFilePathName(i, j), hFileSet); if (hFileEntry == NULL) continue; theTree.SetItemData(hFileEntry, FILESET_TYPE_BASE + 1 + (i*2)); // FileSet Entries are odd-numbers above FILESET_TYPE_BASE } theTree.Expand(hFileSet, TVE_EXPAND); } theTree.Expand(hBase, TVE_EXPAND); } void CFuncViewPrjView::FillMatrixLists() { CTreeCtrl &theTree = GetTreeCtrl(); CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; if (m_hMatrixBaseNode == NULL) { m_hMatrixBaseNode = theTree.InsertItem("Matrix Input/Output File"); if (m_hMatrixBaseNode == NULL) return; } // Delete all of the item's children: if (theTree.ItemHasChildren(m_hMatrixBaseNode)) { HTREEITEM hNextItem; HTREEITEM hChildItem = theTree.GetChildItem(m_hMatrixBaseNode); while (hChildItem != NULL) { hNextItem = theTree.GetNextItem(hChildItem, TVGN_NEXT); theTree.DeleteItem(hChildItem); hChildItem = hNextItem; } } CString strMatrixPathName = pDoc->GetMatrixPathName(); if (!strMatrixPathName.IsEmpty()) { theTree.InsertItem(strMatrixPathName, m_hMatrixBaseNode); } theTree.Expand(m_hMatrixBaseNode, TVE_EXPAND); } void CFuncViewPrjView::OnEditClear() { CTreeCtrl &theTree = GetTreeCtrl(); HTREEITEM hSel = theTree.GetSelectedItem(); if (hSel == NULL) return; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; CString strName = theTree.GetItemText(hSel); DWORD nType = theTree.GetItemData(hSel); int ndx; if (nType < FILESET_TYPE_BASE) return; if ((nType % 2) != 1) return; ndx = pDoc->FindFile((nType - FILESET_TYPE_BASE - 1) / 2, strName); ASSERT(ndx != -1); // Why did we not find it?? if (ndx != -1) { if (pDoc->RemoveFile((nType - FILESET_TYPE_BASE - 1) / 2, ndx)) { theTree.DeleteItem(hSel); pDoc->SetModifiedFlag(TRUE); pDoc->UpdateAllViews(this); } } } void CFuncViewPrjView::OnUpdateEditClear(CCmdUI* pCmdUI) { CTreeCtrl &theTree = GetTreeCtrl(); HTREEITEM hSel = theTree.GetSelectedItem(); if (hSel == NULL) { pCmdUI->Enable(FALSE); return; } // Enable clearing for function description file filenames: DWORD nType = theTree.GetItemData(hSel); pCmdUI->Enable((nType >= FILESET_TYPE_BASE) && ((nType % 2) == 1)); } <file_sep>/programs/funcanal/FuncView/CompMatrixView.cpp // CompMatrixView.cpp : implementation file // ///////////////////////////////////////////////////////////////////////////// // // $Log: CompMatrixView.cpp,v $ // Revision 1.1 2003/09/13 05:45:38 dewhisna // Initial Revision // // #include "stdafx.h" #include "FuncView.h" #include "CompMatrixView.h" #include "FuncViewPrjDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCompMatrixView IMPLEMENT_DYNCREATE(CCompMatrixView, CView) CCompMatrixView::CCompMatrixView() { m_pGridCtrl = NULL; } CCompMatrixView::~CCompMatrixView() { if (m_pGridCtrl) delete m_pGridCtrl; } BEGIN_MESSAGE_MAP(CCompMatrixView, CView) //{{AFX_MSG_MAP(CCompMatrixView) ON_WM_SIZE() ON_WM_ERASEBKGND() ON_COMMAND(ID_SYMBOLS_ADD, OnSymbolsAdd) ON_UPDATE_COMMAND_UI(ID_SYMBOLS_ADD, OnUpdateSymbolsAdd) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCompMatrixView diagnostics #ifdef _DEBUG void CCompMatrixView::AssertValid() const { CView::AssertValid(); } void CCompMatrixView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CFuncViewPrjDoc* CCompMatrixView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFuncViewPrjDoc))); return (CFuncViewPrjDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CCompMatrixView printing BOOL CCompMatrixView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CCompMatrixView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { if (m_pGridCtrl) m_pGridCtrl->OnBeginPrinting(pDC, pInfo); } void CCompMatrixView::OnPrint(CDC* pDC, CPrintInfo* pInfo) { if (m_pGridCtrl) m_pGridCtrl->OnPrint(pDC, pInfo); } void CCompMatrixView::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo) { if (m_pGridCtrl) m_pGridCtrl->OnEndPrinting(pDC, pInfo); } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl required handlers void CCompMatrixView::OnDraw(CDC* pDC) { // Do nothing here -- CGridCtrl will draw itself for us } void CCompMatrixView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); if ((m_pGridCtrl) && (::IsWindow(m_pGridCtrl->m_hWnd))) { CRect rect; GetClientRect(rect); m_pGridCtrl->MoveWindow(rect); } } BOOL CCompMatrixView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { if ((m_pGridCtrl) && (::IsWindow(m_pGridCtrl->m_hWnd))) if (m_pGridCtrl->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; return CView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } BOOL CCompMatrixView::OnEraseBkgnd(CDC* pDC) { return TRUE; // return CView::OnEraseBkgnd(pDC); } ///////////////////////////////////////////////////////////////////////////// // CCompMatrixView message handlers void CCompMatrixView::OnInitialUpdate() { if (m_pGridCtrl == NULL) { // Create the Gridctrl object m_pGridCtrl = new CGridCtrl; if (!m_pGridCtrl) return; // Create the Gridctrl window CRect rect; GetClientRect(rect); m_pGridCtrl->Create(rect, this, 100); // Set settings: m_pGridCtrl->SetEditable(FALSE); m_pGridCtrl->EnableDragAndDrop(FALSE); } // The following will call OnUpdate which will call FillMatrixHeaders // and FillMatrixData CView::OnInitialUpdate(); } void CCompMatrixView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { if (pSender == this) return; switch (lHint) { case 0: // Normal Update case MATRIX_TYPE_BASE: // Matrix data changed FillMatrixHeaders(); FillMatrixData(); break; } } void CCompMatrixView::FillMatrixHeaders() { if (m_pGridCtrl == NULL) return; CWaitCursor waitCursor; m_pGridCtrl->DeleteAllItems(); CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; int nRows = pDoc->GetFuncCount(CFuncViewPrjDoc::FVFS_LEFT_FILES, -1); int nCols = pDoc->GetFuncCount(CFuncViewPrjDoc::FVFS_RIGHT_FILES, -1); try { m_pGridCtrl->SetRowCount(nRows+1); m_pGridCtrl->SetColumnCount(nCols+1); m_pGridCtrl->SetFixedRowCount(1); m_pGridCtrl->SetFixedColumnCount(1); } catch (CMemoryException& e) { e.ReportError(); e.Delete(); return; } // Set Column headers (right-hand function): CFuncDesc *pFunc; int nFileIndex; int nFuncIndex; int i; nFileIndex = 0; nFuncIndex = 0; for (i=0; i<nCols; i++) { pFunc = pDoc->GetNextFunction(CFuncViewPrjDoc::FVFS_RIGHT_FILES, nFileIndex, nFuncIndex); if (pFunc == NULL) continue; GV_ITEM anItem; anItem.mask = GVIF_TEXT|GVIF_FORMAT; anItem.row = 0; anItem.col = i+1; anItem.nFormat = DT_LEFT|DT_WORDBREAK|DT_NOPREFIX; anItem.strText = pFunc->GetMainName(); m_pGridCtrl->SetItem(&anItem); } // Set Row headers (left-hand function): nFileIndex = 0; nFuncIndex = 0; for (i=0; i<nRows; i++) { pFunc = pDoc->GetNextFunction(CFuncViewPrjDoc::FVFS_LEFT_FILES, nFileIndex, nFuncIndex); if (pFunc == NULL) continue; GV_ITEM anItem; anItem.mask = GVIF_TEXT|GVIF_FORMAT; anItem.row = i+1; anItem.col = 0; anItem.nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX; anItem.strText = pFunc->GetMainName(); m_pGridCtrl->SetItem(&anItem); } m_pGridCtrl->AutoSize(GVS_BOTH); } void CCompMatrixView::FillMatrixData(int nSingleRow, int nSingleCol) { if (m_pGridCtrl == NULL) return; CWaitCursor waitCursor; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; double **ppnMatrix = pDoc->GetMatrix(); if ((!pDoc->HaveMatrix()) || (ppnMatrix == NULL)) return; int nRows = pDoc->GetMatrixRowCount(); int nCols = pDoc->GetMatrixColumnCount(); // Set Data: int i,j,k; double nMaxCompResultX; double nMaxCompResultY; CFuncDesc *pLeftFunc; int nLeftFileIndex; int nLeftFuncIndex; CString strLeftName; CFuncDesc *pRightFunc; int nRightFileIndex; int nRightFuncIndex; CString strRightName; CString strTemp; BOOL bLeft; if (nSingleRow != -1) { pDoc->GetFileFuncIndexFromLinearIndex(CFuncViewPrjDoc::FVFS_LEFT_FILES, nSingleRow, nLeftFileIndex, nLeftFuncIndex); } else { nLeftFileIndex = 0; nLeftFuncIndex = 0; } for (i=((nSingleRow != -1) ? nSingleRow : 0); i<((nSingleRow != -1) ? (nSingleRow+1) : nRows); i++) { nMaxCompResultX = 0; pLeftFunc = pDoc->GetNextFunction(CFuncViewPrjDoc::FVFS_LEFT_FILES, nLeftFileIndex, nLeftFuncIndex); if (pLeftFunc) { strLeftName = pLeftFunc->GetMainName(); } else { strLeftName = ""; } bLeft = pDoc->LookupLeftFuncAssociation(strLeftName, strTemp); if (nSingleCol != -1) { pDoc->GetFileFuncIndexFromLinearIndex(CFuncViewPrjDoc::FVFS_RIGHT_FILES, nSingleCol, nRightFileIndex, nRightFuncIndex); } else { nRightFileIndex = 0; nRightFuncIndex = 0; } for (j=0; j<nCols; j++) nMaxCompResultX = __max(nMaxCompResultX, ppnMatrix[i][j]); for (j=((nSingleCol != -1) ? nSingleCol : 0); j<((nSingleCol != -1) ? (nSingleCol+1) : nCols); j++) { pRightFunc = pDoc->GetNextFunction(CFuncViewPrjDoc::FVFS_RIGHT_FILES, nRightFileIndex, nRightFuncIndex); if (pRightFunc) { strRightName = pRightFunc->GetMainName(); } else { strRightName = ""; } GV_ITEM anItem; anItem.mask = ((ppnMatrix[i][j] != 0) ? GVIF_TEXT|GVIF_FORMAT|GVIF_BKCLR : GVIF_FORMAT|GVIF_BKCLR); anItem.row = i+1; anItem.col = j+1; anItem.nFormat = DT_RIGHT|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX; anItem.crBkClr = CLR_DEFAULT; if (ppnMatrix[i][j] != 0) anItem.strText.Format("%f%%", ppnMatrix[i][j]*100); if ((ppnMatrix[i][j] != 0) && (ppnMatrix[i][j] == nMaxCompResultX)) { nMaxCompResultY = 0; for (k=0; k<nRows; k++) nMaxCompResultY = __max(nMaxCompResultY, ppnMatrix[k][j]); if (nMaxCompResultX == nMaxCompResultY) { anItem.crBkClr = RGB(0, 192, 192); } } if (anItem.crBkClr == CLR_DEFAULT) { if (bLeft || pDoc->LookupRightFuncAssociation(strRightName, strTemp)) anItem.crBkClr = RGB(255, 255, 0); } m_pGridCtrl->SetItem(&anItem); } } m_pGridCtrl->AutoSize(GVS_BOTH); } void CCompMatrixView::OnSymbolsAdd() { if (m_pGridCtrl == NULL) return; CWaitCursor waitCursor; CFuncViewPrjDoc *pDoc = GetDocument(); if (pDoc == NULL) return; CCellID aCell(-1, -1); BOOL bDone = FALSE; CFuncDesc *pLeftFunc; CFuncDesc *pRightFunc; int nLeftFileIndex; int nLeftFuncIndex; CString strLeftName; int nRightFileIndex; int nRightFuncIndex; CString strRightName; double nCompResult; CSymbolMap &theSymbolMap = pDoc->GetSymbolMap(); CString strTemp; int i; int nRows = pDoc->GetMatrixRowCount(); int nCols = pDoc->GetMatrixColumnCount(); while (1) { aCell = m_pGridCtrl->GetNextItem(aCell, GVNI_ALL | GVNI_SELECTED); if ((aCell.row == -1) || (aCell.col == -1)) break; pLeftFunc = pDoc->GetFileFuncIndexFromLinearIndex(CFuncViewPrjDoc::FVFS_LEFT_FILES, aCell.row-1, nLeftFileIndex, nLeftFuncIndex); pRightFunc = pDoc->GetFileFuncIndexFromLinearIndex(CFuncViewPrjDoc::FVFS_RIGHT_FILES, aCell.col-1, nRightFileIndex, nRightFuncIndex); if ((pLeftFunc == NULL) || (pRightFunc == NULL)) continue; strLeftName = pLeftFunc->GetMainName(); strRightName = pRightFunc->GetMainName(); if (pDoc->LookupLeftFuncAssociation(strLeftName, strTemp)) continue; if (pDoc->LookupRightFuncAssociation(strRightName, strTemp)) continue; if (!pDoc->GetCompDiffText().IsEmpty()) pDoc->GetCompDiffText() += "\n"; pDoc->GetCompDiffText() += ::DiffFunctions(FCM_DYNPROG_GREEDY, pDoc->GetFuncDescFile(CFuncViewPrjDoc::FVFS_LEFT_FILES, nLeftFileIndex), nLeftFuncIndex, pDoc->GetFuncDescFile(CFuncViewPrjDoc::FVFS_RIGHT_FILES, nRightFileIndex), nRightFuncIndex, OO_ADD_ADDRESS, nCompResult, &theSymbolMap); pDoc->AddFunctionAssociation(strLeftName, strRightName); nLeftFileIndex = 0; nLeftFuncIndex = 0; for (i=0; i<nRows; i++) { pLeftFunc = pDoc->GetNextFunction(CFuncViewPrjDoc::FVFS_LEFT_FILES, nLeftFileIndex, nLeftFuncIndex); if (pLeftFunc == NULL) continue; if (pLeftFunc->GetMainName().Compare(strLeftName) == 0) FillMatrixData(i, -1); } nRightFileIndex = 0; nRightFuncIndex = 0; for (i=0; i<nCols; i++) { pRightFunc = pDoc->GetNextFunction(CFuncViewPrjDoc::FVFS_RIGHT_FILES, nRightFileIndex, nRightFuncIndex); if (pRightFunc == NULL) continue; if (pRightFunc->GetMainName().Compare(strRightName) == 0) FillMatrixData(-1, i); } } pDoc->UpdateAllViews(this, SYMBOL_MAP_ALL, NULL); pDoc->UpdateAllViews(this, COMP_DIFF_TYPE_BASE, NULL); // Update CompDiffEditViews } void CCompMatrixView::OnUpdateSymbolsAdd(CCmdUI* pCmdUI) { if (m_pGridCtrl == NULL) { pCmdUI->Enable(FALSE); return; } pCmdUI->Enable(m_pGridCtrl->GetSelectedCount() != 0); }
0fe7cfb034db0d37b3761c5a2b0d902782f89cea
[ "Markdown", "C", "Text", "C++" ]
59
C++
dewhisna/m6811dis
ab345e6fa714c8607ca85cbc885b53a9aa782710
a7fc0310dfa9ccfe5e626fc64a1f99350c567b2e
refs/heads/master
<repo_name>eluminatis/roteiros<file_sep>/ruby on rails/rails.md # Rails ## Convenções É um framework web que permite um desenvolvimento agil porém ele tem uma forma bem rigida de programar onde o dev precisa seguir suas convenções para extrair o maximo rendimento, ele usa massivamente geradores para tudo que vc precisar e as principais convenções são: - views que atendem um metodo de um controller devem ficar no caminho ``` bash app/views/nome_do_controller/nome_do_metodo_do_controller.html.erb ``` - variaveis de instancia - *@var* - criadas no metodo do controller estarão automaticamente disponiveis para serem usadas na views - metodos ruby escritos no helper application estarão disponiveis em todo o sistema e metodos escritos nos helpers com nome de recurso estarão disponíveis no controler, models e views do recurso especifico - nos métodos a ultima linha sempre é retornada como se fosse precedida implicitamente por um return, se precisar usar o return no meio de um metodo ele tambem está disponivel ### criar projeto Para criar um novo projeto em rails existem as seguintes opções: ```bash rails new app_name # novo projeto com configs default rails new app_name --database=mysql # pré definindo o db rails new app_name -api # nova api rails new app_name -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb # novo projeto com rails composer, uma espécie de wizard que te ajuda a deixar tudo configurado ``` Loga após cria faça ... ``` bash cd nome_projeto #entra na pasta bundle install #instala as dependencias ``` No arquivo config/database.yml vc deve colocar as configurações de acesso ao seu bd e rodar ``` bash rails db:create #cria o banco de dados ``` ## Generator ### Scaffold ``` bash rails generate scaffold User name:string description:text age:integer cpf:integer:uniq username:string{30}:uniq social_class:references birthday:datetime active:boolean ``` Esse comando irá criar model(User), migration(users), tabela no banco(users), fixture, helper, controller, views, assets (js, sass) e tests para todo o CRUD de users e ainda adicionará a rota recurso no começo de seu arquivo de rotas. De acordo com os campos passados sua tabela no banco será criada com as seguintes colunas: - name (varchar 255) - description (text) - age (int) - cpf (int, unique) - username (varchar 30) - social_class_id (integer, not null, que vai guardar o id da relação com social_classes) - birthday (datetime) - active (boolean) #### Outros tipos que podem ser usados no scaffold - integer - primary_key - decimal - float - boolean - binary - string - text - date - time - datetime - timestamp Caso precise alterar colunas no recurso criado gere um migração com a seguinte estrutura no comando generate. por exemplo, se voce quiser adicionar a coluna nome a tabela pessoas, e nome é do tipo string, seria assim: ```bash rails g migration add_nome_to_pessoas nome:string #o generate migration funciona da seguinte forma: verbo(add/remove/change),nome da coluna, to/from, nome da tabela no plural e depois um espaço e o nome da coluna:tipo da coluna. ``` Caso precise remover um recurso adicionado com scaffold faça ```bash rails destroy scaffold ModelName ``` ## Rotas O arquivo de rotas fica em *config/routes.rb*, ele aceita os seguintes tipos de rotas ``` ruby get 'welcome/hello' # verbo 'controller/metodo' root 'posts#index' # rota default do projeto resources :posts # rota recurso (laravel like) ``` ## Validações no rails as validações ficam no model, um exemplo de como tornar o campo 'title' obrigatorio é adicionar no model do recurso o seguinte: ``` ruby validates_presence_of :title #title agora é required nesse recurso validates_uniqueness_of :titulo # o title deve ser unico na tabela validates_presence_of :nome, message: 'não pode ser deixado em branco' validates :email, presence: {message: 'não pode ser deixado em branco'}, length: {minimum: 10, message: 'deve ter pelo menos 10 caracteres'}, uniqueness: {message: 'deve ser único'} # varias validações para um campo validates_length_of :telefone, maximum: 11, message: 'deve ter até 11 caracteres' validates_length_of :endereco, in: 10..100, message: 'deve ter entre 10 e 100 caracteres' validates_numericality_of :idade, message: 'deve ser um número' validates_length_of :cpf, :is => 11, :allow_blank => true # o numero deve ter exatamente 11 digitos mas é permitido valor em branco ``` Com as validações criadas no model fica disponivel para você o metodo valid? que retorna um boolean informando se o objeto passa em todas as validações ou não ``` ruby post.valid? # true/false de acordo com o resultado nos testes de validações do model ``` ## Seeders Seeders servem para popular seu banco de dados a fim de ter dados para fazer suas funcionalidades sem precisar inseri-los na mão toda vez que instala uma nova instancia do app, eles ficam em *db/seeds.rb* e usam a seguinte sintaxe: ``` ruby movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) Character.create(name: 'Luke', movie: movies.first) Product.create(name: 'Apple', price: 1) Product.create(name: 'Orange', price: 1) Product.create(name: 'Pineapple', price: 2.4) Product.create(name: 'Marble cake', price: 3) ``` Se a sua intenção for apenas popular o banco com dados fakers para simular o funcionamento do app vc pode fazer algo assim: ``` ruby # criando 50 posts no banco (aprender gem faker) 50.times do |i| Post.create(title: "Titulo de um post #{i}", body: "Corpo de um post #{i}") end ``` Após configurá-los com seus dados vc pode rodá-los com o comando ``` bash rails db:seed #popula o banco ``` ## Dicas Você pode ativar um console interativo com seu projeto carregado digitando ``` bash rails console ``` para resetar um banco de dados *nunca faça isso em produção* ``` bash rails db:drop db:create db:migrate #joga o bd fora, cria um novo e cria as tabelas rails db:seed #popula o banco ``` Você pode visualizar no navegador todas as rotas da aplicação em ``` bash localhost:3000/rails/info/routes ``` ## Simbolos ``` ruby :exemplo ``` À princípio o conceito de Símbolos pode parecer estranho e confuso pois trata-se de algo específico de Ruby que você não vai encontrar na maioria das outras linguagens. Símbolos são textos iniciados com o sinal de dois pontos “:” - Eles estão presentes por todo o framework Rails (como nos exemplos de relacionamento entre models que fizemos acima em que usamos os símbolos :eventos e :categoria) Pense em símbolos como “String levinhas”: Como tudo na linguagem Ruby é um objeto, todas as vezes que você cria um string um novo objeto é instanciado na memória. Os símbolos representam nomes mas não são tão pesadas como strings. <file_sep>/javascript/redux_for_react.md # Configuração e uso do redux no react instale redux e react-redux no projeto ```bash yarn add redux react-redux ``` vamos usar para esse exemplo uma lista de cursos ## crie o store/index.js ```javascript import { createStore } from "redux"; const INITIAL_STATE = { data: ["React Native", "ReactJS", "NodeJS"] }; function courses(state = INITIAL_STATE, action) { switch (action.type) { case "ADD_COURSE": return { ...state, data: [...state.data, action.payload] }; default: return state; } } const store = createStore(courses); export default store; ``` imagine o `courses` como uma função que recebe um objeto com o attr `action` que tem um attr `type:string` e com base nesse type vc vai executar uma ação, essa ação sempre deve receber o state anterior e devolve-lo com as alterações desejadas, seja inclusive, update ou exclusão de algum item especifico do state, dentro desse action vc pode colocar um attr contendo o conteudo necessário para essa alteração, normalmente se usa o attr com nome de `payload` para se manter um padrão. ## crie seu App.js ```javascript import React from "react"; import { Provider } from "react-redux"; import store from "./store"; import CourseList from "./components/CourseList"; function App() { return ( <Provider store={store}> <CourseList /> </Provider> ); } export default App; ``` o Provider vai receber o store e garantir que todos os filhos dele tenham acesso a esse store, por isso é importante que ele fique no topo da arvore de componentes da aplicação ## criando a lista de cursos ```javascript import React, { useState } from "react"; import { useSelector, useDispatch } from "react-redux"; // actions sempre retornam um objeto com o type usado para identificar a ação no reducer e os dados necessários para realizar a ação function addCourseAction(title) { return { type: "ADD_COURSE", payload: title }; } export default function CourseList() { const [input, setInput] = useState(""); const courses = useSelector(state => state.data); const dispatch = useDispatch(); function addCourse() { dispatch(addCourseAction(input)); setInput(""); } return ( <> <ul> {courses.map(course => ( <li key={course}>{course}</li> ))} </ul> <input type="text" value={input} onChange={e => setInput(e.target.value)} /> <button type="button" onClick={addCourse}> Adicionar curso </button> </> ); } ``` os dois hooks principais para se usar o redux são `useSelector` e `useDispatch` #### useSelector recebe uma função que recebe o state inteiro da aplicação e devolve o que vc precisa para esse componente #### useDispatch Devolve uma função que recebe um objeto `{ type: "nome da ação", payload: dados necessários para essa ação }`, normalmente esse objeto é montado por uma action, no nosso exemplo a action é `addCourseAction` mas basicamente esssa action faz alguma coisa e devolve um objeto que carrega o nome da ação e os dados necessários para executa-la. concluimos que para adicionar ou remover algo do redux precisamos criar o reducer que recebe o state inteiro da aplicação e action e de acordo com o type da action manipula esse state e devolve ele com o novo valor, cria-se uma action para montar o objeto com o type e dados e passa esse objeto para o nosso reducer por meio do useDispatch e quando é preciso ler algo desse reducer usa-se o useSelector. repo desse exemplo https://github.com/PetersonJFP/react-hooks-redux-example <file_sep>/django/django-admin.md # Django admin no seu urls.py vc pode reescrever as 3 principais variáveis de nome do django-admin ```python admin.site.site_header = 'My project' # default: "Django Administration" admin.site.index_title = 'Features area' # default: "Site administration" admin.site.site_title = 'HTML title from adminsitration' # default: "Django site admin" ``` Alterando o padrão de campos ManyToMany no admin do django para ficar igual ao de permissões. ```python #em admin.py da sua app class EmployeeAdmin(admin.ModelAdmin): filter_horizontal = ('field',) ``` Nas listagens que o django-admin cria, ainda é possível definir um, ou vários filtros a serem usados na listagem. Esse recurso permite a visualização apenas do que interessa na listagem ou um subconjunto de dados mais relevante. ```python #em admin.py da sua app class MyModelAdmin(admin.ModelAdmin): list_filter = ['field_01', 'field_02'] ``` Definindo um campo como apenas leitura ```python #em admin.py da sua app class MyModelAdmin(admin.ModelAdmin): readonly_fields = (''field’,) ``` Personalizando as colunas que aparecem na listagem do django-admin ('index do model') ```python #em admin.py da sua app class MyModelAdmin(admin.ModelAdmin): list_display = ('nome', 'email') ``` Configure _search_fields_ para habilitar uma caixa de busca na página de listagem do admin. Este deve ser configurado com uma lista de nomes de campos que serão afetados pela busca, sempre que alguém submeter um texto por esta caixa de texto. ```python #em admin.py da sua app class MyModelAdmin(admin.ModelAdmin): search_fields = ('nome', 'email') ``` Você pode também executar uma pesquisa relacionada a ForeignKey com a lookup API “siga” a notação: ```python #em admin.py da sua app class MyModelAdmin(admin.ModelAdmin): search_fields = ['foreign_key__related_fieldname'] ``` <file_sep>/composer.md # Trabalhando com composer ## Criando um Pacote Inicialmente você precisa de uma conta no Packagist e o composer instalado na sua máquina. Feito isso rode o comando: ```bash composer init ``` Siga as instruções na tela descritas abaixo ### Passo 1 - Package name Ele deve respeitar o nome de usuário do GitHub/repositório do GitHub ```bash eluminatis/meu_projeto ``` ### Passo 2 - Descrição Essa descrição ficará disponível no site do Packagist ### Passo 3 - Autor O autor deve seguir exatamente a máscara abaixo: ```bash <NAME> <<EMAIL>> ``` ### Passo 4 - Estabilidade Aqui eu coloquei `dev`. Necessário checar a documentação para mais detalhes ### Passo 5 - Tipo de pacote Escolher um dos disponíveis que o Composer sugere. Os nomes são autoexplicativos ### Passo 6 - Licença (Obrigatório para subir pro Packagist) Para escolher um tipo de licença existe um site interessante [aqui](http://choosealicense.com/) O Composer tem as strings válidas para cada tipo de licença, que devem seguir o padrão abaixo - Apache-2.0 - BSD-2-Clause - BSD-3-Clause - BSD-4-Clause - GPL-2.0-only / GPL-2.0-or-later - GPL-3.0-only / GPL-3.0-or-later - LGPL-2.1-only / LGPL-2.1-or-later - LGPL-3.0-only / LGPL-3.0-or-later - MIT Mais detalhes na [documentacao do composer](https://getcomposer.org/doc/04-schema.md#license) Depois o composer perguntará sobre dependências do seu projeto. Você pode definí-las aqui se necessário. A saída deve ser algo assim: ```json { "name": "eluminatis/meu_projeto", "description": "Projeto de teste do Composer", "type": "library", "license": "GPL-3.0-or-later", "authors": [ { "name": "<NAME>", "email": "<EMAIL>" } ], "minimum-stability": "dev", "require": {} } ``` ## Preparando os diretórios para o seu pacote Uma boa prática é incluir os fontes em `src`, por convenção da comunidade. ## Namespaces Para que seu pacote seja alocado corretamente, você precisa dizer onde "mora" seu namespace. Baseando no namespace escolhido, adicione a diretiva abaixo em seu `composer.json` ```json "autoload": { "psr-4" : { "Eluminatis\\MeuOutroNamespace\\" : "src" } } ``` ## Publicando no Packagist Vá na área "Submit" e aponte para o link do seu repositório no GibHub Ele fará checagens de sintaxe no seu arquivo `composer.json` e corrija os erros que porventura apareçam ## Autoload no Laravel / Gerando pacotes para Laravel O Laravel permite que você carregue Service Providers automaticamente se você adicionar a diretiva no `composer.json` Adicione seu pacote seguindo esse padrão: ```json "extra": { "laravel": { "providers": [ "Eluminatis\\MeuOutroNamespace\\EluminatisServiceProvider" ] } } ``` Tudo pronto, teste com: ```bash composer require eluminatis/meu_projeto dev-master ``` ## TODO Escrever sobre SemVer e tags/releases no github<file_sep>/laravel/email_laravel.md # Email com laravel #### FROM Se todos os emails enviados pelo seu app forem ter o mesmo endereço de remetente, você não precisar ficar definindo isso a cada envio, basta criar e configurar as seguintes variaveis em seu .env MAIL_FROM_ADDRESS=<EMAIL> MAIL_FROM_NAME=SeuNome caso cada email possa ter um remetente diferente configure diretamente no `->from()` do metodo `build()` ```php public function build() { return $this->from('<EMAIL>') ->view('emails.orders.shipped'); } ``` ### Mailables Cada tipo de email disparado por seu app é representado por uma classe mailable, você deve gerar asssim: php artisan make:mail SeuMailable Toda a configuração é feita no build. Dentro deste método, você pode chamar vários métodos, como from, subject, view, e attach para configurar apresentação e entrega do e-mail. ```php public function build() { return $this->from('<EMAIL>') ->subject('Seu assunto') ->view('emails.seuTemplate') ->attach('caminho para o anexo se necessário'); } ``` Ao anexar arquivos a uma mensagem, você também pode especificar o nome de exibição e / ou o tipo MIME, passando um segundo argumento (do tipo `array`) para o método `attach()`: ```php public function build() { return $this->from('<EMAIL>') ->subject('Seu assunto') ->view('emails.seuTemplate') ->attach('/path/to/file', [ 'as' => 'name.pdf', 'mime' => 'application/pdf', ]); //também existe o ->text('texto desagatemelizado') para textos planos } ``` ## Passando variaveis para a classe Mailable Você deve definir variáveis públicas na classe mailable e passar variáveis pelo construtor para ela e automaticamente ela estará disponível dentro de sua view ```php <?php namespace App\Mail; use App\Order; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class OrderShipped extends Mailable { use Queueable, SerializesModels; /** * a variavel que recebe um array de variveis que vc queira passar */ public $data; /** * o construtor recebe a variavel e a joga dentra da var publica * e agora vc pode usa-la dentro da view */ public function __construct($data) { $this->data = $data; } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.template'); } } ``` Depois de os dados serem passados pelo construtor e definidos como propriedade publica, você poderá acessá-los de dentro da view ```php <div> <p>Preço: {{ $data['var1'] }}</p> </div> ``` ## Inserindo imagens no corpo do email o laravel disponibiliza a variavel `$message` nos mailables com alguns métodos que facilitam seu trabalho. Um deles é o método de inserir imagens no corpo do email. Na view, coloque a imagem da seguinte forma: ```php <body> Aqui temos um exemplo de inserção de imagem no corpo <img src="{{ $message->embed(asset('images/email_rodape.png')) }}"> </body> ``` ## Enviando emails No seu controller registre o uso da fachade `Illuminate\Support\Facades\Mail` e o seu mailable `App\Mail\SeuMailable`. Feito isso é só chamar o método`Mail::to('destinatario')->send(New SeuMailable($vars))` O `to()` aceita um endereço de email, uma instância do usuário ou uma coleção de usuários. Se você passar um objeto ou uma coleção de objetos, o programa de email usará automaticamente as propriedades email e name ao configurar os destinatários de e-mail. ```php <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Mail\SeuMailable; //importando seu mailable use Illuminate\Support\Facades\Mail; //importando facade de emails class OrderController extends Controller { /** * Envia um email qualquer a um tolo qualquer */ public function enviaEmail(){ $data['var1'] = 'bla bla bla'; $data['var2'] = 'ble ble ble'; Mail::to('<EMAIL>')->send(new SeuMailable($data)); ou Mail::to('<EMAIL>') ->cc($moreUsers) ->bcc($evenMoreUsers) ->send(new SeuMailable($data)); } } ``` ## Visualizando mailables no navegador Para fins de desenvolvimento você pode visualizar seus mailables no navegador simplesmente retornando-o na rota de testes: ```php Route::get('/mailable_teste', function () { $data['var1'] = 'bla bla bla'; $data['var2'] = 'ble ble ble'; return new App\Mail\SeuMailable($data); }); ``` <file_sep>/laravel/roteiro_laravel.md # Roteiro Laravel ### Configurações Iniciais **Criando um projeto:** Vá com o terminal ate a pasta htdocs cd /opt/lampp/htdocs Digite o comando: composer create-project --prefer-dist laravel/laravel nome_projeto Feito isso, o composer vai baixar o laravel, criar a pasta `nome_projeto` e instalá-lo dentro dele Você deve dar permissao de escrita para a pasta `storage` que é onde o fw guarda os logs e arquivos. Se for trabalhar com uploads crie uma pasta `uploads` dentro de `public` Verifique qual é o usuário que seu webserver utiliza. No Ubuntu, o usuário do apache é o `www-data` # Muda o grupo da pasta para o do apache sudo chown -R seu_usuario:www-data public/uploads sudo chown -R seu_usuario:www-data storage # Aplica as permissões corretas sudo chmod -R 774 storage sudo chmod -R 774 public/uploads No netbeans, crie um novo projeto com codigo fonte existente e aponte para a pasta do seu projeto Crie o banco para seu projeto com a seguinte collation: `utf8mb4_unicode_ci` padrão do laravel Abra o projeto na pasta raiz e abra o arquivo `.env`. Caso não exista, renomeie o `.env.example` para `.env` e insira os seguintes dados: APP_URL = url base de seu projeto APP_NAME = nome do seu projeto Inserir também dados de acesso ao database Altere o timezone default para o BR em: config/app.php 'timezone' => 'America/Sao_Paulo', ### Ajustes finos Em: app/Providers/AppServiceProvider.php@boot addicionar no método: Schema::defaultStringLength(191) No `namespace`: use Illuminate\Support\Facades\Schema; Isso evita conflitos de tamanho de string no Banco de Dados MySQL e MariaDB ### Configurando tradução / linguagem / locale cd resources/lang/ Clone um projeto de traduçao open do git git clone https://github.com/enniosousa/laravel-5.5-pt-BR-localization.git ./pt-br Para que a tradução entre no seu controle de versão principal faça: # Remove o repositório do vendor anterior rm -r pt-br/.git/ Agora só configurar no `config/app.php` 'locale' => 'pt-br', ### Adicionando barra de debbug ao projeto (app_debug === true) composer require barryvdh/laravel-debugbar ### Inserindo Helper próprio coloque seu helper dentro da pasta App/MyHelper.php add ao composer ```javascript "autoload": { "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\\": "app/" }, "files": [ "app/MyHelper.php" //Seu arquivo aqui ] }, ``` ### Removendo arquivos desnecessários ao controle de versão Adicione ao .gitignore da pasta raiz as seguintes linhas ```bash /nbproject //se estiver usando netbeans /storage/* ``` ### Convenções de nomenclatura Quando você vai criar um `model`, coloque o nome no singular com a primeira letra maiúscula. Ele irá alterar essa string para gerar `controler` e `migration` compatíveis com a nomenclatura padrão Links de ações colocados em botos nas tabelas de crud devem seguir a seguinte formação tabela/{{id_item}}/editar ## Banco de dados ### Criando os dados da aplicação (Migrations) Nesse ponto você precisa já ter definido todas as tabelas e relações requeridas para sua aplicação. De preferência utilizar algum gerador de MER (Modelo Entidade Relacionamento) Para cada tabela necessária a seu app, digite no terminal já dentro da pasta de seu app php artisan make:model –all Models\\NOME onde `NOME` é o nome no singular e com a primeira letra maiuscula de sua classe. Feito isso, o `artisan` ira criar a `model`, o `controller` e a `migration`, tudo com as convenções de nomenclatura do fw e nas suas respectivas pastas e também registrar os autoloads necessarios. Abra a migration criada e preencha as colunas necessárias à sua tabela Rode `php artisan migrate` que serão criadas todas as tabelas das quais você criou as `migrations` **Estudar melhor os conceitos de migrations** **Vale lembrar** Não mexer no `id`. Por padrão o laravel salva o horario de criação e uúltima edição de cada tupla do banco, se quiser manter esse comportamento não delete `timestamps` da migration e caso não precise retire o `timestamps` e adiciona na model a variavel protected $timestamps = false; ### Principais tipos de dados para colunas na migration: ```php $table->string('name', 100); // VARCHAR 2° param tamanho opcional $table->text('description'); // TEXT $table->longText('description'); // LONGTEXT $table->integer('votes'); // INT $table->tinyInteger('votes'); // TINYINT $table->bigInteger('votes'); // BIGINT $table->float('amount', 8, 2) // FLOAT 8,2 $table->dateTime('created_at'); // DATETIME ``` **Principais modificadores de colunas:** ```php $table->integer('votes')->charset('utf8'); // charset da coluna $table->integer('votes')->collation('utf8_unicode_ci'); //collation da coluna $table->integer('votes')->comment('my comment'); // comentário da coluna $table->integer('votes')->nullable(); // aceitar null $table->string('email')->unique(); //não aceita dois registros com o mesmo valor nessa coluna ``` ### Add chave estrangeira ```php $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); ``` a tabela `user` já deve estar criada e a coluna que a referencia também, após isso você pode criar a relação. adicionar `->ondelete(‘cascade’)` à `fk` para que se um pai for deletado, deletar tambem os filhos, não deixando assim registros orfãos no sistema. Tabelas pivo devem ser feitas com as models na ordem alfabética `model1_model2` Caso tenha feito um `php artisan make:model` com nome errado, delete os arquivos e após isso rode um composer dump-autoload ## Integrando o adminLTE Após ter feito todos os passos anteriores vamos integrar o `adminLTE` ao laravel. Instalar o pacote com o `composer` composer require jeroennoten/laravel-adminlte Adicione o serviço a `config/app.php` JeroenNoten\LaravelAdminLte\ServiceProvider::class Publique os assets públicos php artisan vendor:publish --provider="JeroenNoten\LaravelAdminLte\ServiceProvider" --tag=assets Crie a integração php artisan make:adminlte Publique o arquivo de configurações php artisan vendor:publish --provider="JeroenNoten\LaravelAdminLte\ServiceProvider" --tag=config Rode as migrations para criar as tabelas necessárias ao sistema de autenticação php artisan migrate As configurações de menus e defaults você faz em `config/adminlte`. Pronto, já está integrado e com sistema de autenticação funcionando. Veja a documentação no repositório https://github.com/jeroennoten/Laravel-AdminLTE ## Mensagens flash: São mensagens que ficam na sessão apenas pela próxima requisição, ideal para mensagens de aviso/sucesso ao usuario. Crie a view `messages/msgs.blade.php` com o seguinte conteudo: ```html @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if(Session::has('flash_msg')) <div class="alert alert-primary text-center"> <p class="text-bold">{{Session::get('flash_msg')}}</p> </div> @endif @if(Session::has('flash_msg_primary')) <div class="alert alert-primary text-center"> <p class="text-bold">{{Session::get('flash_msg_primary')}}</p> </div> @endif @if(Session::has('flash_msg_success')) <div class="alert alert-success text-center"> <p class="text-bold">{{Session::get('flash_msg_success')}}</p> </div> @endif @if(Session::has('flash_msg_info')) <div class="alert alert-info text-center"> <p class="text-bold">{{Session::get('flash_msg_info')}}</p> </div> @endif @if(Session::has('flash_msg_warning')) <div class="alert alert-warning text-center"> <p class="text-bold">{{Session::get('flash_msg_warning')}}</p> </div> @endif @if(Session::has('flash_msg_danger')) <div class="alert alert-danger text-center"> <p class="text-bold">{{Session::get('flash_msg_danger')}}</p> </div> @endif @if(Session::has('flash_msg_alert')) <script> alert('{{Session::get("flash_msg_alert")}}'); </script> @endif ``` **Criada a view e usada como include nos forms e telas que vc precisa exibir a mensagem basta defini-la antes do redirect com:** ```php \Session::flash('flash_msg', 'Ação realizada com sucesso.'); \Session::flash('flash_msg_primary', 'Ação realizada com sucesso.'); \Session::flash('flash_msg_success', 'Ação realizada com sucesso.'); \Session::flash('flash_msg_info', 'Ação realizada com sucesso.'); \Session::flash('flash_msg_warning', 'Ação realizada com sucesso.'); \Session::flash('flash_msg_danger', 'Ação realizada com sucesso.'); \Session::flash('flash_msg_alert', 'Ação realizada com sucesso.'); ``` **Laravel BD Transaction** No laravel você pode colocar uma sequencia de transações com o banco dentro de uma especie de `try/catch` onde se todas tiverem sucesso serão todas gravadas e se acontecer algum erro no meio do caminho todas as transações do bloco serão desfeitas. **Exemplo de uso:** ```php use DB; DB::beginTransaction(); //abre o bloco de transaction $insercao_1 = create(‘ble ble’); //transação 1 $insercao_2 = create(‘bla bla’); //transação 2 if($insercao_1 && $insercao_2){ //verifica se tudo correu bem DB::commit(); //salva tudo no banco }else{ DB::rollback(); //caso deu algum erro da rollback em todas as transações feitas dentro do bloco } ``` ## Eloquent Quando você cria um model através do `artisan` ele já vem associado à tabela criada pelo seu migration e vários metodos usaveis do ORM eloquent. Para exemplificar usaremos um registro `user` com: - name - telefone - status Seguindo as convenções de nomenclatura do laravel o model sera User e a tabela users. Entre os principais métodos estão: **Criando um usuario:** ```php $user = new User(); $user->name = ‘Peter’; $user->telefone = ‘992192851’; $user->status =1; $user->save(); $id = $user->id; //voce pode recuperar o id imediatamente após salvar o objeto no banco se precisar ``` **Resgatando um registro:** ```php $user = User::find($id); //retorna o registro em forma de objeto se existir ou null $user = User::findOrFail($id) // retorna o registro em forma de objeto ou da erro se ele não existir $users = User::find([1, 2, 3]); // retorna um array de objetos (Collection) usuários dos ids passados $users = User::all(); // retorna um array de objetos com todos os registros do banco $users = User::where(‘name’, ‘Peterson’) // retorna um array de objetos ->orderBy(‘name’, ‘desc’) // onde name = peterson order by ->take(10) // name desc limit 0,10 ->get(); $user = User::where(‘status’, 1)->first(); //retorna o primeiro status 1 da tabela ou null $user = User::where(‘status’, ‘>’, 0)->firstOrFail(); //retorna o primeiro status maior que zero da tabela ou um erro $usersActives = User::where(‘status’, 1)->count(); //int com o número de status =1 da tabela ``` **Alterando um registro** ```php $user = User::find($id); $user->name = ‘<NAME>’; $user->save(); ``` **Apagando o registro `id=1` do banco** ```php $user = User::find(1); $user->delete(); ``` ou ```php User::destroy(1); User::destroy([1,2,3]); //vc pode deletar vários se precisar ``` **Sobre SoftDeletes** `SoftDelete` é um conceito muito interessante que você tem que estudar para implementar no projeto. Trata-se de uma lixeira para onde vão os registros e excluidos e que podem ser listados, recuperados ou excluídos definitivamente depois. ## Fluxo de programação Diferente de outros frameworks, o laravel não define rotas automaticamente para cada controller. Se a rota não existir vai dar erro, logo você precisar registrar todas as rotas de seu app. Principais tipos de rotas: ```php # Chamando uma view Route::get('/', function () { return view('welcome'); }); # Chamando view passando variaveis a ela Route::get('/', function () { $dados = array( 'titulo' => 'Peterson' ); return view('welcome', $dados); }); # Chamando um metodo de um controller Route::get('/home', 'HomeController@index'); ``` ## Acrescentando helpers personalizados Há duas maneiras de adicionar seus próprios helpers a aplicação, A primeira é jogar suas functions helpers no arquivo: `vendor\laravel\framework\src\Illuminate\Foundation\helpers.php` A segunda é criando dentro de `app/helpers/seu_helper.php`, adiciona-lo ao `composer.json` e dar um `composer dump` no terminal Exemplo de como add ao `composer.json`: ```json "psr-4": { "App\\": "app/" }, "files": [ "app/Helpers/MyHelper.php" ] ``` ## Logs ```php use Illuminate\Support\Facades\Log; //registre o uso do log no seu controller # use um dos niveis de log definidos na rfc5424 e registre sua mensagem, # os logs ficam em storage/logs Log::emergency($message); Log::alert($message); Log::critical($message); Log::error($message); Log::warning($message); Log::notice($message); Log::info($message); Log::debug($message); ``` ## Requisições - todo o formulario deve conter a linha `{{ csrf_field() }}` - a rota que recebe o formulario deve especificar se é uma requisição POST ou GET ou qualquer outra personalizada - no controller a requisição vem na forma de um objeto `$request` do laravel e para receber os dados você usa assim: ```php nome = $request->nome #sendo nome = name do input que você tá recebendo ``` - no formulario de edição você deve especificar o `id` do item editado na url para o routes saber que se trata de uma variavel e passar para o controller ex.: ```php <form method="post" action="{{ url('noticia/'.$news->id.'/editar') }}"> Route::post('/noticia/{news}/editar', 'newsController@edit'); public function update(Request $request, News $news) { $news->title = $request->title; $news->text = $request->text; $news->save(); return redirect(route('listar_noticias')); } ``` No formulario de edição os `values` dos inputs devem ser preenchidos assim value="{{ $news->title }}" ## Validando requisições a forma mais simples de fazer isso é validando no controllers antes de salvar os dados vindos da request. Exemplo: ```php $request->validate([ 'title' => 'required|unique:posts|max:255', 'text' => 'required|min:6', ]); ``` dentro do array validate você passa como primeiro parametro o name do campo que esta chegando pela request e no segundo parametro as regras de validação. Se passar na validação, o método vai prosseguir normalmente, se não passar irá retornar para o form onde você deve colocar o seguinte metodo antes da abertura do form para exibir os erros: ```php @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif ``` ## Principais regras de validação Regra | Efeito --- | --- accepted | somente checkbox marcado alpha | somente caracteres alphabetics alpha_num | somente alfanumericos confirmed | deve bater com outro campo de nome igual mais sufixo _confirmation ex.: pass = pass_confirmation e-mail | deve ser um e-mail valido image | deve ser uma imagem jpeg, png, bmp, gif ou svg integer | deve ser um inteiro max:999 | numero maximo de caracteres min:9 | numero minimo de caracteres nullable | pode ser nulo input type text numeric | somente numeros required | obrigatorio string | somente texto unique:tabela | deve ser unico na tabela com a coluna do mesmo name ## Traduzindo nomes de campos nas mensagens de erro Vá ate o final do arquivo `resources/lang/pt-BR/validation.php` e edite o seguinte array: ```php 'attributes' => [ 'name_do_input' => 'Nome conforme você quer que apareça na mensagem', 'name_do_input' => 'Nome conforme você quer que apareça na mensagem', ], ``` ## Sistema de autenticação nativo Se você for inserir um usuário por outro método, você deve passar a senha dele pela funcao `bcrypt(‘123’)` para que depois o metodo autenticador reconheça essa senha ## Sistema de niveis de acesso nativo Existem dois métodos de se fazer isso: 1) As regras (Gates) que servem para visualização de itens ou acesso a area restritas daquele nivel entre outras coisa 2) As politicas onde você define regras para cada model especifico. ```php Gate::define('habilidade_requerida', function ($user, $post) { return 'uma logica que retorne true ou false para a permissao'; }); ``` Nesse exemplo estou validando um `post` passado como parametro. O `user` **não** precisa ser passado pois o Gate já pega o objeto user logado. No controller verifique assim: ```php if (Gate::denies('habilidade_requerida', $post)) { // se entrou aqui é porque o usuario não pode executar essa ação então mande um erro. } ``` Não esqueça de dar um `use Gate` no controller. ## Upload de arquivos Existem varias formas mas a que eu achei mais facil é a seguinte: - dentro da pasta `public`, crie uma pasta `images` e ponha a `sua_imagem.jpeg` lá - dentro de sua pasta public crie uma pasta uploads e de permissões para ela - no arquivo config/filesystem.php configura o root do disco local na linha 48 para public_path() - no formulario não esquece o enctype e o input tipe file - no controler você recebe conforme o exemplo abaixo onde usei o nome image para o input ```php if ($request->hasFile('image') && $request->file('image')->isValid()) { $nome_da_imagem_salva = $request->image->store('uploads'); } ``` Na view para exibir a imagem você usa o source assim: {{ asset($nome_da_imagem_salva) }} Na hora de excluir a imagem do banco, exclua o arquivo da seguinte forma: ```php if (!empty($post->image) && file_exists(public_path($post->image))) { unlink(public_path($post->image)); } ``` ## Front-end Atalhos úteis do Blade Template: ```php {{ url(‘/seu link’) }} = url base {{ asset('css/app.css') }} = url base da pasta public {{ config('app.name', 'Laravel') }} = pega o nome da aplicação do .env ou coloca o segundo parametro se a opção não estiver definida {{ Auth::user()->name }} = exibir dados do usuario logado {{ route('name_da_rota') }} = você pode definir um ->name(‘nome’) para suas rotas e chamar os links delas no front dessa forma simplificada {{ csrf_field() }} = campo de segurança obrigatorio em todos os formularios do app ``` ### Exibir itens somente para quem esta logado @guest ‘convidado’ @else ‘usuario logado’ @endguest = if que faz ações diferentes se o usuario for ou não convidado @auth ‘logado’ @else ‘nao logado’ @endauth = if que faz ações diferentes se o usuario estiver ou não logado ## Exibir itens somente para quem tem permissao de ver aquele item ```php @can(‘nivel de acesso exigido’, alguma variavel que você precise passar para verificação) ‘pode visualizar pois tem o nivel necessario de acesso’ @else ‘opcional para aparecer caso o conteudo tenha sido bloqueado por falta de acesso’ @endcan value="{{ old('email') }}" = preenche o campo com o valor submisso anteriormente caso de algum erro ``` ## Usando layouts do blade Você cria um layout mestre com cabeçalho e rodapé no meio dele você utiliza a tag `@yield('content')` por exemplo. Quando você for colocar algo dentro daquele espaço você faz assim: ```php # Exemplo de um arquivo que extende um layout master # Vai buscar a view dentro de /resources/views/layouts e extende a view 'app.blade.php' @extends('layouts.app') @section('content') // Seu HTML vai aqui @endsection ``` você estendeu o layout padrao e definiu aquele bloco de codigo `//Seu HTML vai aqui` como aquela section dele ## Projeto no mundo real - crie um novo site no painel da hostinger - acesse ele por ssh e com o composer crie uma nova aplicação laravel - crie outra pasta na raiz chamada repo.git pára abrigar seu repositorio - dentro dessa pasta crie um repositório git do tipo **bare** com: `git init –-bare` - puxe o projeto da pasta da aplicação para esta do repo - crie o hook post receive - puxe a aplicaçao para sua maquina local via git clone - configure o git remoto para o repo.git do servidor - as vezes vem com permissoes eradas, puxe a pasta para a pasta home, rode `sudo chown -R seu_user:seu_user` - jogue ela devolta para o htdocs - codifique mt e a cada commit você da um push para o repositorio remoto que você configurou - quando você cria algo no artisan em localhost, ao subir deve executar um composer dump-autoload para as novas classes serem reconhecidas <file_sep>/adicionar_repositorio_remoto.md # Adicionar repositorio remoto no git ## Adicionando o host abra o arquivo /etc/host sudo nano /etc/hosts adicione o ip do servidor junto com o nome que vc quiser dar a conexão 172.16.17.32 exemplo_homologa ## Adicionando o ssh Editar o arquivo (se não existir crie) sudo nano ~/.ssh/config ### adicione aqui o host que vc criou com user e port Host exemplo_homologa User meu_user Port 1234 ### adicione sua chave ssh ao servidor p não precisar mais digitar senha ssh-copy-id usuário@host ## Adicionando ao git Agora que vc add o host e os dados de ssh vc pode adicionar o remote ao git git remote add homologa exemplo_homologa:repo.git Pronto, agora vc ja pode dar push para homologa que o git so vai pedir a senha de ssh <file_sep>/django/models.md ## Campos disponiveis para models no django ```python from django.db import models #tupla de tuplas que serão usadas como opções de um select BEBIDAS = (('cafe',u'Café expresso'), ('mate',u'Chá mate'), ('chocolate',u'Chocolate quente')) # perceba que campos de textos não obrigatórios devem ser 'blank=True' pq o valor minimo que o # django trabalho para um campo texto é um texto em branco, o 'null=True' deve ser usado em todos # os outros tipos de campo não obrigatorios exceto em campos texto que deve obrigatoriamente ser # blank class Pessoa(Models.model): # campo de texto com max 191 caracteres, pode ser um teto em branco e unique com mensagens de erro personalizadas para cada tipo de validação que pode dar errada name = models.CharField( 'Nome', max_length=191, blank=True, unique=True, error_messages={ 'unique': _("A user with that username already exists."), 'null': _('Não pode ser nulo!') }, ) # campo inteiro, se n for passado assume o valor padrao de 0 bank_balance = models.IntegerField('Saldo na conta', default=0) # campo inteiro que não aceita numeros negativos qt_friends = models.PositiveIntegerField('Quantidade de amigos', default=0) # decimal de 8 casas sendo 2 apos a virgula ('ideal para valores monetarios') value_in_the_pocket = models.DecimalField('Valor no bolso', max_digits=8, decimal_places=2) # campo date birth_date = models.DateField('Data de nascimento') # campo datetime first_kiss = DateTimeField('Data e hora do primeiro beijo') # campo time when_wake_up = TimeField('Horário em que acorda') # campo texto com validação 'é um slug' slug = models.slugField('Slug', help_text='Texto de ajuda do campo. Usado em formulário gerados pelo Django. Útil para exibir exemplo de preenchimento') # campo texto longo permite texto em branco description = models.TextField('Descrição', blank=True) # fk apontando para um objeto cpf com relação 1 x 1 e clausula de ser deletado em cascata credit_card = models.OneToOneField(CreditCard, on_delete=models.CASCADE) # fk para varios objetos Livro com tabela pivot livros = models.ManyToManyField(Livro) # campo texto que é apresentado como um select apresentando as opções definidas na constante que é passada como parametro favorite_drink = models.CharField('Bebida Favorita', max_length=16, choices=BEBIDAS) # campo texto com validação para email not null email = EmailField('Email', null=False) # campo texto com validação para url site = URLField('Endereço na web') # campo texto apresentado como um input file que armazenara o caminho no banco e o arquivo no sistema de arquivos curriculum = FileField('Currículo em PDF') # campo texto apresentado como um input file que armazenara o caminho no banco e o arquivo no sistema de arquivos, com validação para o arquivo ser tipo imagem photo = ImageField('Foto do perfil') ####################################################################################################### # O Django trata uploads salvando o arquivo no sistema de arquivos e o caminho do arquivo no banco de # # dados, para isso vc deve setar em seu settings do projeto a pasta onde ele salvara os arquivos # # Colocar no settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') # ####################################################################################################### # campo file que armazenara o arquivo em uploads/files/ curriculum = models.FileField('Currículo em PDF', upload_to='files', null=True, blank=True) # campo file com validação para imagens que armazenara o arquivo em uploads/files/images/ photo = models.ImageField('Foto do perfil', upload_to='images', null=True, blank=True) # auto_now_add=True significa que sera preenchido com o datetima atual quando o objeto for criado created_at = models.DateTimeField('Criado em', auto_now_add=True) # auto_now=True significa que sera preenchido com o datetima atual sempre que o objeto for salvo updated_at = models.DateTimeField('Atualizado em', auto_now=True) # A 'class Meta' serve para definir metadados da classe class Meta: # como a classe sera ordenada na exibição em lista ordering = ('name', 'birth_date', 'qt_friends') # label do model verbose_name = 'Serumaninho' # label do model no plural verbose_name_plural = 'Pessoinhas' # Estabelece o campo DateTime a ser usado como critério para o método de consulta latest. get_latest_by = self.first_kiss # Define que este é um modelo abstrato (abstract model), que não será persistido em uma tabela mas será usado para definir um esquema reutilizável por herança. abstract = False # Define o nome da tabela que corresponde ao modelo. Quando esta opção não é usada o nome da tabela é aplicao_modelo (ex.: catalogo_livro é o modelo Livro da aplicação catalogo. db_table = 'nem rela aqui, so com banco legado' ``` <file_sep>/git_workflow.md # Workflow básico de desenvolvimento ## Divisão de Branches **Branches ativos** - `master` -> Código estável e testado, publicado tanto em homologação quanto em produção - `homologacao` -> Código que foi testado na máquina de desenvolvimento e está sendo testado no servidor de testes - `peterson` -> Branch _*work in progress*_ do trabalho do Peterson - `girol`- > Branch _*work in progress*_ do trabalho do Girol As divisões de trabalho serão feitas nos cards. **Branches tópicos (temporários)** Branches que serão usados para resolver um problema pontual. Na maioria dos casos será para resolução de *bugs* :bug: . ### Passo a passo para resolução de problemas com branches tópicos: 1. Abrir uma _issue_ Exemplo: Sistema não redireciona para painel após login. 2. Criar um `branch` com o nome da issue + seu número. Exemplo: ```bash # Supondo que a issue tenha o número 42 git checkout -b issue_42 ``` 3. Commitar mudanças 4. Incluir no seu commit a mensagem: `Fix #42` (número da issue que foi aberta) 5. Dar merge em todos os branches ativos para integrar a resolução do bug em todos os cenários ## Integrando funcionalidades As funcionalidades só podem ser integradas através de _*Pull Requests*_. _*Pull Requests*_. são como um documento ativo que registra integrações de código no sistema _estável_. Passo a Passo: 1. Depois de testado em ambiente de desenvolvimento, abrir um `pull request` no GitHub 2. Verificar quais _issues_ esse `pull request` resolve e marcar na caixa de comentários 3. Verificar conflitos e integrar as mudanças 4. Sincronizar seu clone na máquina de desenvolvimento 5. Dar merge no branch `homologacao` 6. Publicar em `homologação` e enviar para o cliente testar <file_sep>/django/objetosDoBanco.md Como trabalhar com objetos vindos do banco de dados em django ```python #criando um objetona memoria q = Question(question_text="What's new?", pub_date=timezone.now()) # salvando no banco >>> q.save() # agora ele ja tem um ID. >>> q.id 1 # acessando os valores de seus campos >>> q.question_text "What's new?" >>> q.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>) # Mudando o valor de um campo e depois salvando-o >>> q.question_text = "What's up?" >>> q.save() # objects.all() retorna todos os objetos do banco daquele model >>> qs = Question.objects.all() # contando os objetos >>> qs.count() # retorna todos os objetos do banco daquele model em ordem pelo campo passado >>> qs = Question.objects.order_by('headline') # retorna todos os objetos do banco daquele model em ordem descendente pelo campo passado >>> qs = Question.objects.order_by('headline').desc() # retorna todos os objetos do banco daquele model em ordem ascendente pelo campo passado >>> qs = Question.objects.order_by('headline').asc() # pegando por chave primaria ('id') >>> q = Question.objects.get(pk=1) ############################################################################### # Lookups # ############################################################################### # são sufixos que começam com __ e que representam filtros para serem usados # # na query # ############################################################################### # pegando por id passando um array, retorna um queryset >>> q = Question.objects.filter(id__in=[1, 3, 4]) # filtrando por campos >>> q = Question.objects.filter(question_text="What's up?") # filtrando por campos mas ignorando caixa alta/caixa baixa >>> q = Question.objects.get(name__iexact="what's up?") # filtrando por campos que contem aquele conteudo >>> q = Question.objects.get(name__contains='up') # filtrando por campos que contem aquele conteudo mas ignorando caixa alta/caixa baixa >>> q = Question.objects.get(name__icontains='uP') # inicia com >>> q = Question.objects.filter(question_text__startswith='What') # inicia com, mas ignorando caixa alta/caixa baixa >>> q = Question.objects.filter(question_text__istartswith='What') # termina com >>> q = Question.objects.filter(question_text__endswith='up') # termina com, mas ignorando caixa alta/caixa baixa >>> q = Question.objects.filter(question_text__iendswith='UP') # datetime pertence ao ano de 2018 >>> q = Question.objects.get(pub_date__year=2018) # datetime tem mes de 12 >>> q = Question.objects.get(pub_date__month=12) # datetime tem dia de 21 >>> q = Question.objects.get(pub_date__day=21) # datetime tem dia da semana como segunda-feira # ('1 == domingo' '2 == segunda' ... '7 == sabado') >>> q = Question.objects.get(pub_date__week_day=2) # datetime tem data == Null >>> q = Question.objects.get(pub_date__isnull=True) # datetime tem data != Null >>> q = Question.objects.get(pub_date__isnull=False) # datetime com ano maior ou igual a 2015 >>> q = Question.objects.get(pub_date__year__gte=2015) # exclui pub com data maior a hoje ('__gt == grand than') >>> q = Question.objects.exclude(pub_date__gt=datetime.date.today()) # filtra os com data menor a hoje ('__lt == less than') >>> q = Question.objects.filter(pub_date__lt=datetime.date.today()) # exclui pub com data maior ou igual a hoje ('__gte == grand than equal') >>> q = Question.objects.exclude(pub_date__gte=datetime.date.today()) # filtra os com data menor ou igual a hoje ('__lte == less than equal') >>> q = Question.objects.filter(pub_date__lte=datetime.date.today()) # pega as questions filtrando por um name no Blog que é um attr relacionado ('fk') # basta usar o nome do model relacionado todo em caixa baixa >>> q = Question.objects.filter(blog__name='Beatles Blog') # Este exemplo retorna todos os objetos Blog``os quais tem pelo menos uma ``Entry a qual o headline contém 'Lennon': >>> b = Blog.objects.filter(entry__headline__contains='Lennon') # LIMIT # pega 5 objetos ('indices negativos não sao suportados') >>> q = Question.objects.all()[:5] # pega do 5° ao 10° objeto ('indices negativos não sao suportados') >>> q = Question.objects.all()[5:10] # pega do 5° ao 10° objeto ('indices negativos não sao suportados') >>> q = Question.objects.all()[5:10] # range de datas ('BETWEEN') import datetime start_date = datetime.date(2005, 1, 1) end_date = datetime.date(2005, 3, 31) >>> q = Question.objects.filter(pub_date__range=(start_date, end_date)) ``` <file_sep>/laravel/cidades_e_estados_laravel/README.md # Cidades e estados para projetos laravel adicione todos os arquivos do repositorio cada um em sua pasta e roda composer dump-autoload php artisan migrate:fresh --seed pronto, vc já tem uma base de dados com todos os estados brasileiros e suas cidades ## Instruções de uso #### create do model que terá no endereço fk's para estado e cidade Para ter todos os estados em ordem alfabética disponíveis para seleção no formulário, no metodo create passe pasa a view a seguinte variavel ```php $states = \App\Models\State::orderBy('name')->get(); ``` no seu **routes/web** registre a seguinte rota publica auxiliar ```php Route::get('api/cidades_por_estado/{estado}', 'StateController@cities_by_state'); ``` No **StateController** registre o metodo que retornará as cidades do estado atual do select ```php /** * Busca no banco por todas as cidades do estado passado e as retorna * * @return JSON */ public function cities_by_state($id_estado) { $state = \App\Models\State::find($id_estado); $cities = $state->cities; return $cities; } ``` na **view** adicione os seguintes campos ```html <!-- estado --> <div class="form-group"> <label class="control-label" for="estado">Estado</label> <select id="estado" name="state_id" class="form-control"> <option value="">Escolha um estado</option> @foreach($states as $state) <option value="{{ $state->id }}">{{ $state->name }}</option> @endforeach </select> </div> <!-- cidade --> <div class="form-group"> <label class="control-label" for="cidade">Cidade</label> <select id="cidade" name="city_id" class="form-control" disabled> <option value="">Escolha um estado</option> </select> </div> ``` e o seguine javascript ```javascript @section('js') <script> function atualizar_cidades(assincrono = true){ var estado = $('#estado').val(); var page = "{{ url('api/cidades_por_estado') }}/" + estado; $.ajax({ type: 'GET', dataType: 'html', url: page, async: assincrono, beforeSend: function () { $("#cidade").prop('disabled', true); }, success: function (msg) { var cidades = JSON.parse(msg); var options = ''; for (var i = 0; i < cidades.length; i++) { var obj = cidades[i]; options += '<option value="' + obj.id + '">' + obj.name + '</option>'; } $("#cidade").empty(); $("#cidade").append(options); $("#cidade").prop('disabled', false); } }); } $(document).ready(function () { $('#estado').val('{{ $user->state_id }}'); //seleciona o estado do $user atualizar_cidades(false); //atualiza cidades de acordo com o estado $('#cidade').val('{{ $user->city_id }}'); //seleciona a cidade do $user @if (old('city_id') !== NULL) $('#estado').val({{ old('state_id') }}); // se existir um old('cidade') faz o atualizar_cidades(false); // mesmo processo acima dando $('#cidade').val({{ old('city_id') }}); // prioridade ao old() @endif $('#estado').change(function () { atualizar_cidades(); // atualiza as cidades a cada alteração no estado }); }); </script> @endsection ``` <file_sep>/laravel/tdd.md # TDD com Laravel e PHPUnit Tutorial baseado na série de artigos de <NAME>. Link [aqui](https://medium.com/@jsdecena/simple-tdd-in-laravel-with-11-steps-c475f8b1b214). (Em inglês) Foi utilizado também [este link](https://www.devmedia.com.br/test-driven-development-tdd-simples-e-pratico/18533) do DevMedia. (Em português) ## Preparando a suíte de testes do Laravel No diretório raiz do projeto, atualize o arquivo `phpunit.xml` com: ```xml <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value=":memory:"/> <env name="API_DEBUG" value="false"/> <ini name="memory_limit" value="512M" /> ``` Ficará algo parecido com isso: ```xml <?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" bootstrap="vendor/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"> <testsuites> <testsuite name="Feature"> <directory suffix="Test.php">./tests/Feature</directory> </testsuite> <testsuite name="Unit"> <directory suffix="Test.php">./tests/Unit</directory> </testsuite> </testsuites> <filter> <whitelist processUncoveredFilesFromWhitelist="true"> <directory suffix=".php">./app</directory> </whitelist> </filter> <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value=":memory:"/> <env name="API_DEBUG" value="false"/> <env name="MAIL_DRIVER" value="log"/> <ini name="memory_limit" value="512M" /> </php> </phpunit> ``` Usando o banco de dados como `:memory` acelera os testes, bem como `sqlite`. Futuramente, com os testes ficando mais complexos, deve-se ajustar o `memory_limit` para um valor maior. O Debugging também é desabilitado para mostrar apenas os resultados dos testes. ### Sanity Checks Caso você utilize o servidor de desenvolvimento incluído com o Laravel, você não terá tantos problemas com isso. Caso contrário, é necessário que você limpe os caches de `views`, `rotas` e demais recursos que o Laravel cacheia. Utilize os comandos: ```bash artisan cache:clear artisan view:clear artisan route:clear artisan clear-compiled artisan config:clear ``` Uma boa ideia é encapsular esses comandos em um único comando do Artisan ## Tipos de testes ### Testes Unitários (Unit Testing) Servem para testar suas classes: Models, Repositórios, Funções, etc. ### Testes de Funcionalidade (Feature Testing) Servem para testar se seu código, por exemplo, acessa os controllers e verica (asserts) se as ações tomadas são as esperadas, ou até mesmo erros. Por exemplo, acessando uma página que precisa de autenticação, se um erro gera uma _Flash Message_ na sessão ou até mesmo se um redirecionamento ocorre de forma correta. ## Ciclo do TDD Red, Green, Refactor. Ou seja: - Escrevemos um Teste que inicialmente não passa (Red) - Adicionamos uma nova funcionalidade do sistema - Fazemos o Teste passar (Green) - Refatoramos o código da nova funcionalidade (Refactoring) - Escrevemos o próximo Teste Novo Teste -> Teste Falhando -> Nova Funcionalidade -> Teste Passando -> Refatoração (Retorna) ## Sanity Checks Perdi muito tempo tentando debugar testes por assumir que a suíte de testes fará algumas coisas por mim. Abaixo algumas dicas: - Ao gerar um recurso com uma factory utilizando `make()`, lembre-se de ter todos os atributos que precisa na definição da factory. Normalmente assumimos os campos com valores `default` no banco quando vamos gerar seeders, mas no teste isso não acontece. - Ao testar o envio de uma request de qualquer tipo que não `GET`, certifique-se de ter todos os atributos que precisa na request. O phpunit por padrão não exporta os erros, mostrando apenas um internal error com status 500. Às vezes é possível debugar pelo log, mas às vezes ele não loga, como por exemplo, um atributo required que não foi enviado, vai gerar um `return back()` jogando você de volta para `localhost`. ### Exemplos de TDD com Laravel ## TODO <file_sep>/README.md # Roteiros Uma coletânea de roteiros e anotações sobre as ferramentas e linguagens de programação <file_sep>/ambiente_local_apache_dns.md # Preparando ambiente local de desenvolvimento com Apache Este roteiro visa auxliar a configuração de um dns local em sua máquina para trabalhar com urls completas Crie suas pastas de projeto na seguinte estrutura: /caminho/para/pasta/projetos/site1/www `site1` é onde estará armazenado um projeto. `www` será a pasta visível para o apache. ## Editando arquivo de hosts Supondo que o seu projeto será hospedado no domínio site1.com.br Edite o arquivo `/etc/hosts` e adicione a entrada: 127.0.0.1 site1.com.br ## Configurando o virtualhost no apache Vá até: /etc/apache2/sites-available [ Descrever aqui o processo de deploy de um site ] ### Dnsmasq<file_sep>/laravel/basic_api_authentication.md # Autenticação basica para rotas de API no laravel No arquivo de rotas proteja a rota desejada com o middleware auth.basic ```php Route::resource('vehicles', 'VehicleController')->middleware('auth.basic') ``` Para ter acesso a essa rota vc deve mandar um header na requisição chamado Authorization e seu conteudo devera ser a string 'Basic' + espaço + um base64 do '<EMAIL>:userPassword' do usuario ### Exemplo: Dado um usuario com email `<EMAIL>` e senha `<PASSWORD>` - concatenamos `email` + `:` + `senha` resultando na string `<EMAIL>:<PASSWORD>` - convertemos essa string para base64 resultando em `YWRtaW5AYWRtaW4uY29tOnBhc3N3b3Jk` e Enviamos o seguinte header na request protegida por autenticação ``` Authorization : Basic YWRtaW5AYWRtaW4uY29tOnBhc3N3b3Jk ``` <file_sep>/laravel/cidades_e_estados_laravel/app/Http/Controllers/CityController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\City; class CityController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return City::all(); } } <file_sep>/laravel/queue.md # Laravel Queues Nesse tutorial usaremos apenas o modo database ## Conceito - Criamos as tabelas que abrigarão as filas - Criamos varias filas de acordo com nossa necessidade para classificar os tipos de jobs que vamos enfileirar - Criamos os jobs que receberão nossas variaveis pelo construct e jogarão em atributos protected para poder usar no processamento - Uma vez criado um job e preparado para receber as variaveis pelo construtor e passar para seus proprios atributos 'protected', criamos nossa logica de processamento dentro do metodo handle() usando os atributos protected criados no construtor para popular as variaveis da logica - Nos controllers instanciamos o job passando o que precisamos de variaveis para seu construtor ('as variaveis devem ser passadas no método dispatch para cair no construtor do job') e damos um dispatch para mandar o job pra fila - Instanciamos um laravel-worker que vai tomar conta dessa fila e processar cada job que cair nela, apagando os concluidos e mandando para a tabela failed_jobs aqueles que não puderam ser feitos por algum motivo ## Instruções ### Criamos as tabelas que abrigarão as filas Primeiramente você deve gerar a tabela e rodar a migration para que os jobs possam ser enfileirados nessa tabela e os falhados enfileirados na tabela failedjobs para tratamento posterior ```php php artisan queue:table php artisan queue:failed-table php artisan migrate ``` ### Criamos varias filas de acordo com nossa necessidade para classificar os tipos de jobs que vamos enfileirar arquivo config/queue.php ```php //fila default 'database' => [ //nome da conexão 'driver' => 'database', //driver 'table' => 'jobs', //tabela ('mantenha o padrao jobs') 'queue' => 'default', //nome da fila 'retry_after' => 90, //tempo para tentar refazer um job falhado ], //nossa fila personalizada emails 'database' => [ //nome da conexão 'driver' => 'database', //driver 'table' => 'jobs', //tabela ('mantenha o padrao jobs') 'queue' => 'emails', //nome da fila 'retry_after' => 90, //tempo para tentar refazer um job falhado ], ``` ### Criamos os jobs que receberão nossas variaveis pelo construct e jogarão em atributos protected para poder usar no processamento #### para esse exemplo vamos fazer uma fila de emails que recebe duas variaveis: o remetente e o laravel_mailable ja instanciado e preenchido - Crie a fila ```php php artisan make:job EmailQueue ``` - A classe job ficará +- assim ```php <?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Support\Facades\Mail;// <<< use no Mail use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class EmailQueue implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; //attrs que recebem os dados que vem pelo construct protected $destinatario; protected $mailable; /** * Create a new job instance. * * @return void */ public function __construct($destinatario, $mailable) { //passando vars recebidas no construct para attrs do job $this->destinatario = $destinatario; $this->mailable = $mailable; } /** * Execute the job. * * @return void */ public function handle() { //aqui fica a logica do job Mail::to($this->destinatario)->send($this->mailable); } } ``` ## No controller instanciamos o job e damos um dispatch para mandar ele pra fila ### Instanciamos o job passando o que precisamos de variaveis para seu metodo dispatch() que jogara as vars passadas no construct do job ```php $data['token'] = '123'; //dados para criar o mailable $mailable = new App\Mail\EmailConfirmation($data); //criando mailable $destinatario = '<EMAIL>'; //destinatario do mailable App\Jobs\EmailQueue::dispatch($destinatario, $mailable); ->delay(now()->addSeconds(30)) //add um delay para execução apos cair na fila ->onQueue('emails') //escolhe a fila p colocar o job, se nenhuma for escolhida caira na fila default ``` ## Instanciamos um laravel-worker para tomar conta da fila ### O worker processa cada job que cair na fila, apagando os concluidos e mandando para a tabela failed_jobs aqueles que não puderam ser feitos por algum motivo ```php php artisan queue:work ``` <file_sep>/bs_configurar_accordion.md Como configurar corretamente o accordion bootstrap para se montar dinamicamente com os videos do bd - o id do panel-group que envolve tudo deve ser o mesmo do data-parent dos button do panel-title - o id do panel-collapse deve ser colocado em href e aria-controls do button do panel-title - o id do panel-heading deve ser colocado em aria-labelledby no panel-collapse <file_sep>/django/otimizacoes.md # Otimização de consultas django ```python # para pré carregar os objetos relacionados ('one_to_one') de um objeto 'pai' use a seguinte sintaxe pessoa = Pessoa.objects.select_related('cpf').get(id=1) # e ja teremos o objeto cpf que carrega a fk daquela pessoa acessivel em pessoa.cpf # para relação one_to_many utilize pessoa = Pessoa.objects.prefetch_related('carros').get(id=1) # e ja teremos todos os carros da pessoa acessivel no iteravel pessoa.carros ``` <file_sep>/django/django.md # Instalação basica de um projeto em python/django Para esse exemplo vamos usar _wttd_ como nome do diretorio de trabalho e _eventex_ como nome do projeto _Para facilitar sua vida crie o seguinte alias em seu bashrc ou zshrc_ alias manage='python $VIRTUAL_ENV/../manage.py' ## Criando o projeto crie a pasta do projeto e entre nela mkdir wttd cd wttd crie o venv # Como boa prática, utilizar o nome venv ou .venv python -m venv .venv ative o `venv` source .wttd/bin/activate instale o django pip install django inicialize o projeto django-admin startproject eventex . entre no projeto e crie a app núcleo do projeto cd eventex manage startapp core no arquivo _wttd/eventex/settings.py_ adicione a lista INSTALLED_APPS o app que vc acabou de criar para o projeto reconhecê-lo 'eventex.core', no arquivo _eventex/urls.py_ importe as views do core e adicione a rota que sera atendida por seu metodo **home** ```python import eventex.core.views ... path('', eventex.core.views.home), ``` no arquivo _eventex/core/views.py_ adicione o método que atenderá essa rota ```python def home(request): return render(request, 'index.html') ``` perceba que o metodo home chama o arquivo index.html que é um template, crie uma pasta _templates/_ dentro de _core/_ e coloque seu _index.html_ la ainda na pasta _core/_ crie a pasta _static/_ e coloque todos os arquivos estaticos dos quais seu template depende dentro dela nas chamadas para arquivos estaticos substitua o caminha relativo pela função static do python ```python para fins de exemplo substitua todas as strings do tipo "img/favicon.ico" por {% static 'img/favicon.ico' %} ``` ## separando configurações por instância e servindo arquivos estáticos de forma mais perfomática em _wttd/_ instale as dependencias ```python pip install python-decouple # desacopla as vars do settings para um .env pip install dj-database-url # ajuda a criar url de database a partir do .env pip install dj-static # serve os arquivos estaticos sem precisar passar pelo processamento pip install pillow # lib para/se trabalhar com upload e validação de imagens ``` configurar o arquivo settings.py e o arquivo .env #### arquivo _eventex/settings.py_ faça as substituições: ```python import os from decouple import config from dj_database_url import parse as dburl ALLOWED_HOSTS = ['*'] SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # pasta que receberá os estáticos do projeto MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') # pasta que receberá os uploads do projeto ``` #### arquivo _wttd/.env_ crie o arquivo .env na pasta raiz do projeto e adicione: SECRET_KEY=#coloque_aqui_sua_secret_key (sem espaços nem aspas) DEBUG=True #### arquivo _eventex/wsgi.py_ importe o Cling e envolva o get_wsgi_application() com ele ```python from dj_static import Cling ... application = Cling(get_wsgi_application()) ``` #### exportando as dependencias do projeto pip freeze > requirements.txt ## Preparando o projeto para o Heroku no _wttd/requirements.txt_ adicione as seguintes dependencias gunicorn==19.8.1 psycopg2==2.7.4 #### em _wttd/_ crie o arquivo Procfile com o seguinte conteudo web: gunicorn eventex.wsgi --log-file - ## Inicializando o repositório git em _wttd/_ git init ainda em _wttd/_ crie o arquivo .gitignore e adicione o seguinte conteudo .env //seu .env local .vscode //arquivos de sua ide .wttd //seu venv *.sqlite3 //bd de dev *.pyc //arquivos compilados __pycache__ //cache de arquivos compilados do python add o .gitignore a seu projeto, faça commit e em seguida adicione todo o resto ## criando uma app no heroku e colocando seu projeto no ar heroku apps:create eventex-petersonpassos heroku config:set SECRET_KEY='sua_key_entre_aspas_simples' heroku config:set DEBUG=False git push heroku master --force ## começando a trabalhar com banco de dados e o admin do django roda as migrations manage migrate crie o super usuário manage createsuperuser pronto, já pode acessar o admin do django em http://127.0.0.1:8000/admin/ <file_sep>/laravel/comandos_artisan.md ### criar projeto composer create-project laravel/laravel laravel-api ### listar rotas php artisan route:list ### criar controller php artisan make:controller \<ResourceName-Plural>Controller ### criar model php artisan make:model \<ResourceName-Singular> ### criar migration php artisan make:migration create\_\<ResourceName-Plural-minusculo>\_table --create=\<ResourceName-Plural-minusculo> ### terminal do projeto php artisan tinker <file_sep>/laravel/faker_laravel.md # Faker laravel Faker oferece um meio prático de criar dados falsos para pupular seus bancos de dados para teste, em qualquer lugar do laravel você pode gerar uma instancia em pt-BR da biblioteca faker fazendo: ```php $faker = Faker\Factory::create('pt_BR'); ``` Isso inclui o Laravel `tinker`. Caso precise testar, basta chamar o comando acima no shell do tinker. Uma vez gerada vc pode chamar os atributos dela mesmo dentro de um loop que sempre vai sair diferente. ## Principais tipos de dados ### Dados especificos para brasileiros ```php // Generates a random region name $faker->region; // 'Nordeste' // Generates a random region abbreviation $faker->regionAbbr; // 'NE' $faker->areaCode; // 21 $faker->cellphone; // 9432-5656 $faker->landline; // 2654-3445 $faker->phone; // random landline, 8-digit or 9-digit cellphone number // Using the phone functions with a false argument returns unformatted numbers $faker->cellphone(false); // 74336667 // cellphone() has a special second argument to add the 9th digit. Ignored if generated a Radio number $faker->cellphone(true, true); // 98983-3945 or 7343-1290 // Using the "Number" suffix adds area code to the phone $faker->cellphoneNumber; // (11) 98309-2935 $faker->landlineNumber(false); // 3522835934 $faker->phoneNumber; // formatted, random landline or cellphone (obeying the 9th digit rule) $faker->phoneNumberCleared; // not formatted, random landline or cellphone (obeying the 9th digit rule) // The name generator may include double first or double last names, plus title and suffix $faker->name; // 'Sr. <NAME>' // Valid document generators have a boolean argument to remove formatting $faker->cpf; // '145.343.345-76' $faker->cpf(false); // '45623467866' $faker->rg; // '84.405.736-3' $faker->rg(false); // '844057363' // Generates a Brazilian formatted and valid CNPJ $faker->cnpj; // '23.663.478/0001-24' $faker->cnpj(false); // '23663478000124' ``` ### Textos ```php $faker->text; // Dolores sit sint laboriosam dolorem culpa et autem. Beatae nam sunt fugit // et sit et mollitia sed. // Fuga deserunt tempora facere magni omnis. Omnis quia temporibus laudantium // sit minima sint. $faker->word // 'aut' $faker->words($nb = 3, $asText = false) // array('porro', 'sed', 'magni') $faker->sentence($nbWords = 6, $variableNbWords = true) // 'Sit vitae voluptas sint non voluptates.' $faker->sentences($nb = 3, $asText = false) // array('Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.') $faker->paragraph($nbSentences = 3, $variableNbSentences = true) // 'Ut ab voluptas sed a nam. Sint autem inventore aut officia aut aut blanditiis. Ducimus eos odit amet et est ut eum.' $faker->paragraphs($nb = 3, $asText = false) // array('Quidem ut sunt et quidem est accusamus aut. Fuga est placeat rerum ut. Enim ex eveniet facere sunt.', 'Aut nam et eum architecto fugit repellendus illo. Qui ex esse veritatis.', 'Possimus omnis aut incidunt sunt. Asperiores incidunt iure sequi cum culpa rem. Rerum exercitationem est rem.') $faker->text($maxNbChars = 200) // 'Fuga totam reiciendis qui architecto fugiat nemo. Consequatur recusandae qui cupiditate eos quod.' ``` ### Empresas ```php $faker->catchPhrase // 'Monitored regional contingency' $faker->bs // 'e-enable robust architectures' $faker->company // 'Bogan-Treutel' $faker->companySuffix // 'and Sons' $faker->jobTitle // 'Cashier' ``` ### Pessoas ```php $faker->title($gender = null|'male'|'female') // 'Ms.' $faker->titleMale // 'Mr.' $faker->titleFemale // 'Ms.' $faker->suffix // 'Jr.' $faker->name($gender = null|'male'|'female') // 'Dr. <NAME>' $faker->firstName($gender = null|'male'|'female') // 'Maynard' $faker->firstNameMale // 'Maynard' $faker->firstNameFemale // 'Rachel' $faker->lastName // 'Zulauf' ``` ### Endereços ```php $faker->cityPrefix // 'Lake' $faker->secondaryAddress // 'Suite 961' $faker->state // 'NewMexico' $faker->stateAbbr // 'OH' $faker->citySuffix // 'borough' $faker->streetSuffix // 'Keys' $faker->buildingNumber // '484' $faker->city // 'West Judge' $faker->streetName // 'Keegan Trail' $faker->streetAddress // '439 Karley Loaf Suite 897' $faker->postcode // '17916' $faker->address // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473' $faker->country // 'Falkland Islands (Malvinas)' $faker->latitude($min = -90, $max = 90) // 77.147489 $faker->longitude($min = -180, $max = 180) // 86.211205 ``` ### Datas ```php $faker->unixTime($max = 'now') // 58781813 $faker->dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC') $faker->dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris') $faker->iso8601($max = 'now') // '1978-12-09T10:10:29+0000' $faker->date($format = 'Y-m-d', $max = 'now') // '1979-06-09' $faker->time($format = 'H:i:s', $max = 'now') // '20:49:42' $faker->dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos') $faker->dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok') $faker->dateTimeThisCentury($max = 'now', $timezone = null) // DateTime('1915-05-30 19:28:21', 'UTC') $faker->dateTimeThisDecade($max = 'now', $timezone = null) // DateTime('2007-05-29 22:30:48', 'Europe/Paris') $faker->dateTimeThisYear($max = 'now', $timezone = null) // DateTime('2011-02-27 20:52:14', 'Africa/Lagos') $faker->dateTimeThisMonth($max = 'now', $timezone = null) // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok') $faker->amPm($max = 'now') // 'pm' $faker->dayOfMonth($max = 'now') // '04' $faker->dayOfWeek($max = 'now') // 'Friday' $faker->month($max = 'now') // '06' $faker->monthName($max = 'now') // 'January' $faker->year($max = 'now') // '1993' $faker->century // 'VI' $faker->timezone // 'Europe/Paris' ``` ### Internet ```php $faker->email // '<EMAIL>' $faker->safeEmail // '<EMAIL>' $faker->freeEmail // '<EMAIL>' $faker->companyEmail // '<EMAIL>' $faker->freeEmailDomain // 'yahoo.com' $faker->safeEmailDomain // 'example.org' $faker->userName // 'wade55' $faker->password // '<PASSWORD>[' $faker->domainName // 'wolffdeckow.net' $faker->domainWord // 'feeney' $faker->tld // 'biz' $faker->url // 'http://www.skilesdonnelly.biz/aut-accusantium-ut-architecto-sit-et.html' $faker->slug // 'aut-repellat-commodi-vel-itaque-nihil-id-saepe-nostrum' $faker->ipv4 // '192.168.127.12' $faker->localIpv4 // '10.242.58.8' $faker->ipv6 // 'fc00:db20:35b:7399::5' $faker->macAddress // '43:85:B7:08:10:CA' ``` ### Cartão de credito ```php $faker->creditCardType // 'MasterCard' $faker->creditCardNumber // '4485480221084675' $faker->creditCardExpirationDate // 04/13 $faker->creditCardExpirationDateString // '04/13' $faker->creditCardDetails // array('MasterCard', '4485480221084675', '<NAME>', '04/13') ``` ### Cores ```php $faker->hexcolor // '#fa3cc2' $faker->rgbcolor // '0,255,122' $faker->rgbColorAsArray // array(0,255,122) $faker->rgbCssColor // 'rgb(0,255,122)' $faker->safeColorName // 'fuchsia' $faker->colorName // 'Gainsbor' ``` ### Arquivos ```php $faker->fileExtension // 'avi' $faker->mimeType // 'video/x-msvideo' // Copy a random file from the source to the target directory and returns the fullpath or filename $faker->file($sourceDir = '/tmp', $targetDir = '/tmp') // '/path/to/targetDir/13b73edae8443990be1aa8f1a483bc27.jpg' $faker->file($sourceDir, $targetDir, false) // '13b73edae8443990be1aa8f1a483bc27.jpg' ``` ### Imagens ```php // Image generation provided by LoremPixel (http://lorempixel.com/) $faker->imageUrl($width = 640, $height = 480) // 'http://lorempixel.com/640/480/' $faker->imageUrl($width, $height, 'cats') // 'http://lorempixel.com/800/600/cats/' $faker->imageUrl($width, $height, 'cats', true, 'Faker') // 'http://lorempixel.com/800/400/cats/Faker' $faker->imageUrl($width, $height, 'cats', true, 'Faker', true) // 'http://lorempixel.com/grey/800/400/cats/Faker/' Monochrome image $faker->image($dir = '/tmp', $width = 640, $height = 480) // '/tmp/13b73edae8443990be1aa8f1a483bc27.jpg' $faker->image($dir, $width, $height, 'cats') // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat! $faker->image($dir, $width, $height, 'cats', false) // '13b73edae8443990be1aa8f1a483bc27.jpg' it's a filename without path $faker->image($dir, $width, $height, 'cats', true, false) // it's a no randomize images (default: `true`) $faker->image($dir, $width, $height, 'cats', true, true, 'Faker') // 'tmp/13b73edae8443990be1aa8f1a483bc27.jpg' it's a cat with 'Faker' text. Default, `null`. ``` ### Html ```php //Generate HTML document which is no more than 2 levels deep, and no more than 3 elements wide at any level. $faker->randomHtml(2,3) <html><head><title>Aut illo dolorem et accusantium eum.</title></head><body><form action="example.com" method="POST"><label for="username">sequi</label><input type="text" id="username"><label for="password">et</label><input type="password" id="password"></form><b>Id aut saepe non mollitia voluptas voluptas.</b><table><thead><tr><tr>Non consequatur.</tr><tr>Incidunt est.</tr><tr>Aut voluptatem.</tr><tr>Officia voluptas rerum quo.</tr><tr>Asperiores similique.</tr></tr></thead><tbody><tr><td>Sapiente dolorum dolorem sint laboriosam commodi qui.</td><td>Commodi nihil nesciunt eveniet quo repudiandae.</td><td>Voluptates explicabo numquam distinctio necessitatibus repellat.</td><td>Provident ut doloremque nam eum modi aspernatur.</td><td>Iusto inventore.</td></tr><tr><td>Animi nihil ratione id mollitia libero ipsa quia tempore.</td><td>Velit est officia et aut tenetur dolorem sed mollitia expedita.</td><td>Modi modi repudiandae pariatur voluptas rerum ea incidunt non molestiae eligendi eos deleniti.</td><td>Exercitationem voluptatibus dolor est iste quod molestiae.</td><td>Quia reiciendis.</td></tr><tr><td>Inventore impedit exercitationem voluptatibus rerum cupiditate.</td><td>Qui.</td><td>Aliquam.</td><td>Autem nihil aut et.</td><td>Dolor ut quia error.</td></tr><tr><td>Enim facilis iusto earum et minus rerum assumenda quis quia.</td><td>Reprehenderit ut sapiente occaecati voluptatum dolor voluptatem vitae qui velit.</td><td>Quod fugiat non.</td><td>Sunt nobis totam mollitia sed nesciunt est deleniti cumque.</td><td>Repudiandae quo.</td></tr><tr><td>Modi dicta libero quisquam doloremque qui autem.</td><td>Voluptatem aliquid saepe laudantium facere eos sunt dolor.</td><td>Est eos quis laboriosam officia expedita repellendus quia natus.</td><td>Et neque delectus quod fugit enim repudiandae qui.</td><td>Fugit soluta sit facilis facere repellat culpa magni voluptatem maiores tempora.</td></tr><tr><td>Enim dolores doloremque.</td><td>Assumenda voluptatem eum perferendis exercitationem.</td><td>Quasi in fugit deserunt ea perferendis sunt nemo consequatur dolorum soluta.</td><td>Maxime repellat qui numquam voluptatem est modi.</td><td>Alias rerum rerum hic hic eveniet.</td></tr><tr><td>Tempore voluptatem.</td><td>Eaque.</td><td>Et sit quas fugit iusto.</td><td>Nemo nihil rerum dignissimos et esse.</td><td>Repudiandae ipsum numquam.</td></tr><tr><td>Nemo sunt quia.</td><td>Sint tempore est neque ducimus harum sed.</td><td>Dicta placeat atque libero nihil.</td><td>Et qui aperiam temporibus facilis eum.</td><td>Ut dolores qui enim et maiores nesciunt.</td></tr><tr><td>Dolorum totam sint debitis saepe laborum.</td><td>Quidem corrupti ea.</td><td>Cum voluptas quod.</td><td>Possimus consequatur quasi dolorem ut et.</td><td>Et velit non hic labore repudiandae quis.</td></tr></tbody></table></body></html> ``` <file_sep>/django/tests.md classe exemplo de teste ```python from django.test import TestCase # Create your tests here. class HomeTest(TestCase): # o metódo setUp roda automaticamente antes de cada teste e colocar as # vars que vc vai precisar dentro de self é a forma de vc torna-la global na classe def setUp(self): # o client é uma ferramenta do django capaz de fazer requests no projeto para fins de teste self.response = self.client.get('/') def test_get(self): """GET / must return code 200""" # docstring serve para descrever o teste self.assertEqual(200, self.response.status_code) # é igual? def test_template(self): """Must use subscription_form.html""" self.assertTemplateUsed( self.response, 'subscription_form.html') # é esse template usado? def test_html(self): """Html must contain tags""" self.assertContains(self.response, '<form') self.assertContains(self.response, '<input', 6) # contem isso no html? esse numerop de vezes? self.assertContains(self.response, 'type="text"', 3) self.assertContains(self.response, 'type="email"') self.assertContains(self.response, 'type="submit"') def test_csrf_token(self): """Html must contain csrf token""" self.assertContains(self.response, 'csrfmiddlewaretoken') ``` <file_sep>/django/setup.md # Setup inicial do ambiente de trabalho Você precisará das seguintes ferramentas: - python virtualenv - python pip Dependendo da versão do Python que irá utilizar, o nome do pacote em sua distribuiçao muda também. No Ubuntu Linux, instale utilizando o `apt` ```shell apt install python-virtualenv python-pip ``` Caso esteja utilizando o Python3, instale da seguinte forma: ```shell apt install python3-virtualenv python3-pip ```
89a19d030c56fe9985ddffe0efc1be744e4f5ad3
[ "Markdown", "PHP" ]
24
Markdown
eluminatis/roteiros
11ac1b28e94c067b7d414c66e5285c8e1e2c5566
6cac94d4d06ef27ba95c2c2f8e49fb70023381e2
refs/heads/master
<repo_name>fbourelle/first_project_ionic<file_sep>/src/components/components.module.ts import { NgModule } from '@angular/core'; import { CustomBarComponent } from './custom-bar/custom-bar'; @NgModule({ declarations: [CustomBarComponent], imports: [], exports: [CustomBarComponent] }) export class ComponentsModule {} <file_sep>/src/models/PersonnageModel.ts export class Personnage { public _name: string ; public _function: string ; public _avatar: string; constructor(name: string, fonction: string, avatar: string) { this._name = name; this._function = fonction; this._avatar = avatar; } } <file_sep>/src/pages/celibrity/celibrity.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { DestinationPage } from '../destination/destination'; import { PersonnagePage } from '../personnage/personnage'; /** * Generated class for the CelibrityPage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-celibrity', templateUrl: 'celibrity.html', }) export class CelibrityPage { nextPage = DestinationPage; nextPage2 = PersonnagePage; constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { console.log('ionViewDidLoad CelibrityPage'); } findCard() { this.navCtrl.push(DestinationPage); } } <file_sep>/src/pages/personnage/personnage.ts import { Component, Injectable } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular'; import { AddpersonnagePage } from '../addpersonnage/addpersonnage' import { DestinationPage } from '../destination/destination' import { AlertController } from 'ionic-angular'; import { PersonnagesProvider } from '../../providers/personnages/personnages'; import { Groupe } from '../../models/GroupeModels'; /** * Generated class for the PersonnagePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-personnage', templateUrl: 'personnage.html', }) export class PersonnagePage { addPage = AddpersonnagePage; nextPage = DestinationPage; personnages = []; name = String; people: any = []; constructor(public personnagesProviders: PersonnagesProvider, public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public alertCtrl: AlertController) { this.name = navParams.get("name"); this.personnagesProviders.getPeople().then(data => { this.people = data; }); } ionViewDidLoad() { console.log('ionViewDidLoad PersonnagePage'); } showPrompt() { let prompt = this.alertCtrl.create({ title: 'Personnage', message: "Enter a name", inputs: [ { name: 'title', placeholder: 'Title' }, ], buttons: [ { text: 'Cancel', handler: data => { console.log('Cancel clicked'); } }, { text: 'Save', handler: data => { this.personnages.push(data.title); } } ] }); prompt.present(); } showPromptUpdate(i) { let prompt = this.alertCtrl.create({ title: 'Update Personnage', message: "Enter a new name", inputs: [ { name: 'title', placeholder: 'Enter a new name' }, ], buttons: [ { text: 'Cancel', handler: data => { console.log('Cancel clicked'); } }, { text: 'Save', handler: data => { this.personnages.splice(i, 1, data.title); } } ] }); prompt.present(); } getToast(message) { let toast = this.toastCtrl.create({ message: message, duration: 3000 }); toast.present(); } suppPerso(index) { let message = "Personnage " + this.personnages[index] + " supprimé" this.personnages.splice(index, 1); this.getToast(message); } addPersonnage() { this.personnages.push(); } editPersonnage(index) { this.navCtrl.push(AddpersonnagePage, { name: this.personnages[index] }) } onAction() { this.personnagesProviders.envoyer(); } } <file_sep>/src/pages/addpersonnage/addpersonnage.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { AlertController } from 'ionic-angular'; import { PersonnagePage } from '../personnage/personnage'; /** * Generated class for the AddpersonnagePage page. * * See https://ionicframework.com/docs/components/#navigation for more info on * Ionic pages and navigation. */ @IonicPage() @Component({ selector: 'page-addpersonnage', templateUrl: 'addpersonnage.html', }) export class AddpersonnagePage { public name; constructor(public navCtrl: NavController, public navParams: NavParams ) { this.name = navParams.get("name"); } // logForm(form) { // console.log(form.value) // this.navCtrl.pop(); // } sendParam() { this.navCtrl.push(PersonnagePage, { name: this.name }) } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { SplashScreen } from '@ionic-native/splash-screen'; import { StatusBar } from '@ionic-native/status-bar'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { CelibrityPage } from '../pages/celibrity/celibrity'; import { DestinationPage } from '../pages/destination/destination'; import { PersonnagePage } from '../pages/personnage/personnage'; import { AddpersonnagePage } from '../pages/addpersonnage/addpersonnage'; import { CustomBarComponent } from '../components/custom-bar/custom-bar'; @NgModule({ declarations: [ MyApp, HomePage, CelibrityPage, DestinationPage, PersonnagePage, AddpersonnagePage, CustomBarComponent ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, CelibrityPage, DestinationPage, PersonnagePage, AddpersonnagePage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler} ], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class AppModule {} <file_sep>/src/providers/personnages/personnages.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Personnage } from '../../models/PersonnageModel'; import { Groupe } from '../../models/GroupeModels'; import { Subject } from 'rxjs/Subject'; /* Generated class for the PersonnagesProvider provider. See https://angular.io/guide/dependency-injection for more info on providers and Angular DI. */ @Injectable() export class PersonnagesProvider { modeleSubject = new Subject<Groupe>(); public perso1 = new Personnage("Eugénie", "<NAME>", "avatar_1.jpg"); public perso2 = new Personnage("Louise", "Infirmière", "avatar_2.jpg"); public perso3 = new Personnage("Agathe", "Modèle", "avatar_3.jpg"); public modele = new Groupe([this.perso1, this.perso2, this.perso3]); apiUrl = 'https://bonnard-17c91.firebaseio.com/'; constructor(public httpClient: HttpClient) {} emitMusiqueSubject() { this.modeleSubject.next(this.modele); } getModele(){ return this.modele; } getPeople() { let people = new Promise(resolve => { this.httpClient.get(this.apiUrl).subscribe(data => { resolve(data); }, err => { console.log(err); }); }); return people; } envoyer() { this.httpClient.put(this.apiUrl + '/tableau.json', this.modele) .subscribe( () => { console.log('ok'); }, (error) => { console.log('error'); } ); } postPerson(groupe: Groupe) { return new Promise((resolve, reject) => { // this.http.post(this.apiUrl + 'users/', JSON.stringify(person), { this.http.post(this.apiUrl, JSON.stringify(groupe), { // Si votre API nécessite des headers et paramètres additionnels // headers: new HttpHeaders().set('Authorization', 'my-auth-token'), // params: new HttpParams().set('id', '3'), }).subscribe(data => { resolve(data); }, (err) => { reject(err); }); }); } } <file_sep>/src/models/GroupeModels.ts import { Personnage } from "./PersonnageModel"; export class Groupe { public _tab_personnages: Personnage[]; constructor(tab_personnages) { this._tab_personnages = tab_personnages; } } <file_sep>/src/components/custom-bar/custom-bar.ts import { Component, Input } from '@angular/core'; /** * Generated class for the CustomBarComponent component. * * See https://angular.io/api/core/Component for more info on Angular * Components. */ @Component({ selector: 'custom-bar', templateUrl: 'custom-bar.html' }) export class CustomBarComponent { @Input('progression') progress; text: string; constructor() { console.log('Hello CustomBarComponent Component'); } increaseProgress() { if (this.progress < 100) this.progress += 5; console.log ("la barre progresse de ", this.progress); } }
3534d8e09268d882d9c1123040ccc58c8c11ab5a
[ "TypeScript" ]
9
TypeScript
fbourelle/first_project_ionic
4a4eeec463a91a1e68b23ca41b76693d5fcbea5e
af9abe12bdc18a69367e5ea89824c17f8a8de7f1
refs/heads/master
<file_sep>#include<stdio.h> #include<conio.h> void main() { char a[20]; int i=0,count=0,count1=0,count2=0; clrscr(); printf('Enter the string"); scanf("%s",a); while(a[i] != '\0') { if((a[i] >= 'a' && a[i] =< 'z') || (a[i] >= 'A' && a[i] =< 'Z')) { count++; } else if(a[i] => '0' && a[i] =< '9') { count1++; } else { count2++; } i++; } printf("The number os characters in string is %d",count); printf("The number of numbers in string is %d",count1); printf("The number of alphanumerics in string is %d",count2++); getch(); }
dd47c7b8564350f0b13b6b39671fe343fa36cec7
[ "C" ]
1
C
akilayuva/cprogramm
41c07faddb6cc49ade96eb037f96f25802610581
4a6f252873f74915bfe5828fd023b477542f3f71
refs/heads/master
<file_sep># Weathermap from MEPS latest runs ... can be adjusted to the archived forecasts: - MEPS latest: https://thredds.met.no/thredds/catalog/mepslatest/catalog.html - MEPS archive: https://thredds.met.no/thredds/catalog/meps25epsarchive/catalog.html - AROME Arctic latest: https://thredds.met.no/thredds/catalog/aromearcticlatest/catalog.html - AROME Arctic archive: https://thredds.met.no/thredds/catalog/aromearcticarchive/catalog.html ## HOW TO CITE Hellmuth, Franziska, <NAME> (2019), Weathermaps from MEPS latest runs, University of Oslo, Oslo, Norway. Contact: <EMAIL> ## Necessary Python 3.7 packages - jupyter - jupyterlab - numpy - pandas - matplotlib - basemap - netcdf4 - xarray - cartopy ## Weathermaps created: ### 700hPa humidity Needed variables from the Met-NO files: - geopotential_pl - air_temperature_pl - relative_humidity_pl ### Jet-Thickness-MSLP Needed variables from the Met-NO files: - x_wind_pl - y_wind_pl - air_pressure_at_sea_level - lwe_thickness_of_atmosphere_mass_content_of_water_vapor ### 850hP-Temperature-Wind Needed variables from the Met-NO files: - air_temperature_pl - x_wind_pl - y_wind_pl <file_sep># --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # https://gist.github.com/ajdawson/dd536f786741e987ae4e from copy import copy import cartopy.crs as ccrs import numpy as np import shapely.geometry as sgeom import matplotlib.pyplot as plt import matplotlib.colors as colors from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER import os ### Define colorbar colors champ = 255. # tot. precipitable water (grey scale) no1 = np.array([255,255,255])/champ no2 = np.array([231,231,231])/champ no3 = np.array([201,201,201])/champ no4 = np.array([171,171,171])/champ no5 = np.array([140,140,140])/champ no6 = np.array([110,110,110])/champ no7 = np.array([80,80,80])/champ # 250 hPa wind speed (colored scale) no11 = np.array([255,255,255])/champ no12 = np.array([196,225,255])/champ no13 = np.array([131,158,255])/champ no14 = np.array([255,209,177])/champ no15 = np.array([255,118,86])/champ no16 = np.array([239,102,178])/champ no17 = np.array([243,0,146])/champ def createFolder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Error: Creating directory. ' + directory) def find_yx(lat, lon, point_lat, point_lon): abs_lat = abs(lat - point_lat) abs_lon = abs(lon - point_lon) c = np.maximum(abs_lat, abs_lon) y, x = np.where(c == c.min()) y = y[0] x = x[0] xx = lat[y, x].x yy = lon[y, x].y return(xx, yy) def find_side(ls, side): """ Given a shapely LineString which is assumed to be rectangular, return the line corresponding to a given side of the rectangle. """ minx, miny, maxx, maxy = ls.bounds points = {'left': [(minx, miny), (minx, maxy)], 'right': [(maxx, miny), (maxx, maxy)], 'bottom': [(minx, miny), (maxx, miny)], 'top': [(minx, maxy), (maxx, maxy)],} return sgeom.LineString(points[side]) def lambert_xticks(ax, ticks): """Draw ticks on the bottom x-axis of a Lambert Conformal projection.""" te = lambda xy: xy[0] lc = lambda t, n, b: np.vstack((np.zeros(n) + t, np.linspace(b[2], b[3], n))).T xticks, xticklabels = _lambert_ticks(ax, ticks, 'bottom', lc, te) ax.xaxis.tick_bottom() ax.set_xticks(xticks) ax.set_xticklabels([ax.xaxis.get_major_formatter()(xtick) for xtick in xticklabels]) def lambert_yticks(ax, ticks): """Draw ricks on the left y-axis of a Lamber Conformal projection.""" te = lambda xy: xy[1] lc = lambda t, n, b: np.vstack((np.linspace(b[0], b[1], n), np.zeros(n) + t)).T yticks, yticklabels = _lambert_ticks(ax, ticks, 'left', lc, te) ax.yaxis.tick_left() ax.set_yticks(yticks) ax.set_yticklabels([ax.yaxis.get_major_formatter()(ytick) for ytick in yticklabels]) def _lambert_ticks(ax, ticks, tick_location, line_constructor, tick_extractor): """Get the tick locations and labels for an axis of a Lambert Conformal projection.""" outline_patch = sgeom.LineString(ax.outline_patch.get_path().vertices.tolist()) axis = find_side(outline_patch, tick_location) n_steps = 30 extent = ax.get_extent(ccrs.PlateCarree()) _ticks = [] for t in ticks: xy = line_constructor(t, n_steps, extent) proj_xyz = ax.projection.transform_points(ccrs.Geodetic(), xy[:, 0], xy[:, 1]) xyt = proj_xyz[..., :2] ls = sgeom.LineString(xyt.tolist()) locs = axis.intersection(ls) if not locs: tick = [None] else: tick = tick_extractor(locs.xy) _ticks.append(tick[0]) # Remove ticks that aren't visible: ticklabels = copy(ticks) while True: try: index = _ticks.index(None) except ValueError: break _ticks.pop(index) ticklabels.pop(index) return _ticks, ticklabels def plt_Jet_Thick_MSLP(fnx, u_250, mslp, Z_thickness, pw, andenes_x, andenes_y): projection = ccrs.LambertConformal(central_longitude =fnx.projection_lambert.longitude_of_central_meridian, central_latitude =fnx.projection_lambert.latitude_of_projection_origin, standard_parallels = fnx.projection_lambert.standard_parallel) f, ax = plt.subplots(subplot_kw={'projection' : projection}, ) #ax.set_title('Ensemble mean %s')# %s' %(_dm.time)) ax.coastlines(resolution = '50m') ################################################### levels_u = np.arange(40,120,10) levels_th1 = np.arange(402,546,6) levels_th2 = np.arange(546,650,6) levels_p = np.arange(800,1100,4) # levels_pw = np.arange(22,78,8) # levels_pw = np.arange(14,62,8) levels_pw = np.arange(0,62,8) ################################################### # Plot contour lines for 250-hPa wind and fill U_map = colors.ListedColormap([no11, no12, no13, no14, no15, no16, no17]) norm = colors.BoundaryNorm(boundaries = levels_u, ncolors=U_map.N) _U_250 = u_250.plot.pcolormesh(ax = ax, transform = projection, levels = levels_u, cmap = U_map, norm = norm, add_colorbar = False, extend = 'both' ) cb_U_250 = plt.colorbar(_U_250, ax=ax, orientation="vertical",extend='both', shrink = 0.5) cb_U_250.set_label(label='250$\,$hPa Wind (m$\,$s$^{-1}$)', #size='large', weight='bold') ################################################### # Plot MSL pressure every 4 hPa CS_p = mslp.plot.contour(ax = ax, transform = projection, levels = levels_p, colors = 'k', linewidths = 1.8) ax.clabel(CS_p, levels_p[::2], inline=1, fmt='%1.0f', #fontsize=10 ) ################################################### # Plot the 1000-500 hPa thickness CS_th1 = Z_thickness.where(Z_thickness < 546).plot.contour(ax = ax, transform = projection, levels = levels_th1, colors = 'b', linewidths = 2., linestyles = '--') ax.clabel(CS_th1, levels_th1, inline = 1, fmt = '%1.0f') try: CS_th2 = Z_thickness.plot.contour(ax = ax, transform = projection, levels = levels_th2, colors = 'r', linewidths = 2., linestyles = '--') ax.clabel(CS_th2, levels_th2, inline = 1, fmt = '%1.0f') except (ValueError): pass # labels = ['line1'] # CS_th1.collections[0].set_label(labels[0]) # plt.legend(bbox_to_anchor=(1.1, 1.05)) ################################################### # Plot contourf for precipitable water PW_map = colors.ListedColormap([no1, no2, no3, no4, no5, no6, no7]) PW_norm = colors.BoundaryNorm(boundaries = levels_pw, ncolors=PW_map.N) _PW = pw.plot.pcolormesh(ax = ax, transform = projection, levels = levels_u, cmap = PW_map, norm = PW_norm, add_colorbar = False, extend = 'both' ) cb_PW = plt.colorbar(_PW, ax=ax, orientation="vertical",extend='both', shrink = 0.5) cb_PW.set_label(label='Precipitable water (m)', #size='large', weight='bold') ################################################### ax.plot([andenes_x], [andenes_y], color = 'red', marker = "^", transform=projection, markersize = 22 ) ################################################### map_design(f,ax) def plt_700_humidity(fnx, geop, temp, RH,andenes_x, andenes_y): projection = ccrs.LambertConformal(central_longitude =fnx.projection_lambert.longitude_of_central_meridian, central_latitude =fnx.projection_lambert.latitude_of_projection_origin, standard_parallels = fnx.projection_lambert.standard_parallel) f, ax = plt.subplots(subplot_kw={'projection' : projection}, ) #ax.set_title('Ensemble mean %s')# %s' %(_dm.time)) ax.coastlines(resolution = '50m') ################################################### # Geopotential levels_g = np.arange(200,300,4) levels_T = np.arange(temp.min(), temp.max(),2) CS_g = geop.plot.contour(ax = ax, transform = projection, levels = levels_g, colors = 'k', linewidths=2) ax.clabel(CS_g, levels_g[::2], inline=1, fmt='%1.0f', #fontsize=10 ) ################################################### # Temperature CS_T = temp.plot.contour(ax = ax, transform = projection, levels = levels_T, #vmin=-40, vmax=10, cmap=plt.get_cmap('plasma'), linewidths=2, # extend='both', add_colorbar = False) ax.clabel(CS_T, inline = 1, fmt ='%1.0f',) cb_T = plt.colorbar(CS_T,ax = ax, format ='%1.0f', orientation = 'vertical', #extend = 'both', shrink = 0.5) cb_T.lines[0].set_linewidth(25) cb_T.set_label(label='Temperature ($^{o}C$)', #size='large', weight='bold') #cb_T.ax.tick_params(labelsize='large') ################################################### # relative Humidity CS_rh = RH.where(RH >= 70.).plot.pcolormesh(ax = ax, transform = projection, levels = np.arange(70,110,10), cmap = plt.get_cmap('YlGn'), # extend = 'both', add_colorbar = False) cb_rh = plt.colorbar(CS_rh, orientation="vertical",#extend='both', shrink = 0.5) cb_rh.set_label(label='Relative humidity (%)', #size='large', weight='bold') #cb_rh.ax.tick_params(labelsize='large') ################################################### ax.plot([andenes_x], [andenes_y], color = 'red', marker = "^", transform=projection, markersize = 22 ) ################################################### map_design(f,ax) def plt_temp_wind_850(fnx, temp, u_wind, v_wind, XX, YY, andenes_x, andenes_y): projection = ccrs.LambertConformal(central_longitude =fnx.projection_lambert.longitude_of_central_meridian, central_latitude =fnx.projection_lambert.latitude_of_projection_origin, standard_parallels = fnx.projection_lambert.standard_parallel) f, ax = plt.subplots(subplot_kw={'projection' : projection}, ) #ax.set_title('Ensemble mean %s')# %s' %(_dm.time)) ax.coastlines(resolution = '50m') ################################################### # Temperature levels_T = np.arange(-30, 31) ################################################### # Temperature CB_T = temp.plot.pcolormesh(ax = ax, transform = projection, levels = levels_T[::2], cmap=plt.get_cmap('BrBG_r'), extend='both', add_colorbar = False ) cb_T = plt.colorbar(CB_T,orientation="vertical",#extend='both', shrink = 0.5) cb_T.set_label(label='Temperature ($^{o}C$)', #size='large', weight='bold') ##### CS_T = temp.plot.contour(ax = ax, transform = projection, levels = levels_T[::5], colors = 'k', linewidths = 2, linestyles = '-') ax.clabel(CS_T, levels_T[::5], inline=1, fmt='%1.0f', ) ##### CS_T2 = temp.plot.contour(ax = ax, transform = projection, levels = np.array([ -38, -36, -34, -32, -28, -26, -24, -22, -18, -16, -14, -12, -8, -6, -4, -2, 2, 4, 6, 8, 12, 14, 16, 18, 22, 24, 26, 28, 32, 34, 36, 38, ]), colors = 'lightgray', linewidths = 1.2, linestyles = '--') ################################################### # Wind barbs ax.barbs(XX[::70,::70], YY[::70,::70], u_wind[::70,::70], v_wind[::70,::70], barbcolor=[0.31372549, 0.31372549, 0.31764706]) ################################################### ax.plot([andenes_x], [andenes_y], color = 'red', marker = "^", transform=projection, markersize = 22 ) map_design(f,ax) ################################################### def map_design(f, ax,): # *must* call draw in order to get the axis boundary used to add ticks: f.canvas.draw() # Define gridline locations and draw the lines using cartopy's built-in gridliner: xticks = [-110, -50, -40, -30, -20, -11, 0, 10, 20, 30, 40, 50] yticks = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80] ax.gridlines(xlocs=xticks, ylocs=yticks) #ax.add_feature(cy.feature.OCEAN) #ax.add_feature(cy.feature.LAND) # Label the end-points of the gridlines using the custom tick makers: ax.xaxis.set_major_formatter(LONGITUDE_FORMATTER) ax.yaxis.set_major_formatter(LATITUDE_FORMATTER) lambert_xticks(ax, xticks) lambert_yticks(ax, yticks) ax.set_xlabel('Longitude') ax.set_ylabel('Latitude') plt.tight_layout(); <file_sep># -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.4.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pysftp import xarray as xr import numpy as np #import cartopy as cy import matplotlib.pyplot as plt from datetime import datetime #from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER import functions as fct # %load_ext autoreload # %autoreload 2 # + active="" # srv = pysftp.Connection(host="sftp://[email protected]/uio/kant/geo-metos-u1/franzihe/", username="franzihe", private_key="/home/franzihe/.ssh/id_rsa") # - # Set figure size for all our plots plt.rcParams['figure.figsize'] = [10., 8.] plt.rcParams['font.family'] = 'sans-serif' plt.rcParams.update({'font.size': 22}) # datetime object containing current date and time # needed if used latest now = datetime.now() # dd/mm/YY H:M:S date = now.strftime("%Y%m%d") time = now.strftime('%H') print("date and time =", date, time) ini_time = '00' # + savefig = 0 # 1=yes, 0=no form = 'png' # File direction where figures should be saved (to be changed) #figdir = 'sftp://[email protected]/uio/kant/geo-metos-u1/franzihe/www_docs' figdir = '/home/franzihe/Documents/Figures/Weathermaps' # + # Pick out area around 400km to Andenes # Andøya Space Center Coordinates: 69.2950N, 16.0300E # to be changed to the location of interest, define the lower left latitude and longitude, # upper right corner latitude and longitude #andenes_lat = 69.2950; andenes_lon = 16.03 #lower_lat = 65.69; lower_lon = 5.8 #upper_lat = 72.9; upper_lon = 26.26 #lower_lat = 65.; lower_lon = 1.24 #upper_lat = 75; upper_lon = 26.26 # - # Nordmela Coordinates: 69.1358N, 15.6776E andenes_lat = 69.135840; andenes_lon = 15.677645 lower_lat = 64.83; lower_lon = 0.98 upper_lat = 74.85; upper_lon = 25.85 # + # Open the netCDF file containing the input data. # MEPS forecasts (Norway without Svalbard) from recent initialisations: https://thredds.met.no/thredds/catalog/mepslatest/catalog.html # AROME Arctic forecast (Arctic including Svalbard) can be found in the # archive: https://thredds.met.no/thredds/catalog/aromearcticarchive/catalog.html # latests: https://thredds.met.no/thredds/catalog/aromearcticlatest/catalog.html #thredds = 'https://thredds.met.no/thredds/dodsC/mepslatest/meps_det_2_5km_%sT%sZ.ncml' %(date, ini_time) # deterministic forecast year = '2019' month = '09' day = '27' date = year+month+day thredds = 'https://thredds.met.no/thredds/dodsC/aromearcticarchive/%s/%s/%s/arome_arctic_extracted_2_5km_%sT%sZ.nc' %(year, month, day, date, ini_time) fnx = xr.open_dataset(thredds, decode_times = True, use_cftime = True) # - lower_x, lower_y = fct.find_yx(fnx.latitude, fnx.longitude, lower_lat, lower_lon) upper_x, upper_y = fct.find_yx(fnx.latitude, fnx.longitude, upper_lat, upper_lon) andenes_x, andenes_y = fct.find_yx(fnx.latitude, fnx.longitude, andenes_lat, andenes_lon) # + active="" # forecast_in_hours = '03' # + for forecast_in_hours in range(0,39,3): if forecast_in_hours < 10: forecast_in_hours = '0%s' %forecast_in_hours # print(int(forecast_in_hours)) fig_name = 'meps_2_5_km_%sT%sZ_%s.%s' %(date,ini_time,forecast_in_hours, form) ################################################################################# map_area = 'Andoya' ################################################################################# ### 700hP - Temp - RH fct.plt_700_humidity(fnx, fnx.geopotential_pl.sel(pressure = 700., x = slice(lower_x, upper_x), y = slice(lower_y, upper_y)).isel(time=int(forecast_in_hours))/100, fnx.air_temperature_pl.sel(pressure = 700., x = slice(lower_x, upper_x), y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours)) - 273.15, fnx.relative_humidity_pl.sel(pressure = 700., x = slice(lower_x, upper_x), y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours))*100, andenes_x, andenes_y) if savefig == 1: fct.createFolder('%s/700hPa_RH_T/%s/' %(figdir,map_area)) plt.savefig('%s/700hPa_RH_T/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True) print('plot saved: %s/700hPa_RH_T/%s/%s' %(figdir, map_area, fig_name)) plt.close() ################################################################################# # convert Geopotential to height # https://en.wikipedia.org/wiki/Geopotential a = 6.378*10**6 # average radius of the earth [m] G = 6.673*10**(-11) # gravitational constant [Nm2/kg2] ma = 5.975*10**24 # mass of the earth [kg] Z_1000 = (-a**2 * fnx.geopotential_pl.sel(pressure = 1000.,).isel(time = int(forecast_in_hours)))/\ (a * fnx.geopotential_pl.sel(pressure = 1000.,).isel(time = int(forecast_in_hours)) - G * ma) Z_500 = (-a**2 * fnx.geopotential_pl.sel(pressure = 500.,).isel(time = int(forecast_in_hours)))/\ (a * fnx.geopotential_pl.sel(pressure = 500.,).isel(time = int(forecast_in_hours)) - G * ma) Z_thickness = (Z_500 - Z_1000)/10 ######################################## ### Jet - Thickness - MSLP fct.plt_Jet_Thick_MSLP(fnx, np.sqrt(fnx.x_wind_pl.sel(pressure = 250.,x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours))**2 + \ fnx.y_wind_pl.sel(pressure = 250.,x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours))**2), fnx.air_pressure_at_sea_level.sel(height_above_msl = 0, x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours))/100, Z_thickness.sel(x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)), fnx.lwe_thickness_of_atmosphere_mass_content_of_water_vapor.sel(surface = 0, x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours)), andenes_x, andenes_y) if savefig == 1: fct.createFolder('%s/MSLP_Thickness_Jet/%s/' %(figdir,map_area)) plt.savefig('%s/MSLP_Thickness_Jet/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True) print('plot saved: %s/MSLP_Thickness_Jet/%s/%s' %(figdir, map_area, fig_name)) plt.close() ################################################################################# ### 850hP - temperature - wind XX, YY = np.meshgrid(fnx.x.sel(x = slice(lower_x, upper_x)), fnx.y.sel(y = slice(lower_y, upper_y))) fct.plt_temp_wind_850(fnx, fnx.air_temperature_pl.sel(pressure = 850.,x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours)) - 273.15, fnx.x_wind_pl.sel(pressure = 850.,x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours)), fnx.y_wind_pl.sel(pressure = 850.,x = slice(lower_x, upper_x),y = slice(lower_y, upper_y)).isel(time = int(forecast_in_hours)), XX, YY, andenes_x, andenes_y) if savefig == 1: fct.createFolder('%s/850hPa_U_T/%s/' %(figdir,map_area)) plt.savefig('%s/850hPa_U_T/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True) print('plot saved: %s/850hPa_U_T/%s/%s' %(figdir, map_area, fig_name)) plt.close() ################################################################################# map_area = 'Norway' ################################################################################# ### 700hP - Temp - RH fct.plt_700_humidity(fnx, fnx.geopotential_pl.sel(pressure = 700.,).isel(time=int(forecast_in_hours))/100, fnx.air_temperature_pl.sel(pressure = 700.,).isel(time = int(forecast_in_hours)) - 273.15, fnx.relative_humidity_pl.sel(pressure = 700.,).isel(time = int(forecast_in_hours))*100, andenes_x, andenes_y) if savefig == 1: fct.createFolder('%s/700hPa_RH_T/%s/' %(figdir,map_area)) plt.savefig('%s/700hPa_RH_T/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True) print('plot saved: %s/700hPa_RH_T/%s/%s' %(figdir, map_area, fig_name)) plt.close() ################################################################################# fct.plt_Jet_Thick_MSLP(fnx, np.sqrt(fnx.x_wind_pl.sel(pressure = 250.,).isel(time = int(forecast_in_hours))**2 + fnx.y_wind_pl.sel(pressure = 250.,).isel(time = int(forecast_in_hours))**2), fnx.air_pressure_at_sea_level.sel(height_above_msl = 0).isel(time = int(forecast_in_hours))/100, Z_thickness, fnx.lwe_thickness_of_atmosphere_mass_content_of_water_vapor.sel(surface = 0).isel(time = int(forecast_in_hours)), andenes_x, andenes_y) if savefig == 1: fct.createFolder('%s/MSLP_Thickness_Jet/%s/' %(figdir,map_area)) plt.savefig('%s/MSLP_Thickness_Jet/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True) print('plot saved: %s/MSLP_Thickness_Jet/%s/%s' %(figdir, map_area, fig_name)) plt.close() ################################################################################# XX, YY = np.meshgrid(fnx.x, fnx.y) fct.plt_temp_wind_850(fnx, fnx.air_temperature_pl.sel(pressure = 850,).isel(time = int(forecast_in_hours)) - 273.15, fnx.x_wind_pl.sel(pressure = 850,).isel(time = int(forecast_in_hours)), fnx.y_wind_pl.sel(pressure = 850,).isel(time = int(forecast_in_hours)), XX, YY, andenes_x, andenes_y) if savefig == 1: fct.createFolder('%s/850hPa_U_T/%s/' %(figdir,map_area)) plt.savefig('%s/850hPa_U_T/%s/%s' %(figdir, map_area, fig_name), format = form, bbox_inches='tight', transparent=True) print('plot saved: %s/850hPa_U_T/%s/%s' %(figdir, map_area, fig_name)) plt.close() # - fnx.close() <file_sep>import xarray as xr import metpy as mp from datetime import datetime import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.interpolate import cross_section forecast_in_hours = 12 ini_time = '09' # datetime object containing current date and time now = datetime.now() # dd/mm/YY H:M:S date = now.strftime("%Y%m%d") time = now.strftime('%H') print("date and time =", date, time) # Open the netCDF file containing the input data. fnx = xr.open_dataset('https://thredds.met.no/thredds/dodsC/mepslatest/meps_det_2_5km_%sT%sZ.ncml' % (date, ini_time), decode_times=True, use_cftime=True) data = fnx.metpy.parse_cf().squeeze() # Cross section along 69.3 latitude and between 1 and 25 longitude # Andenes = 16deg longitude start = (69.3, 1) end = (69.3, 25) cross_data = data[['cloud_area_fraction_pl', 'air_temperature_pl', 'relative_humidity_pl']] cross = cross_section( cross_data, start, end).set_coords(('latitude', 'longitude')) # Inverse the pressure axes (doesn't work as intended) # cross = cross.reindex(pressure=list(reversed(cross.pressure))) temperature, clouds, relative_humidity = xr.broadcast(cross['air_temperature_pl'], cross['cloud_area_fraction_pl'], cross['relative_humidity_pl']) # Plot the cross section fig, axs = plt.subplots( nrows=3, ncols=3, sharey=True, sharex=True, figsize=(14, 10)) ax = axs.ravel().tolist() j = 0 # Define the figure object and primary axes for i in [0, 6, 12, 18, 24, 30, 36, 42, 48]: # Plot RH using contourf rh_contour = ax[j].contourf(cross['longitude'], cross['pressure'], cross['relative_humidity_pl'].isel(time=i), levels=np.arange(0, 1.05, .05), cmap='YlGnBu') # Plot cloud fraction using contour, with some custom labeling clouds_contour = ax[j].contour(cross['longitude'], cross['pressure'], cross['cloud_area_fraction_pl'].isel(time=i), levels=np.arange(0.4, 1.2, 0.2), colors='k', linewidths=2) # Reverse the y axis to get surface pressure at the bottom ax[j].set_ylim(ax[j].get_ylim()[::-1]) j += 1 fig.tight_layout() rh_colorbar = fig.colorbar( rh_contour, ax=ax, ticks=list(np.arange(0, 1.05, .05))) rh_colorbar.set_label( 'Relative Humidity (%)', fontsize=18)
ed248d47e2137629bb52c561427e4d5197e66ecd
[ "Markdown", "Python" ]
4
Markdown
franzihe/Weathermap
cc24168855d8d36806179c963ea853d08a0b5b7c
d18adef35b60e7f952fd7d45d69d6ce33412f1c8
refs/heads/master
<repo_name>tehwentzel/Simple-Expert-System<file_sep>/project1/Condition.java public class Condition { public static final int CARDIOVASCULAR_CONDITION = 1; public static final int STATIN_INTERACTION = 2; public static final int IMPAIRED_KINDEY_OR_LIVER = 3; public static final int MUSCLE_DISORDER = 4; public static final int HIV = 5; public static final int PRE_HYPERTENSION = 6; public static final int HYPERTENSION = 7; private String description; private int code; public Condition(){ return; } public Condition(String description, int code){ this.description = description.toLowerCase(); this.code = code; } public String getDescription(){ return this.description; } public void setDescription( String newDescription ) { this.description = newDescription.toLowerCase(); } public int getCode() { return this.code; } public void setCode (int newCode) { this.code = newCode; } } <file_sep>/project1/Record.java public class Record { private String description; public Record(String description){ this.description = description.toLowerCase(); } public String getDescription(){ return this.description; } public void setDescription( String newDescription ) { this.description = newDescription.toLowerCase(); } } <file_sep>/readme.md ### Overview This is a project for CS 514 Applied AI. It consists of a prototype version of an expert system called a clinical decision support system. It was written in Java using the rule inference engine Jess (jessrules.com). ##### Domain My domain is in the area of Clinical Decision Support Systems, and application of expert systems that are designed to aid medical professional with making medical decisions. These systems aren’t intended to fully replace medical professionals, as many decisions are guided by personal judgment, but can aid greatly in speeding up decision making and reducing errors in a medical setting, where professionals are often short on time, and rules for many conditions can become extremely complex. This specific example covers some of the basics of dealing with high cholesterol and some related heart conditions in individuals, as today heart disease is the leading cause of death and there is a wealth of literature on treatment. The specifics of the prototype cover some of the basic guidelines for prescribing treatment high cholesterol based on certain patient information and cholesterol levels. It will also make some basic insights into related issues - namely diagnosing high blood pressure - and finally provided suggestions for specific popular drugs based on the results. #### System Design The system is designed to be used for a unique individual. It defines 4 classes (in java) and corresponding templates in lisp: Person, Condition, Record, and Recommendation. The *Person* class is required. A number of fields are given regarding the patient that were chosen to reflect normal information taken at the time of a doctor visit (name, weight, height, etc), which are included in the constructor for the class. A number of additional information is included that is used to calculate the patients 10-year risk of having a heart attack or stroke according to [1], which is encapsulated in the private methods *predictMaleRisk() *and *predictFemaleRisk()*. The latter fields are defined in the system by using the "lipid-panel" function in Jess or can be set manually. This functionality is chosen to reflect the fact that patients may not necessarily have information about their cholesterol levels on their first visit to a doctor. The *Condition* class is a small class that is meant to encapsulate different conditions the patient may have. Each condition has a *description *which is a string, and a *code, *which is an integer that the system uses to classify them. Conditions can be put in manually, or can be outputs of the system* *(e.g. high blood pressure). The existence of certain conditions can be used to determine if certain recommendations should be made or altered. E.g. Patients with HIV on protease inhibitors have certain statins they shouldn’t take. Any patient with an existing heart condition should automatically be prescribed statins. The *Recommendation *Class is the actual output of the system. Like Conditions, they each have a *description *and a *code. *Additionally, a boolean field called *active* is used to allow Recommendations to be inactivated to prevent loops where recommendations are removed, causing the rules that created them to re-fire. The *Record *Class is largely a placeholder to allow for further expansion to the system. It contains a *description. *It is meant to be used in the potential case where patients and doctors could be continually interacting, and records could be added dynamically. Here, when a "lipid panel" is created, it creates a corresponding record. #### Running The System and Output The system can be run in an IDE (e.g. Eclipse), or from the command line by navigating to the folder "project 1" and running the command: >java MyClinicalSupportSystem The command line will prompt you for a file to run for the test case. Pressing <enter> will result in the default file being run, defined in the *testCaseFile *static field at the top of the MyClinicalSupportSystem class. This can be changed as well. Several test cases have been given as examples of the form *test_case[0-6].clp*. The files are in the form of jess files that instantiate a *Person *object, and an option (but highly recommended) lipid test and one or more conditions. A template is also given in the *test_case_template.clp* file, where all input strings and integers are replaced by /* INTEGER */ and /* STRING */, respectively. The Person initialization is required. The lipid panel and conditions are recommended, or the system will just tell you to get a lipid test or not, probably. The system will then run and print out all active generated by the expert system. #### A Bit More on the Logic and All That The logic in the system works largely in three stages. In the first stage, patient information is taken in. In the event that a lipid test is not included, the system will decide if one is suggested (based on age). The system will also look at the patient’s blood pressure and will add a condition and corresponding recommendation if the patient has hypertension. In the event of a lipid test, more information can be gleamed. The Person class implements a risk variable that calculates a 10-year likelihood of someone having a stroke or heart attack. A risk of >20% will result in the patient being diagnosed with Cardiovascular Disease, as this is an equivalent clinical definition. Several factors are then used to check for cases where guidelines recommend the use of different treatments. The treatments covered in this systems are predominantly: * Moderate or High Intensity Statins, which lower bad LDL cholesterol. * Fibrates, which lower triglycerides. * Therapeutic Lifestyle Changes (TLC), which are the first-line recommendation for many case. Factors that are considered are age, 10-year risk, LDL cholesterol levels, Triglyceride levels, if the patient has diabetes, and presence of certain conditions such as a previous heart attack or hypertension. After this stage, certain conditions are checked against the resulting recommendations for contra-indications. One example of this is that people of Asian descent are more likely to face side effects from high-intensity statins, and should be downgraded to taking medium-intensity statins. When this occurs, previous recommendations are deactivated, where there *active *field is set to FALSE, instead of being removed. This allows logic to prevent the recommendations from being re-generated. Finally, some specific recommendations for medications are generated for the prescription of statins. While there are a number of different drugs, these recommendations are based on the subset of those recommended in [3], due to their effectiveness and cost. At this point the system could allow for interactions with specific drugs to be checked. For this example, patients with a Condition with the HIV code will be given a different set of statin recommendations. #### Miscellania This system uses forward chaining to generate recommendations. However, for systems where a medical professional is able to more dynamically, backward chaining systems are often used. In these cases, the professional can try to check for a specific diagnosis, and will be able to be given any suite of tests that are required in order to reach a conclusion. The algorithm used for calculating 10-year risk is take from literature and covers the values given for white males and females. African-american and hispanic specific algorithms also exists, but were not included due to difficulty in finding them. The test cases provided cover most of the cases considered in testing the system. Certain results are taken from literature, but the specific conditions haven’t been found as they rely on a large number of variables and specific ranges for calculating 10-year risk. Certain guidelines among the cited literature are fuzzy and contradict each other in certain situations. None of the rules in this system should be taken as fact and are purely demonstrative. Please don’t sue me if this system tells you you’re ok and then your heart explodes. This system makes use of certain demographic factors such as gender and race. These are used in relation to how they are cited in literature and are not meant to be exhaustive or reflect the views of the author. #### Sources Most of the rules in this system are drawn from the *2013 ACC/AHA Guideline on the Assessment of Cardiovascular Risk* (NOTE: Andrus, Bruce, and <NAME>. "2013 ACC/AHA guideline on the assessment of cardiovascular risk." Journal of the American College of Cardiology 63.25 Part A (2014): 2886.)*, *as well as the the National Cholesterol Education Program’s published report on *Detection, Evaluation, and Treatment of High Blood Cholesterol In Adults (Adult Treatment Panel)* (NOTE: Expert Panel on Detection, Evaluation. "Executive summary of the third report of the National Cholesterol Education Program (NCEP) expert panel on detection, evaluation, and treatment of high blood cholesterol in adults (Adult Treatment Panel III)." Jama 285.19 (2001): 2486.)*. *Certain guidelines for suggesting specific drugs were taken from *Consumer Reports Best Buy Drugs: Evaluating Statin Drugs to Treat High Cholesterol and Heart Disease* (NOTE: http://article.images.consumerreports.org/prod/content/dam/cro/news_articles/health/PDFs/StatinsUpdate-FINAL.pdf)*. * This system is implemented using Java and Jess. (NOTE: <NAME>, "Jess in Action: Rule-based Systems in Java", ISBN 1930110898. )
e5d748e73dab8154c81b698026c0cf4457cbd8d6
[ "Markdown", "Java" ]
3
Java
tehwentzel/Simple-Expert-System
384200cfeb4ad2d8f9b33952fa7fddc2addb804e
0d91072baa02d911f234ebc489b563b864ca0922
refs/heads/master
<repo_name>ucking44/mobileApp<file_sep>/database/migrations/2020_12_27_033440_create_products_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->bigIncrements('product_id'); //$table->bigInteger('user_id')->unsigned(); $table->unsignedBigInteger('category_id'); $table->unsignedBigInteger('manufacture_id'); $table->string('product_name'); $table->longText('product_description'); //$table->float('product_price'); $table->double('product_price', 14, 2); $table->unsignedBigInteger('stock'); $table->string('product_image'); $table->string('product_size'); $table->string('product_color'); $table->string('status')->default('disable'); $table->float('rating_cache', 2, 1)->default(3.0); $table->unsignedBigInteger('rating_count')->default(0); $table->string('icon'); $table->foreign('category_id')->references('category_id')->on('categories')->onDelete('cascade'); $table->foreign('manufacture_id')->references('manufacture_id')->on('manufactures')->onDelete('cascade'); $table->timestamps(); // $table->foreign('user_id') // ->references('user_id') // ->on('users') // ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('products'); } } <file_sep>/app/Http/Controllers/ServiceCategoryController.php <?php namespace App\Http\Controllers; use App\ServiceCategory; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; class ServiceCategoryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $serviceCates = ServiceCategory::paginate(4); return view('admin.serviceCategory.index', compact('serviceCates')); //$serviceCate = ServiceCategory::paginate(4); //return response()->json($serviceCate, 200); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.serviceCategory.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'category_name' => 'required', 'category_description' => 'required', ]); $serviceCate = new ServiceCategory(); $serviceCate->category_name = $request->category_name; $serviceCate->category_description = $request->category_description; if ($request->status) { $serviceCate->status = 'enable'; } else { $serviceCate->status = 'disable'; } $serviceCate->save(); return Redirect::to('/service-category')->with('successMsg', 'Service Categories Saved Successfully ):'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $serviceCate = ServiceCategory::findOrFail($id); return view('admin.serviceCategory.edit', compact('serviceCate')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'category_name' => 'required', 'category_description' => 'required', ]); $serviceCate = ServiceCategory::findOrFail($id); $serviceCate->category_name = $request->category_name; $serviceCate->category_description = $request->category_description; if ($request->status) { $serviceCate->status = 'enable'; } else { $serviceCate->status = 'disable'; } $serviceCate->save(); return Redirect::to('/service-category')->with('successMsg', 'Service Categories Updated Successfully ):'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $serviceCate = ServiceCategory::findOrFail($id); $serviceCate->delete(); return Redirect::to('/service-category')->with('successMsg', 'Service Categories Deleted Successfully):'); } public function unactive_service_category($id) { $unactive_category = ServiceCategory::findOrFail($id); $unactive_category->update(['status' => 'disable']); return Redirect::to('/service-category')->with('successMsg', 'Service Category Un-activated Successfully ):'); } public function active_service_category($id) { $active_category = ServiceCategory::findOrFail($id); $active_category->update(['status' => 'enable']); return Redirect::to('/service-category')->with('successMsg', 'Service Category Activated Successfully ):'); } public function search($category_name) { $search = ServiceCategory::where("category_name", "like", "%" . $category_name . "%") ->get(); return $search; } } <file_sep>/app/Service.php <?php namespace App; //use App\ServiceCategory; use App\Appointment; use Illuminate\Database\Eloquent\Model; class Service extends Model { protected $table = 'services'; protected $primaryKey = 'id'; protected $fillable = [ 'service_name', 'fee', 'duration', 'status', ]; // public function serviceCategory() // { // return $this->belongsTo(ServiceCategory::class); // } public function appointments() { return $this->hasMany(Appointment::class); } } <file_sep>/app/Http/Controllers/UsersController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UsersController extends Controller { public function __construct() { $this->middleware('auth.role:admin', ['only' => ['blockUser']]); } public function blockUser() { return '<b><h1>This is an admin route.</h1></b>'; } public function profile() { return '<b><h1>This route is for all users.</h1></b>'; } } <file_sep>/app/Http/Controllers/Admin/CheckoutController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Carbon; use App\Http\Requests; //use Session; use Cart; session_start(); class CheckoutController extends Controller { public $loginAfterSignUp = true; public function login_check() { return view('pages.login'); } public function customer_registration(Request $request) { $this->validate($request, [ 'customer_name' => 'required', 'customer_email' => 'required', 'password' => '<PASSWORD>', 'mobile_number' => 'required', ]); $data = array(); $data['customer_name'] = $request->customer_name; $data['customer_email'] = $request->customer_email; $data['password'] = md5($request->password); $data['mobile_number'] = $request->mobile_number; $data['created_at'] = Carbon::now(); //->toDateString(); $data['updated_at'] = Carbon::now(); //->toDateString(); // if ($this->loginAfterSignUp) { // return $this->login($request); // } $customer_id = DB::table('customer') ->insertGetId($data); // return response()->json([ // 'success' => true, // 'data' => $customer_id // ], 200); Session::put('customer_id', $customer_id); Session::put('customer_name', $request->customer_name); return Redirect('/checkout'); } public function checkout() { // $all_published_category = DB::table('category') // ->where('publication_status', 1) // ->get(); // return view('pages.checkout', compact('all_published_category')); return view('pages.checkout'); } public function save_shipping_details(Request $request) { $data = array(); $data['shipping_email'] = $request->shipping_email; $data['shipping_first_name'] = $request->shipping_first_name; $data['shipping_last_name'] = $request->shipping_last_name; $data['shipping_address'] = $request->shipping_address; $data['shipping_mobile_number'] = $request->shipping_mobile_number; $data['shipping_city'] = $request->shipping_city; $data['created_at'] = Carbon::now(); //->toDateString(); $data['updated_at'] = Carbon::now(); //->toDateString(); $shipping_id = DB::table('shipping') ->insertGetId($data); Session::put('shipping_id', $shipping_id); return Redirect::to('/payment'); } public function customer_login(Request $request) { $customer_email = $request->customer_email; $password = md5($request->password); $result = DB::table('customer') ->where('customer_email', $customer_email) ->where('password', $password) ->first(); if ($result) { Session::put('customer_id', $result->customer_id, 'customer_name', $result->customer_name); //Session::put('customer_name', $result->customer_name); return Redirect::to('/checkout'); } else { return Redirect::to('/login-check'); } } public function payment() { return view('pages.payment'); } public function order_place(Request $request) { $payment_gateway = $request->payment_method; $paymentData = array(); $paymentData['payment_method'] = $payment_gateway; $paymentData['payment_status'] = 'pending'; $paymentData['created_at'] = Carbon::now(); //->toDateString(); $paymentData['updated_at'] = Carbon::now(); //->toDateString(); $payment_id = DB::table('payment') ->insertGetId($paymentData); $orderData = array(); $orderData['customer_id'] = Session::get('customer_id'); $orderData['shipping_id'] = Session::get('shipping_id'); $orderData['payment_id'] = $payment_id; $orderData['order_total'] = Cart::total(); $orderData['order_status'] = 'pending'; $orderData['created_at'] = Carbon::now(); //->toDateTimeString(); $orderData['updated_at'] = Carbon::now(); //->toDateString(); $order_id = DB::table('order') ->insertGetId($orderData); $contents = Cart::content(); $orderData = array(); foreach ($contents as $v_content) { $odData['order_id'] = $order_id; $odData['product_id'] = $v_content->id; $odData['tax'] = Cart::tax(); $odData['total'] = Cart::total(); $odData['product_name'] = $v_content->name; $odData['product_price'] = $v_content->price; $odData['product_sales_quantity'] = $v_content->qty; $odData['created_at'] = Carbon::now()->toDateTimeString(); $odData['updated_at'] = Carbon::now()->toDateTimeString(); DB::table('order_details') ->insert($odData); } if ($payment_gateway == 'handcash') { Cart::destroy(); return view('pages.handcash'); // Cart::destroy(); } elseif ($payment_gateway == 'card') { echo "Successfully Done By Card"; } elseif ($payment_gateway == 'paypal') { echo "Successfully Done By Paypal"; } else { echo "No Payment Method Selected"; } } public function manage_order() { $all_order_info = DB::table('order') ->join('customer', 'order.customer_id', '=', 'customer.customer_id') ->select('order.*', 'customer.customer_name') ->get(); return view('admin.manage_order', compact('all_order_info')); } public function view_order($order_id) { $order_by_id = DB::table('order') ->join('customer', 'order.customer_id', '=', 'customer.customer_id') ->join('order_details', 'order.order_id', '=', 'order_details.order_id') ->join('shipping', 'order.shipping_id', '=', 'shipping.shipping_id') ->select('order.*', 'order_details.*', 'shipping.*', 'customer.*') ->get(); return view('admin.view_order', compact('order_by_id')); } public function customer_logout() { Session::flush(); return Redirect::to('/'); } // private function sslapi() // { // } } <file_sep>/app/Http/Controllers/AppointmentController.php <?php namespace App\Http\Controllers; use App\Appointment; use App\Service; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; class AppointmentController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $appointments = DB::table('appointments') ->join('services', 'appointments.service_id', '=', 'services.id') ->select('appointments.*', 'services.service_name', 'services.duration', 'services.fee') //->oldest() ->latest() //->paginate(3); ->get(); //return view('admin.appointment.index', compact('appointments')); return response()->json($appointments, 200); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $services = Service::pluck('service_name', 'id'); return view('appointment.create', compact('services')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'service_name' => 'required', 'firstName' => 'required', 'lastName' => 'required', 'date' => 'required', 'time' => 'required', 'gender' => 'required', 'email' => 'required | email', 'phone' => 'required | numeric', 'message' => 'required', ]); $appointment = new Appointment(); $appointment->service_id = $request->service_name; $appointment->firstName = $request->firstName; $appointment->lastName = $request->lastName; $appointment->date = Carbon::now(); $appointment->time = $request->time; $appointment->gender = $request->gender; $appointment->email = $request->email; $appointment->phone = $request->phone; $appointment->message = $request->message; if ($request->status) { $appointment->status = 'enable'; } else { $appointment->status = 'disable'; } $appointment->save(); return Redirect::back()->with('successMsg', 'You Have Successfully Booked An Appointment !!!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $service = Service::all(); $appointment = Appointment::all(); return view('admin.appointment.edit', compact('service', 'appointment')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'service_name' => 'required', 'firstName' => 'required', 'lastName' => 'required', 'date' => 'required', 'gender' => 'required', 'email' => 'required | email', 'phone' => 'required | phone', 'message' => 'required', ]); $appointment = Appointment::findOrFail($id); $appointment->service_id = $request->service_name; $appointment->firstName = $request->firstName; $appointment->date = Carbon::now(); $appointment->gender = $request->gender; $appointment->email = $request->email; $appointment->phone = $request->phone; $appointment->message = $request->message; if ($request->status) { $appointment->status = 'enable'; } else { $appointment->status = 'disable'; } $appointment->save(); return Redirect::to('')->with('successMsg', 'Your Appointment Have Been Successfully Updated !!!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $appointment = Appointment::findOrFail($id); $appointment->delete(); return Redirect::to('')->with('successMsg', 'Appointment Was Successfully Deleted !!!'); } } <file_sep>/routes/api.php <?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\OminiPaymentController; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ // Route::middleware('auth:api')->get('/user', function (Request $request) { // return $request->user(); // }); Route::post('login', 'CheckoutController@login'); //Route::post('customer-register', 'CustomerApiController@customerRegister'); Route::post('register', 'CheckoutController@register'); // Route::post('login', 'ApiController@login'); // //Route::post('customer-register', 'CustomerApiController@customerRegister'); // Route::post('register', 'ApiController@register'); Route::post('/customer_registration', 'CheckoutController@customer_registration'); Route::group(['middleware' => 'auth.jwt'], function () { // Route::get('logout', 'ApiController@logout'); Route::get('logout', 'CheckoutController@logout'); //Route::get('user', 'ApiController@getAuthUser'); Route::get('user', 'CheckoutController@getAuthUser'); ///////////////////////// PRODUCT ROUTE //////////////////////////// Route::get('products', 'ProductController@index'); ////////////////// SHIPPING ROUTE ////////////////// Route::post('/save-shipping-details', 'CheckoutController@save_shipping_details'); ////////////////// ORDER ROUTE /////////////////// Route::post('/order-place', 'CheckoutController@order_place'); Route::get('/manage-order', 'CheckoutController@manage_order'); Route::get('/view-order/{order_id}', 'CheckoutController@view_order'); ///////////////////////////////// REVIEW ROUTE //////////////////////////////////// Route::post('/reviews', 'ReviewsController@store'); }); Route::get('users/profile', ['uses' => 'UsersController@profile', 'as' => 'users.profile']); Route::get('users/block', ['uses' => 'UsersController@blockUser', 'as' => 'users.block']); ///////////////////////////////////// SERVICE ROUTE //////////////////////////////////////////// Route::get('/service', 'ServiceController@index'); Route::get('/create/service', 'ServiceController@create'); Route::post('/store/service', 'ServiceController@store'); Route::get('/edit/service/{id}', 'ServiceController@edit'); Route::put('/update/service/{id}', 'ServiceController@update'); Route::get('/delete/service/{id}', 'ServiceController@destroy'); Route::get('/service/unactive/{id}', 'ServiceController@unactive_service'); Route::get('/service/active/{id}', 'ServiceController@active_service'); /////////////////////// APPOINTMENT ROUTE ////////////////////////////// Route::get('/appointment', 'AppointmentController@index'); Route::get('/create/appointment', 'AppointmentController@create'); Route::post('/save/appointment', 'AppointmentController@store'); Route::get('/', 'HomesController@index'); //////////////////////// SHOWING PRODUCT ROUTE ///////////////////////// Route::get('/product_by_category/{category_id}', 'HomesController@show_product_by_category'); Route::get('/product_by_manufacture/{manufacture_id}', 'HomesController@show_product_by_manufacture'); Route::get('/view_product/{product_id}', 'HomesController@product_details_by_id'); //////////////////// CART ROUTE //////////////////////// Route::post('/add-to-cart', 'CartController@add_to_cart'); Route::get('/show-cart', 'CartController@show_cart'); Route::delete('/delete-to-cart/{rowId}', 'CartController@delete_to_cart'); Route::post('/update-cart', 'CartController@update_cart'); /////////////////// WISHLIST ROUTE ////////////////// Route::post('/addToWishList', 'HomeController@wishList'); Route::get('/wishList', 'HomeController@view_wishList'); Route::get('/removeWishList/{id}', 'HomeController@removeWishList'); ////////////////////////////// PAYMENT ROUTE /////////////////////////////// /////////////////// OMINI PACKAGE IS OK //////////////////////// //Route::get('payment', [OminiPaymentController::class, 'index']); Route::post('/store/payment', [OminiPaymentController::class, 'store']); Route::get('/success/payment', [OminiPaymentController::class, 'success']); Route::put('/payment/details/{id}', [OminiPaymentController::class, 'payment_details']); /////////////////// REVIEWS ROUTE /////////////////// Route::get('/product-show-review/{product_id}', 'HomeController@productReview'); Route::get('/show-reviews/{id}', 'ProductController@showReview'); ////////////////////// CATEGORY ROUTE //////////////////////// Route::get('/category', 'CategoryController@index'); Route::get('/category-id/{category_id}', 'CategoryController@category_by_id'); ////////////////////// MANUFACTURE ROUTE //////////////////////// Route::get('/manufacture', 'ManufactureController@index'); Route::get('/manufacture-id/{manufacture_id}', 'ManufactureController@manufacture_by_id'); // ///////////////////////// PRODUCT ROUTE //////////////////////////// // Route::get('products', 'ProductController@index'); Route::get('/products/{product_id}', 'ProductController@show_product_by_id'); //////////////////////// SEARCH ROUTE /////////////////////////// Route::get('/search-product', 'ProductController@search'); // Route::get('/search-product/{product_name}', 'ProductController@search'); Route::get('/search-category/{category_name}', 'CategoryController@search'); Route::get('/search-manufacture/{manufacture_name}', 'ManufactureController@search'); ///////////////////////////////// REVIEW ROUTE //////////////////////////////////// Route::get('/review', 'ReviewsController@index'); //Route::apiResource('products/{product}/reviews', 'ReviewController')->only('store', 'update', 'destroy'); <file_sep>/app/Http/Controllers/CheckoutController.php <?php namespace App\Http\Controllers; use App\Http\Requests\RegisterAuthRequest; use App\User; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; use Cart; class CheckoutController extends Controller { public $loginAfterSignUp = true; public function register(RegisterAuthRequest $request) { $user = new User(); $user->name = $request->name; $user->email = $request->email; $user->phone = $request->phone; $user->password = <PASSWORD>($request->password); $user->save(); if ($this->loginAfterSignUp) { return $this->login($request); } return response()->json([ 'success' => true, 'data' => $user ], 200); } public function login(Request $request) { $input = $request->only('email', 'password'); $jwt_token = null; if (!$jwt_token = JWTAuth::attempt($input)) { return response()->json([ 'success' => false, 'message' => 'Invalid Email or Password', ], 401); } return response()->json([ 'success' => true, 'token' => $jwt_token, ]); } public function logout(Request $request) { $this->validate($request, [ 'token' => 'required' ]); try { JWTAuth::invalidate($request->token); return response()->json([ 'success' => true, 'message' => 'User logged out successfully' ]); } catch (JWTException $exception) { return response()->json([ 'success' => false, 'message' => 'Sorry, the user cannot be logged out' ], 500); } } public function getAuthUser(Request $request) { $this->validate($request, [ 'token' => 'required' ]); $user = JWTAuth::authenticate($request->token); return response()->json(['user' => $user]); } public function save_shipping_details(Request $request) { $data = array(); $data['shipping_email'] = $request->shipping_email; $data['shipping_first_name'] = $request->shipping_first_name; $data['shipping_last_name'] = $request->shipping_last_name; $data['shipping_address'] = $request->shipping_address; $data['shipping_mobile_number'] = $request->shipping_mobile_number; $data['shipping_city'] = $request->shipping_city; $data['created_at'] = Carbon::now(); //->toDateString(); $data['updated_at'] = Carbon::now(); //->toDateString(); $shipping_id = DB::table('shipping') ->insertGetId($data); Session::put('shipping_id', $shipping_id); return response()->json([ 'success' => true, 'data' => $shipping_id ], 200); //return Redirect::to('/payment'); } public function payment() { return view('pages.payment'); } public function order_place(Request $request) { $payment_gateway = $request->payment_method; $paymentData = array(); $paymentData['payment_method'] = $payment_gateway; $paymentData['payment_status'] = 'pending'; $paymentData['created_at'] = Carbon::now(); //->toDateString(); $paymentData['updated_at'] = Carbon::now(); //->toDateString(); $payment_id = DB::table('payment') ->insertGetId($paymentData); $orderData = array(); $orderData['user_id'] = Session::get('user_id'); $orderData['shipping_id'] = Session::get('shipping_id'); $orderData['payment_id'] = $payment_id; $orderData['order_total'] = Cart::total(); $orderData['order_status'] = 'pending'; $orderData['created_at'] = Carbon::now(); //->toDateTimeString(); $orderData['updated_at'] = Carbon::now(); //->toDateString(); $order_id = DB::table('order') ->insertGetId($orderData); $contents = Cart::content(); $orderData = array(); foreach ($contents as $v_content) { $odData['order_id'] = $order_id; $odData['product_id'] = $v_content->id; $odData['tax'] = Cart::tax(); $odData['total'] = Cart::total(); $odData['product_name'] = $v_content->name; $odData['product_price'] = $v_content->price; $odData['product_sales_quantity'] = $v_content->qty; $odData['created_at'] = Carbon::now()->toDateTimeString(); $odData['updated_at'] = Carbon::now()->toDateTimeString(); DB::table('order_details') ->insert($odData); } if ($payment_gateway == 'handcash') { Cart::destroy(); return view('pages.handcash'); // Cart::destroy(); return response()->json([ 'success' => true, 'message' => 'Transaction Successfully Done By Handcash !!!', ], 200); //return response()->json('handcash', 200); } elseif ($payment_gateway == 'card') { echo "Successfully Done By Card"; } elseif ($payment_gateway == 'paypal') { echo "Successfully Done By Paypal"; } else { echo "No Payment Method Selected"; } } public function manage_order() { $all_order_info = DB::table('order') ->join('users', 'order.user_id', '=', 'users.user_id') ->select('order.*', 'users.name') ->get(); //return view('admin.manage_order', compact('all_order_info')); return response()->json([ 'success' => true, 'data' => $all_order_info, 'message' => 'This is all successfully placed orders !!!', ], 200); } public function view_order($order_id) { $order_by_id = DB::table('order') ->join('users', 'order.user_id', '=', 'users.user_id') ->join('order_details', 'order.order_id', '=', 'order_details.order_id') ->join('shipping', 'order.shipping_id', '=', 'shipping.shipping_id') ->select('order.*', 'order_details.*', 'shipping.*', 'users.*') ->get(); //return view('admin.view_order', compact('order_by_id')); return response()->json([ 'success' => true, 'data' => $order_by_id, 'message' => 'This is a successfully placed order !!!', ], 200); } // public function customer_logout() // { // Session::flush(); // return Redirect::to('/'); // } } <file_sep>/app/Http/Controllers/AboutUsController.php <?php namespace App\Http\Controllers; use App\AboutUs; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; class AboutUsController extends Controller { public function aboutUs() { $aboutUs = AboutUs::simplePaginate(3); return view('admin.aboutUs.index', compact('aboutUs')); } public function createAboutUs() { return view('admin.aboutUs.create'); } public function saveAboutUs(Request $request) { $this->validate($request, [ 'name' => 'required', 'years_of_experience' => 'required', 'email' => 'required | email', 'company' => 'required', 'website' => 'required | url', ]); $aboutUs = new AboutUs(); $aboutUs->name = $request->name; $aboutUs->years_of_experience = $request->years_of_experience; $aboutUs->email = $request->email; $aboutUs->company = $request->company; $aboutUs->website = $request->website; if ($request->status) { $aboutUs->status = 'enable'; } else { $aboutUs->status = 'disable'; } $aboutUs->save(); return Redirect::to('/aboutus')->with('successMsg', 'About Us Page Created Successfully !!!'); } public function editAboutUs($id) { $aboutUs = AboutUs::findOrFail($id); return view('admin.aboutUs.edit', compact('aboutUs')); } public function updateAboutUs(Request $request, $id) { $this->validate($request, [ 'name' => 'required', 'years_of_experience' => 'required', 'email' => 'required | email', 'company' => 'required', 'website' => 'required | url', ]); $aboutUs = AboutUs::findOrFail($id); $aboutUs->name = $request->name; $aboutUs->years_of_experience = $request->years_of_experience; $aboutUs->email = $request->email; $aboutUs->company = $request->company; $aboutUs->website = $request->website; if ($request->status) { $aboutUs->status = 'enable'; } else { $aboutUs->status = 'disable'; } $aboutUs->save(); return Redirect::to('/aboutus')->with('successMsg', 'About Us Page Updated Successfully !!!'); } public function deleteAboutUs($id) { $aboutUs = AboutUs::findOrFail($id); $aboutUs->delete(); return Redirect::to('/aboutus')->with('successMsg', 'About Us Page Deleted Successfully !!!'); } public function unactive_aboutUs($id) { $unactive_aboutUs = AboutUs::findOrFail($id); $unactive_aboutUs->update(['status' => 'disable']); return Redirect::to('/aboutus')->with('successMsg', 'About Us Un-activated Successfully ):'); } public function active_aboutUs($id) { $active_aboutUs = AboutUs::findOrFail($id); $active_aboutUs->update(['status' => 'enable']); return Redirect::to('/aboutus')->with('successMsg', 'About Us Activated Successfully ):'); } } // 'name', // 'email', // 'company', // 'website', <file_sep>/app/Http/Controllers/BlogController.php <?php namespace App\Http\Controllers; use App\Blog; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Str; class BlogController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $blogs = Blog::latest()->get(); return view('admin.blog.index', compact('blogs')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.blog.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'title' => 'required', 'body' => 'required', 'image' => 'required | file', ]); $image = $request->file('image'); $slug = Str::slug($request->name); if (isset($image)) { $currentDate = Carbon::now()->toDateString(); $imagename = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension(); if (!file_exists('uploads/blog')) { mkdir('uploads/blog', 0777, true); } $image->move('uploads/blog', $imagename); } else { $imagename = 'default.png'; } $blog = new Blog(); $blog->title = $request->title; $blog->body = $request->body; $blog->image = $imagename; if ($request->status) { $blog->status = 'enable'; } else { $blog->status = 'disable'; } $blog->save(); return redirect('/blogs')->with('successMsg', 'Your Post Has been Successfully Saved !'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $blog = Blog::findOrFail($id); return view('admin.blog.edit', compact('blog')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'title' => 'required', 'body' => 'required', ]); $image = $request->file('image'); $slug = Str::slug($request->name); //$slug = str_slug($request->name); $blog = Blog::findOrFail($id); if (isset($image)) { $currentDate = Carbon::now()->toDateString(); $imagename = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension(); if (!file_exists('uploads/blog')) { mkdir('uploads/blog', 0777, true); } $image->move('uploads/blog', $imagename); } else { $imagename = 'default.png'; } $blog->title = $request->title; $blog->body = $request->body; $blog->image = $imagename; if ($request->status) { $blog->status = 'enable'; } else { $blog->status = 'disable'; } $blog->save(); return redirect('/blogs')->with('successMsg', 'Your Post Has been Successfully Updated !'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $blog = Blog::findOrFail($id); $blog->delete(); return redirect('/blogs')->with('successMsg', 'Your Post Has been Successfully Deleted !'); } public function unactive_blog($id) { $unactive_blog = Blog::findOrFail($id); $unactive_blog->update(['status' => 'disable']); return Redirect::to('/blogs')->with('successMsg', 'Blog Post Un-activated Successfully ):'); } public function active_blog($id) { $active_blog = Blog::findOrFail($id); $active_blog->update(['status' => 'enable']); return Redirect::to('/blogs')->with('successMsg', 'Blog Post Activated Successfully ):'); } // public function search($blog_title) // { // $search = Blog::where("category_name", "like", "%" . $blog_title . "%") // ->get(); // return $search; // } } <file_sep>/app/Http/Controllers/ContactUsController.php <?php namespace App\Http\Controllers; use App\ContactUs; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; class ContactUsController extends Controller { public function contacts() { $contacts = ContactUs::simplePaginate(3); return view('admin.contactUs.index', compact('contacts')); } public function createContact() { return view('contactUs.create'); } public function saveContact(Request $request) { $this->validate($request, [ 'name' => 'required', 'email' => 'required | email', 'phone' => 'required | numeric', 'message' => 'required', ]); $contact = new ContactUs(); $contact->name = $request->name; $contact->email = $request->email; $contact->phone = $request->phone; $contact->message = $request->message; $contact->save(); return Redirect::back()->with('successMsg', 'Thanks for contacting us, we will get back to you shortly !!!'); } } <file_sep>/app/Http/Controllers/OminiPaymentController.php <?php namespace App\Http\Controllers; use App\Payment; use App\User; use Exception; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Omnipay\Omnipay; class OminiPaymentController extends Controller { public $gateway; public function __construct() { $this->gateway = Omnipay::create('PayPal_Pro'); $this->gateway->setUsername(env('PAYPAL_API_USERNAME', 'sb-ni47s46317465_api1.business.example.com')); $this->gateway->setPassword(env('PAYPAL_API_PASSWORD', '<PASSWORD>')); $this->gateway->setSignature(env('PAYPAL_API_SIGNATURE', 'A02X.K7GjnEoug.blfyz-e3rD5F9APMmKnNonXliUkjyy06S.iF0288n')); $this->gateway->setTestMode(true); // here 'true' is for sandbox. Pass 'false' when go live } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('payment.payment'); } public function store(Request $request) { $arr_expiry = explode("/", $request->input('expiry')); $formData = array( 'firstName' => $request->input('first-name'), 'lastName' => $request->input('last-name'), 'number' => $request->input('number'), 'expiryMonth' => trim($arr_expiry[0]), 'expiryYear' => trim($arr_expiry[1]), 'cvv' => $request->input('cvc'), //'user' => Auth::user() ); try { // Send purchase request $response = $this->gateway->purchase([ 'amount' => $request->input('amount'), 'currency' => 'USD', 'card' => $formData ])->send(); // Process response if ($response->isSuccessful()) { // Payment was successful $arr_body = $response->getData(); $amount = $arr_body['AMT']; $currency = $arr_body['CURRENCYCODE']; $transaction_id = $arr_body['TRANSACTIONID']; //$message = $arr_body['SUCCESS']; //$isPaymentExist = Payment::where('payment_id', auth()->user()->id)->first(); $isPaymentExist = Payment::where('user_id', auth()->user()->id)->first(); if(!$isPaymentExist) { $payment = new Payment(); //$payment->payment_id = $request->transaction_id; $payment->payer_email = $request->email; //['payer']['payer_info']['payer_id']; $payment->firstName = Auth::user()->firstName;; $payment->lastName = Auth::user()->lastName;; $payment->user_email = Auth::user()->email; //$request->email; //$arr_body['payer']['payer_info']['email']; $payment->amount = $request->amount; //$arr_body['transactions'][0]['amount']['total']; //$payment->currency = env('PAYPAL_CURRENCY'); $payment->user_id = Auth::user()->id; // $payment->associate_id = $request->associate_id; // $payment->corporate_id = $request->corporate_id; // $payment->fellow_id = $request->fellow_id; // $payment->full_id = $request->full_id; // $payment->student_id = $request->student_id; $payment->payment_status = true; //$arr_body['state']; if(!isset($request->payment)) { $payment->payment = 'paid'; } else { $payment->payment = 'not-paid'; } $payment->save(); // if ($payment->payment_status == true) // { // Student::where('payment_id', 0)->update([ // 'payment_id' => 1 // ]); // } // DB::table('users')->where('users.id', $id)->where('usertype', 'null') // ->update(['usertype' => 'student']); // DB::table('users') // ->where('users.id', $id) // ->where('usertype', 'null')->update([ // 'usertype' => 'student' // ]); } //$user = User::where('usertype', '=', 'admin')->get(); //// $data = []; //// $data['firstName'] = Auth::user(); //// $data['title'] = 'Title'; //$data = Auth::user()->email; //Notification::send($user, new PaymentNotification($data)); return response()->json([ 'success' => true, 'payment' => $amount, 'currency' => $currency, 'transaction_id' => $transaction_id, //'data' => $user ], 200); //return Redirect::to('/success/payment')->with('success', 'Payment of ' . $amount .' '. $currency . ' is successful. Your Transaction ID is : ' . $transaction_id); //echo "Payment of $amount $currency is successful. Your Transaction ID is: $transaction_id"; } else { // Payment failed return response()->json([ 'success' => false, 'message' => 'Payment failed. ' . $response->getMessage(), ], 401); //return Redirect::to('/failed/payment')->with('error', 'Payment failed. ' . $response->getMessage()); //echo "Payment failed. ". $response->getMessage(); } } catch(Exception $e) { echo $e->getMessage(); } } } <file_sep>/app/Http/Controllers/CategoryController.php <?php namespace App\Http\Controllers; use App\Category; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; use App\Http\Requests; use Carbon\Carbon; use Session; session_start(); class CategoryController extends Controller { public function admin_index() { return view('admin.category.create'); } public function index() { $dataC = Category::paginate(4); return response()->json($dataC, 200); } public function all_category() { $categories = Category::paginate(4); // $all_category_info = DB::table('category')->paginate(5); //->get(); return view('admin.category.index', compact('categories')); } public function category_by_id($category_id) { $category_by_id = Category::findOrFail($category_id); return response()->json($category_by_id, 200); } public function save_category(Request $request) { $this->validate($request, [ 'category_name' => 'required', 'category_description' => 'required', ]); $data = new Category(); $data['category_id'] = $request->category_id; $data['category_name'] = $request->category_name; $data['category_description'] = $request->category_description; if(isset($request->status)) { $data->status = 'enable'; } else { $data->status = 'disable'; } $data->save(); return redirect('all-category')->with('successMsg', 'Category Saved Successfully ):'); } public function edit_category($category_id) { $category_info = Category::findOrFail($category_id); return view('admin.category.edit', compact('category_info')); } public function update_category(Request $request, $category_id) { $category = Category::findOrFail($category_id); $category->category_name = $request->category_name; $category->category_description = $request->category_description; //$category->updated_at = $request->updated_at; $category->updated_at = Carbon::now(); $category->save(); return Redirect::to('/all-category')->with('successMsg', 'Category Updated Successfully ):'); } public function delete_category($category_id) { $deleteC = Category::findOrFail($category_id); $deleteC->delete(); return Redirect::to('/all-category')->with('successMsg', 'Category Deleted Successfully ):'); } public function unactive_category($category_id) { $unactive_category = Category::findOrFail($category_id); $unactive_category->update(['status' => 'disable']); return Redirect::to('/all-category')->with('successMsg', 'Category Un-activated Successfully ):'); } public function active_category($category_id) { $active_category = Category::findOrFail($category_id); $active_category->update(['status' => 'enable']); return Redirect::to('/all-category')->with('successMsg', 'Category Activated Successfully ):'); } public function search($category_name) { $search = Category::where("category_name", "like", "%" . $category_name . "%") ->get(); return $search; } } <file_sep>/app/Http/Controllers/ServiceController.php <?php namespace App\Http\Controllers; use App\Service; use App\ServiceCategory; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; class ServiceController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $services = Service::all(); return response()->json($services, 200); //return view('admin.service.index', compact('services')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.service.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'service_name' => 'required', 'fee' => 'required | numeric', 'duration' => 'required', ]); $service = new Service(); $service->service_name = $request->service_name; $service->fee = $request->fee; $service->duration = $request->duration; if ($request->status) { $service->status = 'enable'; } else { $service->status = 'disable'; } $service->save(); return Redirect::to('/service')->with('successMsg', 'Service Saved Successfully ):'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $service = Service::findOrFail($id); return view('admin.service.edit', compact('service')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'service_name' => 'required', 'fee' => 'required | numeric', 'duration' => 'required', ]); $service = Service::findOrFail($id); $service->service_name = $request->service_name; $service->fee = $request->fee; $service->duration = $request->duration; if ($request->status) { $service->status = 'enable'; } else { $service->status = 'disable'; } $service->save(); return Redirect::to('/service')->with('successMsg', 'Service Updated Successfully ):'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $service = Service::findOrFail($id); $service->delete(); return Redirect::to('/service')->with('successMsg', 'Service Deleted Successfully ):'); } public function unactive_service($id) { $unactive_service = Service::findOrFail($id); $unactive_service->update(['status' => 'disable']); return Redirect::to('/service')->with('successMsg', 'Service Un-activated Successfully ):'); } public function active_service($id) { $active_service = Service::findOrFail($id); $active_service->update(['status' => 'enable']); return Redirect::to('/service')->with('successMsg', 'Service Activated Successfully ):'); } // public function search($category_name) // { // $search = ServiceCategory::where("category_name", "like", "%" . $category_name . "%") // ->get(); // return $search; // } } <file_sep>/app/WishList.php <?php namespace App; use App\Customer; use App\User; use Illuminate\Database\Eloquent\Model; class WishList extends Model { protected $table = 'wish_lists'; protected $primaryKey = 'id'; protected $fillable = [ 'user_id', 'product_id', ]; public function customer() { return $this->belongsTo(Customer::class); } public function user() { return $this->belongsTo(User::class); } } <file_sep>/app/Http/Controllers/Admin/CustomerApiiController.php <?php namespace App\Http\Controllers; use App\Http\Requests\CustomerRegisterRequest; use App\Customer; use Illuminate\Http\Request; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; class CustomerApiController extends Controller { public $loginAfterSignUp = true; public function customerRegister(CustomerRegisterRequest $request) { $customer = new Customer(); $customer->customer_name = $request->customer_name; $customer->customer_email = $request->customer_email; $customer->password = <PASSWORD>($request->password); $customer->mobile_number = bcrypt($request->mobile_number); $customer->save(); if ($this->loginAfterSignUp) { return $this->login($request); } return response()->json([ 'success' => true, 'data' => $customer ], 200); } public function login(Request $request) { $input = $request->only('email', 'password'); $jwt_token = null; if (!$jwt_token = JWTAuth::attempt($input)) { return response()->json([ 'success' => false, 'message' => 'Invalid Email or Password', ], 401); } return response()->json([ 'success' => true, 'token' => $jwt_token, ]); } public function logout(Request $request) { $this->validate($request, [ 'token' => 'required' ]); try { JWTAuth::invalidate($request->token); return response()->json([ 'success' => true, 'message' => 'User logged out successfully' ]); } catch (JWTException $exception) { return response()->json([ 'success' => false, 'message' => 'Sorry, the user cannot be logged out' ], 500); } } public function getAuthUser(Request $request) { $this->validate($request, [ 'token' => 'required' ]); $customer = JWTAuth::authenticate($request->token); return response()->json(['customer' => $customer]); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // Route::get('/', function () { // return view('layout'); // }); use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use App\Http\Controllers\CheckoutController; use App\Http\Controllers\BlogController; use App\Http\Controllers\OminiPaymentController; Route::get('/', function () { return view('/welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::group(['middleware' => ['auth', 'admin']], function () { ////////////////////////////// DASHBOARD ///////////////////////////// Route::get('/dashboard', 'Admin\DashboardController@dashboard')->name('dashboard'); Route::get('/dashboard', 'Admin\DashboardController@index')->name('dashboard'); //////////////////////////// REGISTER ROLE /////////////////////////////// Route::get('/role-register', 'Admin\AdminController@registered')->name('role-register'); Route::get('/edit/{id}', 'Admin\AdminController@edit')->name('edit'); Route::put('/update/{id}', 'Admin\AdminController@update')->name('update'); Route::delete('/delete/{id}', 'Admin\AdminController@delete')->name('delete'); /////////////////////////// CATEGORY ROUTE ///////////////////////// Route::get('/add-category', 'CategoryController@admin_index'); Route::get('/all-category', 'CategoryController@all_category'); Route::post('/save-category', 'CategoryController@save_category'); Route::get('/edit-category/{category_id}', 'CategoryController@edit_category'); Route::put('/update-category/{category_id}', 'CategoryController@update_category'); Route::get('/delete-category/{category_id}', 'CategoryController@delete_category'); Route::get('/unactive_category/{category_id}', 'CategoryController@unactive_category'); Route::get('/active_category/{category_id}', 'CategoryController@active_category'); ////////////////////////////// SERVICE CATEGORIES ROUTE //////////////////////////////////// Route::get('/service-category', 'ServiceCategoryController@index'); Route::get('/create/service-category', 'ServiceCategoryController@create'); Route::post('/store/service-category', 'ServiceCategoryController@store'); Route::get('/edit/service-category/{id}', 'ServiceCategoryController@edit'); Route::put('/update/service-category/{id}', 'ServiceCategoryController@update'); Route::get('/delete/service-category/{id}', 'ServiceCategoryController@destroy'); Route::get('/service/unactive_category/{id}', 'ServiceCategoryController@unactive_service_category'); Route::get('/service/active_category/{id}', 'ServiceCategoryController@active_service_category'); ///////////////////////////////////// SERVICE ROUTE //////////////////////////////////////////// Route::get('/service', 'ServiceController@index'); Route::get('/create/service', 'ServiceController@create'); Route::post('/store/service', 'ServiceController@store'); Route::get('/edit/service/{id}', 'ServiceController@edit'); Route::put('/update/service/{id}', 'ServiceController@update'); Route::get('/delete/service/{id}', 'ServiceController@destroy'); Route::get('/service/unactive/{id}', 'ServiceController@unactive_service'); Route::get('/service/active/{id}', 'ServiceController@active_service'); //////////////////////////// MANUFACTURE ROUTE //////////////////////// Route::get('/all-manufacture', 'ManufactureController@all_manufacture'); Route::get('/add-manufacture', 'ManufactureController@manufacture_create'); Route::post('/save-manufacture', 'ManufactureController@save_manufacture'); Route::get('/show-manufacture/{manufacture_id}', 'ManufactureController@show'); Route::get('/edit-manufacture/{id}', 'ManufactureController@edit_manufacture'); Route::post('/update-manufacture/{id}', 'ManufactureController@update_manufacture'); Route::get('/delete-manufacture/{id}', 'ManufactureController@delete_manufacture'); Route::get('/unactive_manufacture/{id}', 'ManufactureController@unactive_manufacture'); Route::get('/active_manufacture/{id}', 'ManufactureController@active_manufacture'); /////////////////////////// PRODUCT ROUTE ///////////////////////// Route::get('/add-product', 'ProductController@product_create'); Route::post('/save-product', 'ProductController@save_product'); Route::get('/all-product', 'ProductController@all_product'); Route::get('/show-product/{product_id}', 'ProductController@show'); Route::get('/edit-product/{product_id}', 'ProductController@edit'); Route::put('/update-product/{product_id}', 'ProductController@update_product'); Route::get('/delete-product/{id}', 'ProductController@delete_product'); Route::get('/unactive_product/{product_id}', 'ProductController@unactive_product'); Route::get('/active_product/{product_id}', 'ProductController@active_product'); ////////////////////////////// BLOG ROUTE ///////////////////////////// Route::get('/blogs', [BlogController::class, 'index']); Route::get('/create/blogs', [BlogController::class, 'create']); Route::post('/store/blogs', [BlogController::class, 'store']); Route::get('/show/blogs/{id}', [BlogController::class, 'show']); Route::get('/edit/blogs/{id}', [BlogController::class, 'edit']); Route::put('/update/blogs/{id}', [BlogController::class, 'update']); Route::delete('/delete/blogs/{id}', [BlogController::class, 'destroy']); Route::get('/blog/unactive/{id}', [BlogController::class, 'unactive_blog']); Route::get('/blog/active/{id}', [BlogController::class, 'active_blog']); /////////////////////// ABOUT US ROUTE ///////////////////////////// Route::get('/aboutus', 'AboutUsController@aboutUs'); Route::get('/create/aboutus', 'AboutUsController@createAboutUs'); Route::post('/save/aboutus', 'AboutUsController@saveAboutUs'); Route::get('/edit/aboutus/{id}', 'AboutUsController@editAboutUs'); Route::put('/update/aboutus/{id}', 'AboutUsController@updateAboutUs'); Route::get('/delete/aboutus/{id}', 'AboutUsController@deleteAboutUs'); Route::get('/aboutus/unactive/{id}', 'AboutUsController@unactive_aboutUs'); Route::get('/aboutus/active/{id}', 'AboutUsController@active_aboutUs'); /////////////////////// APPOINTMENT ROUTE ////////////////////////////// Route::get('/appointment', 'AppointmentController@index'); /////////////////////// CONTACT US ROUTE //////////////////////////// Route::get('/contact-us', 'ContactUsController@contacts'); }); Route::get('/', 'HomeController@index'); Route::get('/product_by_category/{category_id}', 'HomeController@show_product_by_category'); Route::get('/product_by_manufacture/{manufacture_id}', 'HomeController@show_product_by_manufacture'); Route::get('/view_product/{product_id}', 'HomeController@product_details_by_id'); /////////////////////// APPOINTMENT ROUTE ////////////////////////////// Route::get('/create/appointment', 'AppointmentController@create'); Route::post('/save/appointment', 'AppointmentController@store'); /////////////////////// CONTACT US ROUTE //////////////////////////// Route::get('/create/contact-us', 'ContactUsController@createContact'); Route::post('/save/contact-us', 'ContactUsController@saveContact'); //////////////////// CART ROUTE //////////////////////// Route::post('/add-to-cart', 'CartController@add_to_cart'); Route::get('/show-cart', 'CartController@show_cart'); Route::get('/delete-to-cart/{rowId}', 'CartController@delete_to_cart'); Route::post('/update-cart', 'CartController@update_cart'); ///////////////////////// CHECKOUT ROUTE //////////////////////// Route::get('/login-check', 'CheckoutController@login_check'); Route::post('/customer_registration', 'CheckoutController@customer_registration'); Route::get('/checkout', 'CheckoutController@checkout'); Route::post('/save-shipping-details', 'CheckoutController@save_shipping_details'); //////////////////// CUSTOMER LOGIN AND LOGOUT ROUTE //////////////// Route::post('/customer_login', 'CheckoutController@customer_login'); Route::get('/customer_logout', 'CheckoutController@customer_logout'); Route::get('/payment', 'CheckoutController@payment'); Route::post('/order-place', 'CheckoutController@order_place'); Route::get('/manage-order', 'CheckoutController@manage_order'); Route::get('/view-order/{order_id}', 'CheckoutController@view_order'); ////////////////////////////// PAYMENT ROUTE /////////////////////////////// /////////////////// OMINI PACKAGE IS OK //////////////////////// Route::get('payment', [OminiPaymentController::class, 'index']); Route::post('/store/payment', [OminiPaymentController::class, 'store']); Route::get('/success/payment', [OminiPaymentController::class, 'success']); Route::put('/payment/details/{id}', [OminiPaymentController::class, 'payment_details']); //////////////////////////// SLIDER ROUTE //////////////////////// Route::get('/sliders', 'SliderController@index'); Route::get('/create/slider', 'SliderController@create'); Route::post('/save-slider', 'SliderController@save_slider'); //Route::get('/all-slider', 'SliderController@all_slider'); Route::delete('/delete-slider/{id}', 'SliderController@delete_slider'); Route::get('/unactive_slider/{id}', 'SliderController@unactive_slider'); Route::get('/active_slider/{id}', 'SliderController@active_slider'); /////////////////// SEARCH ROUTE //////////////////////// Route::get('/search', 'ProductController@search'); /////////////////// REVIEWS ROUTE /////////////////// Route::get('/product-show-review/{product_id}', 'HomeController@productReview'); Route::get('/show-reviews/{id}', 'ProductController@showReview'); Route::post('/reviews', 'ReviewsController@store'); /////////////////// ADD TO WISHLIST ROUTE ////////////////// Route::post('/addToWishList', 'HomeController@wishList'); Route::get('/wishList', 'HomeController@view_wishList'); Route::get('/removeWishList/{id}', 'HomeController@removeWishList'); // Route::post('products/{product_id}/#reviews-anchor', 'ReviewController@storeReview'); //->only('store', 'update', 'destroy'); // Route::post('/products/{product_id}', 'ReviewController@storeReview'); //->only('store', 'update', 'destroy'); // Route::get('/product-review/{product_id}', 'ReviewController@product_review_by_id'); // Route::get('/product-review/{product_id}/#reviews-anchor', 'ReviewController@reviews_anchor'); // Route::get('/productReviews/{product_id}', 'ReviewController@index'); // Route::get('/search-category/{category_name}', 'CategoryController@search'); // Route::get('/search-manufacture/{manufacture_name}', 'ManufactureController@search'); <file_sep>/app/Http/Controllers/ProductController.php <?php namespace App\Http\Controllers; use App\Category; use App\Product; use JWTAuth; //use Tymon\JWTAuth\Facades\JWTAuth; use Illuminate\Support\Facades\Input; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; use App\Http\Requests; use App\Manufacture; use App\Review; use Carbon\Carbon; use Session; session_start(); class ProductController extends Controller { protected $user; /** * The attributes that is for user authentication * * */ // public function __construct() // { // $this->user = JWTAuth::parseToken()->authenticate(); // } public function __construct() { //$this->middleware('auth.role:admin'); //$this->middleware('auth.role:admin', ['except' => ['index']]); } /** * The attributes that is for all products * * */ public function all_product() { // $categories = Category::all(); // $all_manufacture_info = Manufacture::all(); // $products = Product::paginate(5); // return view('admin.product.index', compact('categories', 'all_manufacture_info', 'products')); $products = DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.category_id') ->join('manufactures', 'products.manufacture_id', '=', 'manufactures.manufacture_id') ->select('products.*', 'categories.category_name', 'manufactures.manufacture_name') //->orderBy('product_id', 'asc') ->oldest() //->latest() ->paginate(4); return view('admin.product.index', compact('products')); } public function index() { return $this->user = DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.category_id') ->join('manufactures', 'products.manufacture_id', '=', 'manufactures.manufacture_id') ->select('products.*', 'categories.category_name', 'manufactures.manufacture_name') ->paginate(4); //->toArray(); //->get(); // return response()->json([ // 'success' => true, // 'data' => $all_published_product, // 'message' => 'All Successfully Published Products !!!', // ], 200); } public function product_create() { $products = Product::all(); //$categories = Category::all(); $categories = Category::pluck('category_name', 'category_id'); $all_manufacture_info = Manufacture::all(); return view('admin.product.create', compact('products', 'categories', 'all_manufacture_info')); } public function show($product_id) { $show_product = Product::findOrFail($product_id); return view('admin.product.show', compact('show_product')); } public function showReview($id) { $product = Product::findOrFail($id); $review = Review::all()->where('product_id', $id); //return view('pages.showReview.show', compact('product', 'review')); return response()->json([ 'success' => true, 'data' => $product, $review, ], 200); } public function show_product_by_id($product_id) { $product = Product::findOrFail($product_id); return response()->json($product, 200); } // public function show(Product $product) // { // $product->load(['reviews' => function ($query) { // $query->latest(); // }, 'user']); // return response()->json(['product' => $product]); // } public function save_product(Request $request) { $this->validate($request, [ 'category' => 'required', 'manufacture' => 'required', 'product_name' => 'required', 'product_description' => 'required', 'product_price' => 'required | numeric', 'stock' => 'required', 'product_image' => 'required | file', ]); $image = $request->file('product_image'); $slug = str_slug($request->name); if (isset($image)) { $currentDate = Carbon::now()->toDateString(); $imagename = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension(); if (!file_exists('uploads/products')) { mkdir('uploads/products', 0777, true); } $image->move('uploads/products', $imagename); } else { $imagename = 'default.png'; } $data = new Product(); $data->product_name = $request->product_name; $data->category_id = $request->category; $data->manufacture_id = $request->manufacture; $data->product_description = $request->product_description; $data->product_price = $request->product_price; $data->stock = $request->stock; $data->product_size = $request->product_size; $data->product_color = $request->product_color; $data->product_image = $imagename; if(isset($request->status)) { $data->status = 'enable'; } else { $data->status = 'disable'; } $data->save(); return Redirect::to('/all-product')->with('successMsg', 'Product Saved Successfully ):'); } public function edit($product_id) { $product_info = Product::findOrFail($product_id); $categories = Category::all(); $all_manufacture_info = Manufacture::all(); return view('admin.product.edit', compact('product_info', 'categories', 'all_manufacture_info')); } public function update_product(Request $request, $product_id) { $product = Product::findOrFail($product_id); $product->category_id = $request->category; $product->manufacture_id = $request->manufacture; $product->product_name = $request->product_name; $product->product_description = $request->product_description; $product->product_price = $request->product_price; $product->stock = $request->stock; $product->product_size = $request->product_size; $product->product_color = $request->product_color; $product->status = $request->status; if(isset($request->status)) { $product->status = 'enable'; } else { $product->status = 'disable'; } $product->save(); return Redirect::to('/all-product')->with('successMsg', 'Product Updated Successfully ):'); } public function delete_product($product_id) { $deleteP = Product::findOrFail($product_id); $deleteP->delete(); return Redirect::to('/all-product')->with('successMsg', 'Product Deleted Successfully ):'); } public function unactive_product($product_id) { $unactive_product = Product::findOrFail($product_id); $unactive_product->update(['status' => 'disable']); return Redirect::to('/all-product')->with('successMsg', 'Product Un-activated Successfully ):'); } public function active_product($product_id) { $active_product = Product::findOrFail($product_id); $active_product->update(['status' => 'enable']); return Redirect::to('/all-product')->with('successMsg', 'Product Activated Successfully ):'); } public function search(Request $request) { $data = Product::where('product_name', 'like', '%' . $request->input('query') . '%') ->join('categories', 'products.category_id', '=', 'categories.category_id') ->join('manufactures', 'products.manufacture_id', '=', 'manufactures.manufacture_id') ->simplePaginate(2); // ->select('products.*', 'categories.category_name', 'manufactures.manufacture_name') //->get(); //return view('pages.search', ['products' => $data]); //return $data; return response()->json([ 'success' => true, 'data' => $data, ], 200); } } <file_sep>/app/Review.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Product; use App\User; use App\Customer; //use Carbon\Carbon; use Illuminate\Support\Facades\Auth; use Collective\Html\Eloquent\FormAccessible; use Illuminate\Support\Carbon; class Review extends Model { protected $table = 'reviews'; protected $primaryKey = 'review_id'; protected $fillable = [ 'review', //'rating', //'approved', //'spam', ]; public $timestamps = true; /** * Get the product that owns the review. * * */ public function product() { return $this->belongsTo(Product::class); } /** * Get the user that made the review. * * */ public function user() { return $this->belongsTo(User::class); } public function customer() { return $this->belongsTo(Customer::class); } // public function scopeApproved($query) // { // return $query->where('approved', true); // } // public function scopeSpam($query) // { // return $query->where('spam', true); // } // public function scopeNotSpam($query) // { // return $query->where('spam', false); // } public function getTimeagoAttribute() { //return Carbon::parse($value)->format('m/d/Y'); $date = Carbon::createFromTimeStamp(strtotime($this->created_at))->diffForHumans(); return $date; } public function storeReviewForProduct($product_id, $review, $rating) { $product = Product::find($product_id); // this will be added when we add user's login functionality $this->user_id = Auth::user()->id; $this->review = $review; $this->rating = $rating; $product->reviews()->save($this); // recalculate ratings for the specified product $product->recalculateRating(); } public function getCreateRules() { return array( 'review' => 'required|min:10', 'rating' => 'required|integer|between:1,5' ); } } <file_sep>/resources/Dummy/CartController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Cart; use Illuminate\Support\Facades\Redirect; class CartController extends Controller { public function add_to_cart(Request $request) { $qty = $request->qty; $product_id = $request->product_id; $product_info = DB::table('products') ->where('product_id', $product_id) ->first(); $data['qty'] = $qty; $data['id'] = $product_info->product_id; $data['name'] = $product_info->product_name; $data['price'] = $product_info->product_price; $data['options']['image'] = $product_info->product_image; $dataC = Cart::add($data); //return response()->json($dataC, 201); return response([ 'success' => $dataC, 'Product' => 'Item Added To Cart Successfully!', ]); } public function show_cart() { $all_published_category = DB::table('category') ->where('publication_status', 1) ->get(); return response([ 'success' => $all_published_category, 'category' => 'Showing All Category Successfully!', ]); } public function delete_to_cart($rowId) { $deleteC = Cart::update($rowId, 0); return response([ 'success' => $deleteC, 'product' => 'Item Deleted Successfully!!!', ]); //return Redirect::to('/show-cart'); //Cart::destroy(); } public function update_cart(Request $request) { $qty = $request->qty; $rowId = $request->rowId; //dd($rowId); $updateC = Cart::update($rowId, $qty); return response([ 'success' => $updateC, 'product' => 'Item Updated Successfully!!!', ]); //return Redirect::to('/show-cart'); //Cart::destroy(); } } <file_sep>/app/Http/Controllers/ManufactureController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; use App\Http\Requests; use App\Manufacture; use Carbon\Carbon; use Session; session_start(); class ManufactureController extends Controller { public function all_manufacture() { $all_manufacture_info = DB::table('manufactures')->paginate(5); //->get(); return view('admin.manufacture.index', compact('all_manufacture_info')); } public function manufacture_create() { return view('admin.manufacture.create'); } public function index() { $dataM = Manufacture::paginate(4); return response()->json($dataM, 200); } public function show($manufacture_id) { $show_manufacture = Manufacture::findOrFail($manufacture_id); return view('admin.product.show', compact('show_manufacture')); } public function manufacture_by_id($manufacture_id) { $manufacture_by_id = Manufacture::findOrFail($manufacture_id); return response()->json($manufacture_by_id, 200); } public function save_manufacture(Request $request) { $data = new Manufacture(); $data['manufacture_id'] = $request->manufacture_id; $data['manufacture_name'] = $request->manufacture_name; $data['manufacture_description'] = $request->manufacture_description; //$data['created_at'] = Carbon::now(); if(isset($request->status)) { $data->status = 'enable'; } else { $data->status = 'disable'; } $data->save(); return Redirect::to('/all-manufacture')->with('successMsg', 'Brand Saved Successfully ):'); } public function edit_manufacture($manufacture_id) { $manufacture_info = Manufacture::findOrFail($manufacture_id); return view('admin.manufacture.edit', compact('manufacture_info')); } public function update_manufacture(Request $request, $manufacture_id) { $manufacture = Manufacture::findOrFail($manufacture_id); $manufacture['manufacture_name'] = $request->manufacture_name; $manufacture['manufacture_description'] = $request->manufacture_description; $manufacture->updated_at = Carbon::now(); $manufacture->save(); return Redirect::to('/all-manufacture')->with('successMsg', 'Brand Updated Successfully ):'); } public function delete_manufacture($manufacture_id) { $deleteM = Manufacture::findOrFail($manufacture_id); $deleteM->delete(); //Session::get('message', 'Manufacture Deleted successfully !!'); return Redirect::to('/all-manufacture')->with('successMsg', 'Brand Deleted Successfully ):'); } public function unactive_manufacture($manufacture_id) { $unactive_manufacture = Manufacture::findOrFail($manufacture_id); $unactive_manufacture->update(['status' => 'disable']); return Redirect::to('/all-manufacture')->with('successMsg', 'Brand Un-activated Successfully ):'); } public function active_manufacture($manufacture_id) { $active_manufacture = Manufacture::findOrFail($manufacture_id); $active_manufacture->update(['status' => 'enable']); return Redirect::to('/all-manufacture')->with('successMsg', 'Brand Activated Successfully ):'); } public function search($manufacture_name) { $search = Manufacture::where("manufacture_name", "like", "%" . $manufacture_name . "%") ->get(); return $search; } } <file_sep>/resources/Dummy/HomesController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; //use Illuminate\Support\Facades\Redirect; //use App\Http\Requests; use Session; //session_start(); class HomesController extends Controller { public function index() { $all_published_product = DB::table('products') ->join('category', 'products.category_id', '=', 'category.category_id') ->join('manufacture', 'products.manufacture_id', '=', 'manufacture.manufacture_id') ->select('products.*', 'category.category_name', 'manufacture.manufacture_name') ->where('products.publication_status', 1) ->limit(9) //->paginate(2); ->get(); return response()->json([ 'success' => true, 'data' => $all_published_product ], 200); } public function show_product_by_category($category_id) { $product_by_category = DB::table('products') ->join('category', 'products.category_id', '=', 'category.category_id') //->join('manufacture', 'products.manufacture_id', '=', 'manufacture.manufacture_id') ->select('products.*', 'category.category_name') ->where('category.category_id', $category_id) ->where('products.publication_status', 1) ->limit(10) //->paginate(2); ->get(); return response()->json([ 'success' => true, 'data' => $product_by_category ], 200); } public function show_product_by_manufacture($manufacture_id) { $product_by_manufacture = DB::table('products') ->join('category', 'products.category_id', '=', 'category.category_id') ->join('manufacture', 'products.manufacture_id', '=', 'manufacture.manufacture_id') ->select('products.*', 'category.category_name', 'manufacture.manufacture_name') ->where('manufacture.manufacture_id', $manufacture_id) ->where('products.publication_status', 1) ->limit(18) ->get(); return response()->json([ 'success' => true, 'data' => $product_by_manufacture, ], 200); } public function product_details_by_id($product_id) { $product_by_details = DB::table('products') ->join('category', 'products.category_id', '=', 'category.category_id') ->join('manufacture', 'products.manufacture_id', '=', 'manufacture.manufacture_id') ->select('products.*', 'category.category_name', 'manufacture.manufacture_name') ->where('products.product_id', $product_id) ->where('products.publication_status', 1) ->first(); //->limit(18) //->get(); return response()->json([ 'success' => true, 'data' => $product_by_details, ], 200); } } <file_sep>/app/Category.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Product; class Category extends Model { protected $table = 'categories'; protected $primaryKey = 'category_id'; protected $fillable = [ 'category_name', 'category_description', 'status', ]; public $timestamps = true; // public function products() // { // return $this->hasMany(Product::class); // } public function product() { return $this->hasOne(Product::class); } } <file_sep>/app/Customer.php <?php namespace App; use App\WishList; use App\Review; use Illuminate\Database\Eloquent\Model; class Customer extends Model { protected $table = 'customer'; protected $primaryKey = 'customer_id'; protected $fillable = [ 'customer_name', 'customer_email', '<PASSWORD>', 'mobile_number', ]; public function reviews() { return $this->hasMany(Review::class); } public function wishlists() { return $this->hasMany(WishList::class); } } <file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use App\Customer; use App\Product; use App\Review; use App\WishList; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; //use Illuminate\Support\Facades\Redirect; //use App\Http\Requests; //use Session; session_start(); class HomeController extends Controller { public function index() { $all_published_product = DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.category_id') ->join('manufactures', 'products.manufacture_id', '=', 'manufactures.manufacture_id') ->select('products.*', 'categories.category_name', 'manufactures.manufacture_name') ->where('products.status', 'enable') ->limit(9) ->get(); //return view('pages.home_content', compact('all_published_product')); return response()->json([ 'success' => true, 'data' => $all_published_product, 'message' => 'All Successfully Published Products !!!', ], 200); } public function show_product_by_category($category_id) { $product_by_category = DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.category_id') //->join('manufacture', 'products.manufacture_id', '=', 'manufacture.manufacture_id') ->select('products.*', 'categories.category_name') ->where('categories.category_id', $category_id) ->where('products.status', 'enable') ->limit(10) ->get(); //return view('pages.category_by_products', compact('product_by_category')); return response()->json([ 'success' => true, 'data' => $product_by_category, 'message' => 'All Successfully Published Product Category !!!', ], 200); } public function show_product_by_manufacture($manufacture_id) { $product_by_manufacture = DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.category_id') ->join('manufactures', 'products.manufacture_id', '=', 'manufactures.manufacture_id') ->select('products.*', 'categories.category_name', 'manufactures.manufacture_name') ->where('manufactures.manufacture_id', $manufacture_id) ->where('products.status', 'enable') ->limit(18) ->get(); //return view('pages.manufacture_by_products', compact('product_by_manufacture')); return response()->json([ 'success' => true, 'data' => $product_by_manufacture, 'message' => 'All Successfully Published Product Manufacture !!!', ], 200); } public function product_details_by_id($product_id) { $product_by_details = DB::table('products') ->join('categories', 'products.category_id', '=', 'categories.category_id') ->join('manufactures', 'products.manufacture_id', '=', 'manufactures.manufacture_id') ->select('products.*', 'categories.category_name', 'manufactures.manufacture_name') ->where('products.product_id', $product_id) ->where('products.status', 'enable') ->first(); //->limit(18) //->get(); //return view('pages.product_details', compact('product_by_details')); return response()->json([ 'success' => true, 'data' => $product_by_details, 'message' => 'Products By Details !!!', ], 200); } public function productReview($product_id) { $product = Product::findOrFail($product_id); $review = Review::all()->where('product_id', $product_id); //return view('pages.reviews.show', compact('product', 'review')); return response()->json([ 'success' => true, 'data' => $product, $review, 'message' => 'Product Review !!!', ], 200); } public function wishList(Request $request) { // $this->validate($request, [ // 'customer_name' => 'required', // ]); // $customer_name = $request->customer_name; // $customer_id = $request->customer_id; // $customer_id = DB::table('customer') // ->where('customer_name', $customer_name) // ->where('customer_id', $customer_id) // ->get(); $wishList = new WishList(); $wishList->customer_id = Session::get('customer_id'); $wishList->product_id = $request->product_id; // $wishList->customer()->associate($customer_id); $wishList->save(); //return redirect()->back()->with('success', 'Product Added To WishList'); return response()->json([ 'success' => true, //'data' => $product_by_details, 'message' => 'Wish List Saved Successfully !!!', ], 200); // $products = DB::table('products')->where('product_id', $request->product_id)->get(); // return view('pages.product_details', compact('products')); } public function view_wishList() { $products = DB::table('wish_lists')->leftJoin('products', 'wish_lists.product_id', '=', 'products.product_id')->get(); //return view('pages.wishList', compact('products')); return response()->json([ 'success' => true, 'data' => $products, 'message' => 'View Wish List !!!', ], 200); } public function removeWishList($id) { DB::table('wish_lists')->where('product_id', '=', $id)->delete(); //return back()->with('success', 'Product Removed From WishList'); return response()->json([ 'success' => true, // 'data' => $product_by_details, 'message' => 'Products By Details !!!', ], 200); } } <file_sep>/app/AboutUs.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class AboutUs extends Model { protected $table = 'about_us'; protected $primaryKey = 'id'; protected $fillable = [ 'name', 'years_of_experience', 'email', 'company', 'website', 'status', ]; } <file_sep>/app/Http/Controllers/SliderController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Redirect; use App\Http\Requests; use App\Slider; use Illuminate\Support\Carbon; use Session; session_start(); class SliderController extends Controller { public function index() { $sliders = Slider::simplePaginate(4); return view('admin.slider.index', compact('sliders')); } public function create() { return view('admin.slider.create'); } public function save_slider(Request $request) { $data = array(); $data['status'] = $request->status; $data['created_at'] = Carbon::now(); //->toDateString(); $data['updated_at'] = Carbon::now(); //->toDateString(); //toDateTimeString $image = $request->file('slider_image'); if ($image) { $image_name = str_random(20); $ext = strtolower($image->getClientOriginalExtension()); $image_full_name = $image_name.'.'.$ext; $upload_path = 'slider/'; $image_url = $upload_path.$image_full_name; $success = $image->move($upload_path, $image_full_name); if ($success) { $data['slider_image'] = $image_url; DB::table('sliders')->insert($data); Session::put('message', 'Slider Added Successfully!!'); return Redirect::to('/sliders'); } } $data['slider_image'] = ''; DB::table('sliders')->insert($data); Session::put('message', 'Slider Added Successfully Without Image!!'); return Redirect::to('/sliders'); } // public function all_slider() // { // $all_slider = DB::table('slider')->get(); // return view('admin.slider.index', compact('all_slider')); // } public function delete_slider($id) { DB::table('sliders') ->where('id', $id) ->delete(); Session::get('message', 'Slider Deleted successfully !!'); return Redirect::to('/sliders'); } public function unactive_slider($id) { DB::table('sliders') ->where('id', $id) ->update(['status' => 0 ]); Session::put('message', 'Slider Unactivated successfully !!'); return Redirect::to('/sliders'); } public function active_slider($id) { DB::table('sliders') ->where('id', $id) ->update(['status' => 1 ]); Session::put('message', 'Slider Activated successfully !!'); return Redirect::to('/sliders'); } } <file_sep>/app/Http/Controllers/Admin/AdminController.php <?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; class AdminController extends Controller { public function registered() { $members = User::all(); //return view('admin.register')->with('members', $members); return view('admin.auth.register', compact('members')); } public function edit(Request $request, $id) { $members = User::findOrFail($id); return view('admin.auth.edit', compact('members')); } public function update(Request $request, $id) { $members = User::findOrFail($id); $members->name = $request->input('username'); $members->usertype = $request->input('usertype'); $members->update(); return redirect('/role-register')->with('successMsg', 'Your Data Was Successfully Updated ):'); } public function delete($id) { $member = User::findOrFail($id); $member->delete(); return redirect('/role-register')->with('successMsg', 'Your Data Was Successfully Deleted ):'); } } <file_sep>/database/factories/ProductFactory.php <?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Category; use App\Manufacture; use App\Product; use App\User; use Faker\Generator as Faker; $factory->define(Product::class, function (Faker $faker) { // return [ // 'product_name' => $faker->word, // 'product_short_description' => $faker->paragraph, // 'product_long_description' => $faker->paragraph, // 'product_price' => $faker->numberBetween(1000, 20000), // 'product_size' => $faker->paragraph, // 'product_color' => $faker->paragraph, // 'publication_status' => $faker->numberBetween(0, 1), // 'user_id' => function() { // return User::all()->random(); // }, // 'category_id' => function() { // return Category::all()->random(); // }, // 'manufacture_id' => function() { // return Manufacture::all()->random(); // }, // ]; }); <file_sep>/app/Product.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\User; use App\Review; use App\Category; use App\Manufacture; class Product extends Model { protected $table = 'products'; protected $primaryKey = 'product_id'; protected $fillable = [ 'category_id', 'manufacture_id', 'product_name', 'product_description', 'product_price', 'stock', 'product_image', 'product_size', 'product_color', 'status', ]; public $timestamps = true; /** * Get the reviews of the product * * */ public function reviews() { return $this->hasMany(Review::class, 'product_id'); } public function category() { return $this->belongsTo(Category::class); } public function manufacture() { return $this->belongsTo(Manufacture::class); } public function recalculateRating() { //$reviews = $this->reviews()->notSpam()->approved(); $avgRating = $reviews->avg('rating'); $this->rating_cache = round($avgRating,1); $this->rating_count = $reviews->count(); $this->save(); } /** * Get the user that added the product. * * */ // public function users() // { // return $this->belongsToMany(User::class); // // return $this->belongsTo(User::class, 'user_id'); // } } <file_sep>/app/Http/Controllers/Admin/DashboardController.php <?php namespace App\Http\Controllers\Admin; use App\Category; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Manufacture; use App\Product; class DashboardController extends Controller { // public function dashboard() // { // return view('admin.dashboard'); // } public function index() { $categoryCount = Category::count(); $manufactureCount = Manufacture::count(); $productCount = Product::count(); // $itemCount = Item::count(); // $sliderCount = Slider::count(); // $reservations = Reservation::where('status', false)->get(); // $contactCount = Contact::count(); return view('admin.dashboard', compact('categoryCount', 'manufactureCount', 'productCount')); } } <file_sep>/app/Appointment.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Service; class Appointment extends Model { protected $table = 'appointments'; protected $primaryKey = 'id'; protected $fillable = [ 'service_id', 'firstName', 'lastName', 'date', 'time', 'gender', 'email', 'phone', 'message', 'status', ]; public function service() { return $this->belongsTo(Service::class); } } <file_sep>/app/Manufacture.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Product; class Manufacture extends Model { protected $table = 'manufactures'; protected $primaryKey = 'manufacture_id'; protected $fillable = [ 'manufacture_name', 'manufacture_description', 'status', ]; public $timestamps = true; public function products() { return $this->hasMany(Product::class); } }
34fa36705181c8b4ea30e136fd3c26db09688fd7
[ "PHP" ]
33
PHP
ucking44/mobileApp
064c89087a52de1c42df339b5a6056ff646db6a9
6992bad03fd274ede79c26b5a6388f79580987b9
refs/heads/master
<repo_name>vipinhelloindia/OpenLibra-Material<file_sep>/app/src/main/java/com/saulmm/openlibra/activities/DetailActivity.java package com.saulmm.openlibra.activities; import android.animation.Animator; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.v7.graphics.Palette; import android.support.v7.widget.Toolbar; import android.transition.Transition; import android.view.View; import android.view.ViewPropertyAnimator; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.saulmm.openlibra.R; import com.saulmm.openlibra.fragments.BooksFragment; import com.saulmm.openlibra.models.Book; import com.saulmm.openlibra.other.CustomAnimatorListener; import com.saulmm.openlibra.other.CustomTransitionListener; import com.saulmm.openlibra.views.Utils; public class DetailActivity extends Activity { // UI Stuff private FrameLayout contentCard; private View fabButton; private View titleContainer; private View titlesContainer; private Book selectedBook; private LinearLayout bookInfoLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); // Recover items from the intent final int position = getIntent().getIntExtra("position",0); selectedBook = (Book) getIntent().getSerializableExtra("selected_book"); titlesContainer = findViewById(R.id.activity_detail_titles); // Recover book cover from BooksFragment cache Bitmap bookCoverBitmap = BooksFragment.photoCache.get(position); ImageView toolbarBookCover = (ImageView) findViewById(R.id.activity_detail_cover); toolbarBookCover.setImageBitmap(bookCoverBitmap); // Fab button fabButton = findViewById(R.id.activity_detail_fab); fabButton.setScaleX(0); fabButton.setScaleY(0); // Book summary card contentCard = (FrameLayout) findViewById(R.id.card_view); Utils.configuredHideYView(contentCard); // Book info layout bookInfoLayout = (LinearLayout) findViewById(R.id.activity_detail_book_info); Utils.configuredHideYView(bookInfoLayout); // Title container titleContainer = findViewById(R.id.activity_detail_title_container); Utils.configuredHideYView(titleContainer); // Define toolbar as the shared element final Toolbar toolbar = (Toolbar) findViewById(R.id.activity_detail_toolbar); toolbar.setBackground(new BitmapDrawable(getResources(), bookCoverBitmap)); toolbar.setTransitionName("cover" + position); // Add a listener to get noticed when the transition ends to animate the fab button getWindow().getSharedElementEnterTransition().addListener(sharedTransitionListener); // Generate palette colors Palette.generateAsync(bookCoverBitmap, paletteListener); } /** * I use a listener to get notified when the enter transition ends, and with that notifications * build my own coreography built with the elements of the UI * * Animations order * * 1. The image is animated automatically by the SharedElementTransition * 2. The layout that contains the titles * 3. An alpha transition to show the text of the titles * 3. A scale animation to show the book info */ private CustomTransitionListener sharedTransitionListener = new CustomTransitionListener() { @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); ViewPropertyAnimator showTitleAnimator = Utils.showViewByScale(titleContainer); showTitleAnimator.setListener(new CustomAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); titlesContainer.startAnimation(AnimationUtils.loadAnimation(DetailActivity.this, R.anim.alpha_on)); titlesContainer.setVisibility(View.VISIBLE); Utils.showViewByScale(fabButton).start(); Utils.showViewByScale(bookInfoLayout).start(); } }); showTitleAnimator.start(); } }; @Override public void onBackPressed() { ViewPropertyAnimator hideTitleAnimator = Utils.hideViewByScaleXY(fabButton); titlesContainer.startAnimation(AnimationUtils.loadAnimation(DetailActivity.this, R.anim.alpha_off)); titlesContainer.setVisibility(View.INVISIBLE); Utils.hideViewByScaleY(bookInfoLayout); hideTitleAnimator.setListener(new CustomAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { ViewPropertyAnimator hideFabAnimator = Utils.hideViewByScaleY(titleContainer); hideFabAnimator.setListener(new CustomAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); coolBack(); } }); } }); hideTitleAnimator.start(); } private Palette.PaletteAsyncListener paletteListener = new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { if (palette.getVibrantSwatch() != null) { Palette.Swatch vibrantSwatch = palette.getVibrantSwatch(); titleContainer.setBackgroundColor(vibrantSwatch.getRgb()); getWindow().setStatusBarColor(vibrantSwatch.getRgb()); getWindow().setNavigationBarColor(vibrantSwatch.getRgb()); TextView summaryTitle = (TextView) findViewById(R.id.activity_detail_summary_title); summaryTitle.setTextColor(vibrantSwatch.getRgb()); TextView titleTV = (TextView) titleContainer.findViewById(R.id.activity_detail_title); titleTV.setTextColor(vibrantSwatch.getTitleTextColor()); titleTV.setText(selectedBook.getTitle()); TextView subtitleTV = (TextView) titleContainer.findViewById(R.id.activity_detail_subtitle); subtitleTV.setTextColor(vibrantSwatch.getTitleTextColor()); subtitleTV.setText(selectedBook.getAuthor()); ((TextView) titleContainer.findViewById(R.id.activity_detail_subtitle)) .setTextColor(vibrantSwatch.getTitleTextColor()); } } }; private void coolBack() { try { super.onBackPressed(); } catch (NullPointerException e) { // TODO: workaround } } } <file_sep>/README.md ## An example of how implement an adapter using Palette to tint each cell in a RecyclerView. ![](https://lh3.googleusercontent.com/-tSvezqWH5Sc/VGnprr1k1DI/AAAAAAAAxLc/U7-jN2Am5yo/w1200-h1064-no/palette_adapter.gif) ## Building my own choreography with SharedElements ![](https://lh3.googleusercontent.com/-3L0DTHYEdO8/VIhqAwbNBiI/AAAAAAAAy2Q/wD_yJXvK6Ho/w822-h1482-no/expand_animation.gif)<file_sep>/app/src/main/java/com/saulmm/openlibra/views/Utils.java package com.saulmm.openlibra.views; import android.animation.ArgbEvaluator; import android.animation.ObjectAnimator; import android.view.View; import android.view.ViewPropertyAnimator; import android.view.animation.PathInterpolator; @SuppressWarnings("UnnecessaryLocalVariable") public class Utils { public final static int COLOR_ANIMATION_DURATION = 1000; public final static int DEFAULT_DELAY = 0; public static void animateViewColor (View v, int startColor, int endColor) { ObjectAnimator animator = ObjectAnimator.ofObject(v, "backgroundColor", new ArgbEvaluator(), startColor, endColor); animator.setInterpolator(new PathInterpolator(0.4f,0f,1f,1f)); animator.setDuration(COLOR_ANIMATION_DURATION); animator.start(); } public static void configuredHideYView (View v) { v.setScaleY(0); v.setPivotY(0); } public static ViewPropertyAnimator hideViewByScaleXY(View v) { return hideViewByScale(v, DEFAULT_DELAY, 0, 0); } public static ViewPropertyAnimator hideViewByScaleY(View v) { return hideViewByScale(v, DEFAULT_DELAY, 1, 0); } public static ViewPropertyAnimator hideViewByScalyInX(View v) { return hideViewByScale(v, DEFAULT_DELAY, 0, 1); } private static ViewPropertyAnimator hideViewByScale (View v, int delay, int x, int y) { ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(delay) .scaleX(x).scaleY(y); return propertyAnimator; } public static ViewPropertyAnimator showViewByScale (View v) { ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(DEFAULT_DELAY) .scaleX(1).scaleY(1); return propertyAnimator; } }
65f1d7c59c81908b4597fdc49fa0d0e6edd31625
[ "Markdown", "Java" ]
3
Java
vipinhelloindia/OpenLibra-Material
eca1be3dd223a101258bbf68da9c5f8e826e171b
d0758b8bee36bf1b2a117df2414ae02cc64cf791
refs/heads/master
<repo_name>ANSHUL-original/Top-SeCret<file_sep>/main/urls.py from django.conf.urls import url from .views import about,home,contactus,single,posts,delete_v,edit #login views import from .views import login_v,logout_v,register #website urls from .views import arun,contact,index,trip,confirm urlpatterns = [ url(r'^arun/$',arun,name='arun'), url(r'^contact/$',contact,name='contact'), url(r'^index/$',index,name='index'), url(r'^trip/$',trip,name='trip'), url(r'^confirm/$', confirm,name='confirm'), url(r'^register/$', register, name='register'), url(r'^logout/$', logout_v, name='logout_v'), url(r'^single/(?P<id>\d+)/$',single,name='single'), url(r'^edit/(?P<id>\d+)/$',edit,name='edit'), url(r'^delete/(?P<id>\d+)/$',delete_v,name='delete_v'), url(r'^posts/$',posts,name='posts'), url(r'^about/$', about, name='about'), url(r'^contactus/$', contactus, name='contactus'), url(r'^home/$', home, name='home'), url(r'^$', login_v, name='login_v') ]<file_sep>/admin.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from. models import Post,T_Model # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ['name','email','phone','profession'] search_fields = ['name','email'] class TestAdmin(admin.ModelAdmin): list_display = ['name','email','contact','city'] search_fields = ['name', 'phone'] admin.site.register(Post, PostAdmin) admin.site.register(T_Model, TestAdmin) <file_sep>/templates/posts.html {% extends "base.html" %} {% block content %} <header> <title>post title</title> </header> <h3>posts</h3> {% for obj in obj_list %} <div style="text-align:center;color:blue;padding:10px"> <p>{{ obj.id }}</p> <a href="/single/{{ obj.id }}"><h4>{{ obj.name }}</h4></a> <h5>{{ obj.email }}</h5> <h6>{{ obj.phone }}</h6> <h6>{{ obj.profession }}</h6> <br><br><br><br> </div> {% endfor %} {% endblock content %}<file_sep>/main/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Post(models.Model): name=models.CharField(max_length=50) email= models.EmailField(max_length=50) phone= models.CharField(max_length=50) profession= models.CharField(max_length=50) class T_Model(models.Model): name= models.CharField(max_length=30) email= models.CharField(max_length=30) contact =models.CharField(max_length=15) city = models.CharField(max_length=15) #nationality = models.CharField(max_length=20) <file_sep>/templates/single.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <header> <title>single title</title> </header> <h2>single page {{ instance.id }}</h3> <p>{{ instance.name }}</p> <p>{{ instance.email }}</p> <p>{{ instance.phone }}</p> <p>{{ instance.profession }}</p> <a href="/edit/{{ instance.id }}">Edit</a> <a href="/delete/{{ instance.id }}">Delete</a> <form method="POST" action="">{% csrf_token %} {{ form|crispy }} <input type="submit" name="submit"> </form> {% endblock content %}<file_sep>/main/forms.py from django import forms from .models import Post from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) from .models import T_Model class NPostForm(forms.Form): name=forms.CharField() email= forms.CharField() phone= forms.CharField() profession= forms.CharField() class MPostForm(forms.ModelForm): class Meta: model = Post fields = [ 'name', 'email', 'phone', 'profession' ] #login forms User = get_user_model()#? class UserLoginForm(forms.Form): username= forms.CharField() password= forms.CharField(widget=forms.PasswordInput) class UserRegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'password', 'confirm_password', ] class T_Form(forms.ModelForm): class Meta: model = T_Model fields = ['name' ,'email','contact', 'city',]<file_sep>/main/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render,redirect,get_object_or_404 from .models import Post from .forms import NPostForm,MPostForm from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) from .forms import UserRegisterForm,UserLoginForm from .forms import T_Form from .models import T_Model # Create your views here. #normal form def home(request): if request.user.is_authenticated(): form= NPostForm(request.POST or None) if form.is_valid(): name= form.cleaned_data.get('name') email=form.cleaned_data.get('email') phone=form.cleaned_data.get('phone') profession= form.cleaned_data.get('profession') instance = Post() instance.name=name instance.email=email instance.phone=phone instance.profession=profession instance.save() form = NPostForm() context = { 'form':form } return render(request, "home.html", context) #Model Form def about(request): if request.user.is_authenticated(): form = MPostForm(request.POST or None) if form.is_valid(): new_post= form.save(commit=False) new_post=form.save() form=MPostForm() context = { 'form':form } return render(request, "about.html", context) def contactus(request): if request.user.is_authenticated(): return render(request, "contactus.html",{}) #website forms def trip(request): form = T_Form(request.POST or None) if form.is_valid(): new_post= form.save(commit=False) new_post=form.save() return redirect('/confirm/') context = { 'form':form } return render(request, "trip.html", context) #single,posts,edit,delete_v def single(request ,id=None): if request.user.is_authenticated(): instance=get_object_or_404(Post, id=id) context = { 'instance':instance } return render(request, 'single.html', context) def posts(request): if request.user.is_authenticated(): query= Post.objects.all() context= { 'obj_list':query } return render(request, 'posts.html', context) def edit(request, id=None): if request.user.is_authenticated(): ins=get_object_or_404(Post, id=id)#? form = MPostForm(request.POST or None,instance=ins) if form.is_valid(): up_post = form.save(commit=False) up_post.save() return redirect('/single/'+id) context = { 'form':form } return render(request, "edit.html", context) def delete_v(request, id=None): if request.user.is_authenticated(): instance=get_object_or_404(Post,id=id) #? instance.delete() return redirect('/posts/') #login views def login_v(request): form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) try: login(request, user) return redirect('/home/') except: return redirect('/register/') context = { 'form':form } return render(request, 'login.html' ,context) def register(request): form= UserRegisterForm(request.POST or None) if form.is_valid(): usr= form.save(commit=False) password= form.cleaned_data.get('<PASSWORD>') confirm_password= form.cleaned_data.get('confirm_password') if password == confirm_password: usr.set_password(password) usr.save() user= authenticate(username=usr.username, password=<PASSWORD>) login(request,user) return redirect ('/home/') context = { 'form':form } return render(request, 'register.html', context) def logout_v(request): if request.user.is_authenticated(): logout(request) return redirect('/') #website views def arun(request): return render(request, 'arun.html', {}) def index(request): return render(request, 'index.html', {}) def contact(request): return render(request, 'contact.html', {}) def confirm(request): return render(request, 'confirm.html',{})
07ff653e33c91c9baf3fbbe8c1b661381f2cd163
[ "Python", "HTML" ]
7
Python
ANSHUL-original/Top-SeCret
cf3ed0eb369e5551661d641661424e8713f488a1
19b686dd96d53d0b87fd0615ea2fcc094e035f0d
refs/heads/master
<file_sep># taxfree-searcher Simple code to generate a database comparing airport tax-free and vinmonopolet using their respective APIs. # Structure - db_creator.py - create sqlite database to store values - filedump.py - simple file to dump output to file - main.py - file to search tax-free.no for goods, and lookup at vinmonopolet for corresponding prices - taxfree.py - lookup taxfree products using the algoli api - vinmonopolet.py - lookup for products using the vinmonopolet api # Required keys A app id and secret is needed for the algoli api with search priveliges. An api key is needed for the vinmonopolet api with access to the "open" api.<file_sep>from algoliasearch.search_client import SearchClient class TaxFree: def __init__(self): appid = '' apikey = '' self.client = SearchClient.create(appid, apikey) self.index = self.client.init_index('products') def search(self, search_string, category, sub_category=None, sub_sub_category=None): # Search without sub-category is a bad idea, as the max returned search items is 1k page = 0 hits = [] if sub_sub_category is not None: category_filter = 'categoryPathHierarchy.lvl1:"{} > {} > {}"'.format(category.capitalize(), sub_category.capitalize(), sub_sub_category.capitalize()) elif sub_category is not None: category_filter = 'categoryPathHierarchy.lvl1:"{} > {}"'.format(category.capitalize(), sub_category.capitalize()) else: category_filter = 'categoryPathHierarchy.lvl0:{}'.format(category.capitalize()) while True: result = self.index.search(search_string, { 'filters': category_filter, 'hitsPerPage': 100, 'page': page }) hits.extend(result['hits']) total_pages = result['nbPages'] page = result['page'] + 1 if page > total_pages: return hits def browse(self, category): # Browse needs to be allowed by the api key search_category = category.capitalize() result = self.index.browse_objects( { 'filters': 'categoryPathHierarchy.lvl0:{}'.format(search_category), 'query': '', }) return result <file_sep>import sqlite3 db = sqlite3.connect('database') cursor = db.cursor() cursor.execute(''' CREATE TABLE products(id INTEGER PRIMARY KEY, timestamp TEXT, barcode TEXT, category TEXT, sub_category TEXT, tf_name TEXT, vm_name TEXT, tf_price REAL, vm_price REAL, diff_price REAL, perc_diff_price REAL) ''') db.commit() db.close() <file_sep>import requests import json class Vinmonopolet: def __init__(self): self.apikey = '' self.headers = {'Ocp-Apim-Subscription-Key': self.apikey} def search(self, search_string): search_string = search_string.split(" ")[0] url = 'https://apis.vinmonopolet.no/products/v0/details-normal' \ '?productShortNameContains={}'.format(search_string) response = requests.get(url=url, headers=self.headers) return json.loads(response.text) <file_sep>from taxfree import TaxFree import json search = TaxFree() for vine_type in ['rødvin', 'hvitvin', 'rosévin', 'ressertvin', 'musserende', 'sterkvin', 'perlende vin']: with open('{}.json'.format(vine_type), 'w') as outfile: json.dump(search.search('', 'vin', vine_type), outfile) with open('beer.json', 'w') as outfile: beers = search.search('', 'øl') json.dump(beers, outfile) with open('brennevin.json', 'w') as outfile: fortified = search.search('', 'brennevin') json.dump(fortified, outfile) <file_sep>from taxfree import TaxFree from vinmonopolet import Vinmonopolet import sqlite3 import datetime def get_vm_product_price(tf_name, tf_barcode): for vm_product in vm.search(tf_name): vm_name = vm_product['basic']['productLongName'] vm_barcodes = vm_product['logistics']['barcodes'] if len(vm_product['prices']) >= 1: vm_price = vm_product['prices'][0]['salesPrice'] else: return None, None for vm_barcode in vm_barcodes: if vm_barcode['gtin'] == tf_barcode: return vm_name, vm_price return None, None def lookup_and_store_search(tf_search_result, tf_search_category, tf_search_sub_category): for tf_product in tf_search_result: tf_name = tf_product['name'] tf_barcode = tf_product['ean'] tf_price = tf_product['price']['value'] vm_name, vm_price = get_vm_product_price(tf_name, tf_barcode) if vm_price is not None: diff_price = vm_price - tf_price perc_diff_price = (diff_price/vm_price)*100 else: diff_price = None perc_diff_price = None print('Product name TaxFree: {}'.format(tf_name)) print('Product price TaxFree: {}.00'.format(tf_price)) print('Product name Vinmonopolet: {}'.format(vm_name)) print('Product price Vinmonopolet: {}'.format(vm_price)) print('') print('************************************') cursor.execute('''INSERT INTO products(timestamp, barcode, category, sub_category, tf_name, vm_name, tf_price, vm_price, diff_price, perc_diff_price) VALUES(?,?,?,?,?,?,?,?,?,?)''', (datetime.datetime.now().isoformat(), tf_barcode, tf_search_category, tf_search_sub_category, tf_name, vm_name, tf_price, vm_price, diff_price, perc_diff_price)) db.commit() vm = Vinmonopolet() tf = TaxFree() db = sqlite3.connect('database') cursor = db.cursor() for vine_type in ['Rødvin', 'Hvitvin', 'Rosévin', 'Dessertvin', 'Musserende', 'Sterkvin', 'Per<NAME>']: category = 'vin' tf_search = tf.search('', category, vine_type) lookup_and_store_search(tf_search, category, vine_type) for fortified_vine_type in ['Aperitiff', 'Bitter', 'Eplebrennevin', 'Grappa', 'Tequila & Mezcal', 'Likør', 'Akevitt', 'Brandy', 'Cognac', 'Gin', 'Rom', 'Vodka', 'Armagnac', 'Whisky', 'Brennevin under 22%']: category = 'brennevin' tf_search = tf.search('', category, fortified_vine_type) lookup_and_store_search(tf_search, category, fortified_vine_type) for beer_type in ['Lager og pils', 'Hveteøl', 'Ale', 'Belgisk stil', 'Stout og porter', 'Sider', 'Øvrige']: category = 'øl' tf_search = tf.search('', category, beer_type) lookup_and_store_search(tf_search, category, beer_type) db.close()
840250ab3d84e5bfda25b496d04f1a1ee7a3b934
[ "Markdown", "Python" ]
6
Markdown
christiandt/taxfree-searcher
0590b266d6209f90803a11e9334b477b155e4694
908fb07b2b915ff00f139738df57934535d79ae7
refs/heads/master
<repo_name>programinurdu/DoubleTablesASPNETMVC5<file_sep>/DoubleTablesASPNETMVC5/Scripts/Site.js // On Clicking Student Logo Image, then change the image function ChangePicture() { $('#upload').click(); } function ReadURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#image').attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } $(document).ready(function () { $('#myTable2').dataTable(); }); $(document).ready(function () { $('#myTable').dataTable({ "scrollY": '50vh', "scrollCollapse": true, "paging": false, "ajax": { "url": "/Student/StudentsList", "type": "GET", "datatype": "json" }, "columns": [ { "data": "StudentId" }, { "data": "FullName" }, { "data": "Email" }, { "data": "GenderDesc" }, { "data": "Mobile" }, { "data": "Telephone" } ] }); });<file_sep>/DoubleTablesASPNETMVC5/ViewModels/Home/StudentViewModels.cs using DoubleTablesASPNETMVC5.Models.DB; using DoubleTablesASPNETMVC5.ViewModels.Shared; using System; using System.Collections.Generic; using System.Linq; namespace DoubleTablesASPNETMVC5.ViewModels.Home { public class StudentViewModels { public List<Student> GetAllStudents() { List<Student> students = new List<Student>(); using (StudentDB2Context db = new StudentDB2Context()) { List<Student> std = db.Students.ToList(); List<ListTypesData> ltd = db.ListTypesDatas.Where(x => x.ListTypeId == (int)ListTypes.Gender).ToList(); students = std.Join(ltd, ss => ss.Gender, ld => ld.ListTypeDataId, (ss, ld) => new Student() { StudentId = ss.StudentId, FullName = ss.FullName, GenderDesc = ld.Description, Email = ss.Email, Mobile = ss.Mobile, Telephone = ss.Telephone, Notes = ss.Notes }).ToList(); } return students; } public void AddNewStudent(Student student) { using (StudentDB2Context db = new StudentDB2Context()) { db.Students.Add(student); db.SaveChanges(); } } public List<StudentsQualification> GetStudentQualificationById(int id) { List<StudentsQualification> qualifications = new List<StudentsQualification>(); using (StudentDB2Context db = new StudentDB2Context()) { qualifications = db.StudentsQualifications.Where(x => x.StudentId == id).ToList(); } return qualifications; } public Student GetStudentById(int id) { Student student = new Student(); using (StudentDB2Context db = new StudentDB2Context()) { student = db.Students.Where(x => x.StudentId == id).FirstOrDefault(); } return student; } } }<file_sep>/DoubleTablesASPNETMVC5/Models/Student.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DoubleTablesASPNETMVC5.Models.DB { [MetadataType(typeof(StudentMetaData))] public partial class Student { [Display(Name = "Gender")] public string GenderDesc { get; set; } } public class StudentMetaData { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public StudentMetaData() { this.StudentsQualifications = new HashSet<StudentsQualification>(); } public int StudentId { get; set; } [Display(Name = "Full Name:")] public string FullName { get; set; } [Display(Name = "Email:")] public string Email { get; set; } [Display(Name = "Gender:")] [UIHint("GenderDropDownList")] public Nullable<int> Gender { get; set; } [Display(Name = "Mobile:")] public string Mobile { get; set; } [Display(Name = "Telephone:")] public string Telephone { get; set; } [Display(Name = "Notes:")] public string Notes { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<StudentsQualification> StudentsQualifications { get; set; } } }<file_sep>/README.md # DoubleTablesASPNETMVC5 LINQ Learning Tutorial Discussing about LINQ and Entity Framework 6x <file_sep>/DoubleTablesASPNETMVC5/ViewModels/Shared/SystemEnums.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DoubleTablesASPNETMVC5.ViewModels.Shared { public enum ListTypes { Gender = 1, Qualification = 2 } }<file_sep>/DoubleTablesASPNETMVC5/Controllers/StudentController.cs using DoubleTablesASPNETMVC5.Models.DB; using DoubleTablesASPNETMVC5.ViewModels.Home; using System.Collections.Generic; using System.Web.Mvc; namespace DoubleTablesASPNETMVC5.Controllers { public class StudentController : Controller { // GET: Student public ActionResult Index() { return View(); } public ActionResult StudentsList() { StudentViewModels svm = new StudentViewModels(); List<Student> students = svm.GetAllStudents(); //return View(students); return Json(new { data = students }, JsonRequestBehavior.AllowGet); } // New Student Screen public ActionResult NewStudent() { return View(); } [HttpPost, ValidateAntiForgeryToken] public ActionResult NewStudent(Student student) { if (ModelState.IsValid) { StudentViewModels svm = new StudentViewModels(); svm.AddNewStudent(student); } return View(); } // public ActionResult StudentQualification(int id=0) { if (id == 0) { return RedirectToAction("NewStudent", "Student"); } StudentViewModels svm = new StudentViewModels(); List<StudentsQualification> qualifications = svm.GetStudentQualificationById(id); return View(qualifications); } } }<file_sep>/DoubleTablesASPNETMVC5/Controllers/HomeController.cs using DoubleTablesASPNETMVC5.Models.DB; using DoubleTablesASPNETMVC5.ViewModels.Home; using System.Collections.Generic; using System.Web.Mvc; namespace DoubleTablesASPNETMVC5.Controllers { public class HomeController : Controller { public ActionResult TutorialsList() { return View(); } // GET: Home public ActionResult Index() { StudentViewModels svm = new StudentViewModels(); List<Student> students = svm.GetAllStudents(); return View(students); } public ActionResult LoadDropDownList() { return View(); } public ActionResult Edit(int id=0) { if (id == 0) { return RedirectToAction("Index", "Home"); } StudentViewModels svm = new StudentViewModels(); Student student = svm.GetStudentById(id); LoadDataIntoDropDownList(student); return View("~/Views/Home/LoadDropDownList.cshtml", student); } private void LoadDataIntoDropDownList(Student student) { ViewData["Gender"] = student.Gender; } } }<file_sep>/DoubleTablesASPNETMVC5/ViewModels/Shared/ComboBoxData.cs using DoubleTablesASPNETMVC5.Models.DB; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DoubleTablesASPNETMVC5.ViewModels.Shared { public class ComboBoxData { public static SelectList GetListData(ListTypes listType) { List<SelectListItem> list = new List<SelectListItem>(); using (StudentDB2Context db = new StudentDB2Context()) { list = db.ListTypesDatas.Where(x => x.ListTypeId == (int)listType).Select(x => new SelectListItem { Text = x.Description, Value = x.ListTypeDataId.ToString() }).ToList(); } SelectList lst = new SelectList(list.AsEnumerable(), "Value", "Text"); return lst; } } }
7dcd1bb008cad2f9401201ade94188ace7f9aa6c
[ "JavaScript", "C#", "Markdown" ]
8
JavaScript
programinurdu/DoubleTablesASPNETMVC5
d7d7c1d1b3c786283613c2eb38b2e71a49ce2689
94b1ebbca8ff4ed298e797e18d10ffecea9149cc
refs/heads/master
<file_sep>import pygame import random # Initialize pygame pygame.init() # Create a screen screen = pygame.display.set_mode((800, 600)) # Background background = pygame.image.load("images/background.png") # Title and icon pygame.display.set_caption("Space invaders") icon = pygame.image.load("images/startup.png") pygame.display.set_icon(icon) # Enemy enemyImg = pygame.image.load("images/ufo.png") enemyX = random.randint(0, 800) enemyY = random.randint(50, 150) enemyX_change = 5 enemyY_change = 6 def enemy(x, y): screen.blit(enemyImg, (x,y)) # Enemy bulletImg = pygame.image.load("images/bullet.png") bulletX = 0 bulletY = 480 bulletX_change = 0 bulletY_change = 10 # Ready state means you cna't see the bullet state on the screen # And fire the bullet is currently moving bullet_state = 'ready' def fire_bullet(x, y): global bullet_state bullet_state = 'fire' screen.blit(bulletImg, (x + 16, y + 10)) # Player playerImg = pygame.image.load("images/space-invaders.png") playerX = 370 playerY = 480 playerX_change = 0 def player(x, y): screen.blit(playerImg, (x, y)) # Game loop running = True while running: screen.fill((0, 0, 0)) screen.blit(background, (80, 60)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # If keystroke is pressed check wehther it's left or right if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerX_change = -5 if event.key == pygame.K_RIGHT: playerX_change = 5 if event.key == pygame.K_SPACE: fire_bullet(playerX, bulletY) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerX_change = 0 playerX += playerX_change if playerX <= 0: playerX = 0 elif playerX >= 736: playerX = 736 enemyX += enemyX_change if enemyX <= 0: enemyY += enemyY_change enemyX_change = 5 elif enemyX >= 736: enemyY += enemyY_change enemyX_change = -5 # Bullet movement if bullet_state == 'fire': fire_bullet(playerX, bulletY) bulletY -= bulletY_change player(playerX, playerY) enemy(enemyX, enemyY) pygame.display.update()<file_sep># space-invaders-game Space Invaders Game with Python and pygame Requirements. Just install pygame library : # pip install pygame
ef36628e1b5178ac66e02aabeee616c8e503378d
[ "Markdown", "Python" ]
2
Python
Josias1997/space-invaders-game
6e3e2f695f0f2a97b632bf0d8721d4eb6772e630
f3c763900204ea4bdaef7eef54204323c435d213
refs/heads/master
<repo_name>SamJaimes/Russian-Dolls-App<file_sep>/russiandoll.js $(document).ready(function() { function hidedolls() { $(".doll1").css("visibility", "hidden"); $(".doll2").css("visibility", "hidden"); $(".doll3").css("visibility", "hidden"); $(".doll4").css("visibility", "hidden"); $(".doll5").css("visibility", "hidden"); $(".doll6").css("visibility", "hidden"); }; $("#doll1").click(function() { hidedolls(); $(".doll1").css("visibility", "visible"); }) $("#doll2").click(function() { hidedolls(); $(".doll2").css("visibility", "visible"); }) $("#doll3").click(function() { hidedolls(); $(".doll3").css("visibility", "visible"); }) $("#doll4").click(function() { hidedolls(); $(".doll4").css("visibility", "visible"); }) $("#doll5").click(function() { hidedolls(); $(".doll5").css("visibility", "visible"); }) $("#doll6").click(function() { hidedolls(); $(".doll6").css("visibility", "visible"); }) }); //doc ready <file_sep>/README.md Russian Dolls App using JS/JQuery
a98a92bba6f9f3dc8e1d8d9f992cfa2648c9fd76
[ "JavaScript", "Markdown" ]
2
JavaScript
SamJaimes/Russian-Dolls-App
c4345291953db97910ec97539937b5120944dd31
fdc0e861ec16cebc18c9a92fef49421fe1350173
refs/heads/master
<file_sep># Pontifícia Universidade Católica do Rio Grande do Sul # Escola Politécnica # Disciplina de Sistemas Operacionais # Prof. Avelino Zorzo # ---------------------------- # <NAME> (Engenharia de Software) # <EMAIL> # <NAME> (Ciência da Computação) # <EMAIL> # Maio/2018 # ---------------------------- # Simulador de Escalonamento de Software # Este programa foi desenvolvido para a disciplina de SisOp da FACIN # (Escola Politécnica/PUCRS). Trata-se de um um script para simular # uma fila no modelo Round Robin com prioridades fixas. # O programa lê um imput de dados representando processos e deve # simular seu processo de CPU e I/O, imprimindo ao final uma String # que demonstre os processos ao longo do tempo, bem como os dados de # Tempo de Resposta e Tempo de Espera médios. from collections import deque import process as proc class Scheduler: def __init__(self, processes, timeslice=2, context_shift_size=1): self.timeslice = timeslice self.context_shift_size = context_shift_size self.processes = processes self.processes_count = len(self.processes) # todo: use proper queue instead self.INCOME_QUEUE = self.processes # Keeps a copy of the original requests list (Will update Processes as they change) self.original_requests = list(self.INCOME_QUEUE) # Process being executed self.running_process = None # Ready Queue (Processes that are ready to execute) # todo: use proper queue instead self.READY_QUEUE = [] # todo: use proper queue instead # High Priority Queue (Ready processes with same priority as Running Process) self.PRIORITY_QUEUE = deque() # IO Queue: Handles processes that are currently in IO self.IO_QUEUE = [] # Handles Context Shift (Will bypass Context Shift when Processor is Idle similar to Moodle example) self.context_shift_counter = 1 # Current time self.time = 1 # Resulting String displaying Processes over Time self.log = "" def clock(self): self.time = self.time + 1 def has_process_to_run(self): return self.INCOME_QUEUE or self.READY_QUEUE or self.PRIORITY_QUEUE or self.running_process or self.IO_QUEUE def run(self): # Checks if any requests have become ready arrivals = self.get_new_arrivals() if arrivals: self.enqueue_processes(arrivals) # Checks if Context Shift is occurring if self.should_switch_context(): self.switch_context() return if self.should_run_process(): self.run_process() else: self.write_log("-") if(self.running_process): if self.running_process.start_io(): self.enqueue_io() if (self.IO_QUEUE): for p in self.IO_QUEUE: p.run_io() IO_COPY = list(self.IO_QUEUE) for p in IO_COPY: if p.get_io_counter() == 0: self.IO_QUEUE.remove(p) arrivals.append(p) if(arrivals): for p in arrivals: if(self.should_run_process()): if p.get_priority() == self.running_process.get_priority(): self.PRIORITY_QUEUE.appendleft(p) else: self.READY_QUEUE.append(p) else: self.READY_QUEUE.append(p) # Handles Ready Queue and High-Priority Queue if self.READY_QUEUE: # Creates a copy of the ready list and sorts it by priority (maintains queue order at original Ready list) sorted_ready = list(self.READY_QUEUE) sorted_ready.sort(key=lambda p: p.priority, reverse=False) # Assigns a process to be run if processor is idle # (Does not trigger Context Shift accordingly with Moodle Example) if not self.running_process: if(self.PRIORITY_QUEUE): self.running_process = self.PRIORITY_QUEUE.popleft() elif(sorted_ready): self.running_process = sorted_ready[0] self.remove_ready_process(self.running_process) # Swaps processes if there is a process with higher priority than current process, resets Context Shift elif sorted_ready[0].get_priority() < self.running_process.get_priority(): new_priority = sorted_ready[0].get_priority() # Returns Running Process and High Priority Queue to Ready Queue # Will maintain High Priority queue order and append Running Process last self.enqueue_ready_process(self.running_process) while self.PRIORITY_QUEUE: self.enqueue_ready_process(self.PRIORITY_QUEUE.popleft()) # Creates new High Priority Queue with new highest priority and assigns Running Process self.PRIORITY_QUEUE = deque() READY_COPY = list(self.READY_QUEUE) for p in READY_COPY: if p.get_priority() == new_priority: self.enqueue_priority_process(p) self.remove_ready_process(p) self.running_process = self.PRIORITY_QUEUE.popleft() self.context_shift_counter = 0 # If there are new processes with same priority as running process, adds them to priority_queue elif sorted_ready[0].get_priority() == self.running_process.get_priority(): READY_COPY = list(self.READY_QUEUE) for p in READY_COPY: if p.get_priority() == self.running_process.get_priority(): self.enqueue_priority_process(p) self.remove_ready_process(p) self.clock() def report(self): average_response_time, average_turn_around_time, average_waiting_time = self.calc_averages() self.print_all_processes() self.print_execution_log() self.print_time_averages(average_response_time, average_turn_around_time, average_waiting_time) def print_time_averages(self, average_response_time, average_turn_around_time, average_waiting_time): print("Average Response Time: " + str(average_response_time)) print("Average Waiting Time: " + str(average_waiting_time)) print("Average Turn Around Time: " + str(average_turn_around_time)) def calc_averages(self): n = 0 total_response_time = 0 total_waiting_time = 0 total_turn_around_time = 0 for p in self.original_requests: total_response_time += p.get_response_time() total_waiting_time += p.get_waiting_time() total_turn_around_time += p.get_turn_around_time() n += 1 average_response_time = total_response_time / n average_waiting_time = total_waiting_time / n average_turn_around_time = total_turn_around_time / n return average_response_time, average_turn_around_time, average_waiting_time def print_all_processes(self): print(" P AT BT Pri CT TAT WT RT IO") for p in self.original_requests: print("%3d %3d %3d %3d %3d %3d %3d %3d %3s" % ( p.get_number(), p.get_arrival_time(), p.get_burst_time(), p.get_priority(), p.get_completion_time(), p.get_turn_around_time(), p.get_waiting_time(), p.get_response_time(), str(p.get_io_times()))) def print_execution_log(self): print("\nProcessor Log:\n" + self.log) def run_process(self): self.running_process.execute(self.time) self.write_log(self.running_process.get_number()) # Finishes process if it is done if self.running_process.is_done(): self.running_process.finish(self.time) self.context_shift_counter = 0 if self.PRIORITY_QUEUE: self.running_process = self.PRIORITY_QUEUE.popleft() else: self.running_process = None return if self.timeslice_has_ended(): self.running_process.reset_quantum_counter() self.context_shift_counter = 0 if self.PRIORITY_QUEUE: self.enqueue_priority_process(self.running_process) self.running_process = self.PRIORITY_QUEUE.popleft() def remove_ready_process(self, p): self.READY_QUEUE.remove(p) def should_switch_context(self): return self.context_shift_counter < self.context_shift_size def has_new_arrivals(self): for req in self.INCOME_QUEUE: if not (req.get_arrival_time() == self.time): return True return False def get_new_arrivals(self): arrivals = [] COPY_INCOME_QUEUE = list(self.INCOME_QUEUE) for process in COPY_INCOME_QUEUE: if not (process.get_arrival_time() == self.time): continue self.INCOME_QUEUE.remove(process) arrivals.append(process) return arrivals def enqueue_processes(self, arrivals): for process in arrivals: if self.running_process and process.get_priority() == self.running_process.get_priority(): self.enqueue_priority_process(process) else: self.enqueue_ready_process(process) def enqueue_ready_process(self, process): self.READY_QUEUE.append(process) def enqueue_priority_process(self, process): self.PRIORITY_QUEUE.append(process) def enqueue_io(self): self.IO_QUEUE.append(self.running_process) if(self.PRIORITY_QUEUE): self.running_process = self.PRIORITY_QUEUE.popleft() else: self.running_process = None self.context_shift_counter = 0 def switch_context(self): self.write_log("C") self.context_shift_counter += 1 self.clock() def write_log(self, message): self.log += str(message) def should_run_process(self): return bool(self.running_process) def timeslice_has_ended(self): return self.running_process.get_quantum_counter() == self.timeslice if __name__ == "__main__": scheduler = proc.Reader("input.txt").read_scheduler() while scheduler.has_process_to_run(): scheduler.run() scheduler.report()<file_sep># todo: move scheduler into this module from main import Scheduler class Reader: def __init__(self, filename): self.file = open(filename) def read_scheduler(self): processes_count = int(self.file.readline()) timeslice = int(self.file.readline()) processes = [] # data format: AT BT P for number, line in enumerate(self.file.readlines(), start=1): line_data = [] for x in line.split(" "): line_data.append(int(x)) if len(line_data) == 3: process = Process(number, line_data[0], line_data[1], line_data[2], []) processes.append(process) elif len(line_data) >= 4: io_times = [] for i in range(3, len(line_data)): io_times.append(line_data[i]) process = Process(number, line_data[0], line_data[1], line_data[2], io_times) processes.append(process) self.file.close() return Scheduler(processes, timeslice) class Process: def __init__(self, number, arrival_time, burst_time, priority, io_times): self.number = number self.arrival_time = arrival_time self.burst_time = burst_time self.remaining_burst = burst_time self.priority = priority self.quantum_counter = 0 self.turn_around_time = 0 self.response_time = -1 self.waiting_time = 0 self.completion_time = 0 self.io_times = io_times self.io_counter = 0 def get_number(self): return self.number def get_arrival_time(self): return self.arrival_time def get_burst_time(self): return self.burst_time def get_remaining_burst(self): return self.remaining_burst def get_priority(self): return self.priority def get_response_time(self): return self.response_time def get_waiting_time(self): return self.waiting_time def get_quantum_counter(self): return self.quantum_counter def get_turn_around_time(self): return self.turn_around_time def get_completion_time(self): return self.completion_time def get_io_times(self): return self.io_times def get_io_counter(self): return self.io_counter # Executes Process for one time unit def execute(self, time): self.remaining_burst -= 1 self.quantum_counter += 1 if self.response_time == -1: self.response_time = time - self.arrival_time def start_io(self): if (self.burst_time - self.remaining_burst) in self.io_times: self.io_counter = 4 self.io_times.remove(self.burst_time - self.remaining_burst) return True return False def run_io(self): self.io_counter -= 1 def reset_quantum_counter(self): self.quantum_counter = 0 def is_done(self): return self.get_remaining_burst() <= 0 # calculates requested data def finish(self, time): self.completion_time = time self.turn_around_time = self.completion_time - self.arrival_time self.waiting_time = self.turn_around_time - self.burst_time
f193052b4ab68e2d26414430f34926b790a0acd4
[ "Python" ]
2
Python
henriale/SO-RR-scheduling-script
5760f522f0d427d9387f79e17255b325d5af2a32
8691cdd160e0e825b8a2abf8cb64a8d661d03339
refs/heads/master
<file_sep>;(function($) { var attempts = 0, limit = 10, delay = 250; var dp = document.createElement('script'); dp.setAttribute('src', 'https://github.com/ericclemmons/de-pagify/raw/master/depagify.jquery.js'); document.getElementsByTagName('head')[0].appendChild(dp); var checkForDepagify = function() { setTimeout(function() { if (++attempts === limit) { alert('Could not load De-Pagify after ' + attempts + ' attempts.'); return false; } if (typeof $.fn.depagify === 'undefined') { checkForDepagify(); } else { $('<div>De-Pagify Loaded!</div>').css({ 'position': 'fixed', 'display': 'inline', 'top': '1em', 'right': '1em', 'padding': '2em', 'color': 'white', 'border': '0.25em solid rgba(100%, 100%, 100%, 0.25)', 'background': '#000', 'box-shadow': '0 0.25em 1em rgba(0, 0, 0, 0.5)', '-moz-box-shadow': '0 0.25em 1em rgba(0, 0, 0, 0.5)', '-webkit-box-shadow': '0 0.25em 1em rgba(0, 0, 0, 0.5)', 'border-radius': '1em', '-moz-border-radius': '1em', '-webkit-border-radius': '1em' }).hide() .appendTo('body') .fadeIn('slow') .animate({opacity: 1.0}, 3000) .fadeOut('slow', function() { $(this).remove(); }); } }, delay); }; checkForDepagify(); })(jQuery);<file_sep># De-Pagify v2.0 (Infinite Scroll) De-pagify let's you easily enable [endless scroll][el] for paged sites such as [fmylife][fml], [digg][digg], [failblog][fb] to enable functionality similar to [Bing image search][bing] on any site that has a *More &raquo;*, *Next &raquo;* or similar link. The latest code & documentation will *always* be available at [http://github.com/ericclemmons/de-pagify](http://github.com/ericclemmons/de-pagify), but is also available at [http://plugins.jquery.com/project/de-pagify](http://plugins.jquery.com/project/de-pagify) ## [Infinite Scroll Demo][demo] ## Usage Typical usage will follow the pattern: jQuery(container).depagify(trigger, options); * __container__: Container for content on the remote page and where it will be placed on the local page. * __trigger__: Link to "click" for the next page's content ### Options * __find__: (_defaults to `*`_) Selector or function to filter remote content * __threshold__: (_defaults to `0.90`_) Float, integer, string or function to determine when to load remote content. The default is `0.90`, which is `90%`. You can use `167`, for example, to load content when the user scrolls within `167px` of the bottom of the page. Also, you can specify a selector (such as `#footer`) to load content when the `#footer` element scrolls into view. Finally, you can write your own function that returns `true` whenever you'd like load the next page's content. * __effect__: (_defaults to `$(this).show()`_) Function to transition newly loaded content. (New content is wrapped by `$('<div />).hide()`) * __events__: `request` & `success` events are triggered before and after the GET request. ## Bookmarklets * [jQuerify Bookmarklet][jq] which will inject jQuery into the page * [De-pagify][dpbm] bookmarklet will inject the latest De-Pagify into the page ## Conclusion If you can help in any way, please fork this project or provide feedback. [demo]: http://uxdriven.com/static/js/uxdriven/jquery/de-pagify/demo.php "De-Pagify Demo" [el]: http://uipatternfactory.com/p=endless-scrolling/ "Endless Scroll" [fml]: http://www.fmylife.com "F My Life" [digg]: http://digg.com "Digg" [fb]: http://failblog.org "Failblog" [bing]: http://www.bing.com/images/search?q=jquery "jQuery Images" [jq]: http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet "jQuerify" [dpbm]: https://github.com/ericclemmons/de-pagify/raw/master/bookmarklet.jquery.min.js [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/ericclemmons/de-pagify/trend.png)](https://bitdeli.com/free "Bitdeli Badge") <file_sep>;(function($) { $('.nextprev:last').depagify({ trigger: '#footer', container: 'div.main', filter: '.news-summary', request: function(options) { jQuery('.pages', options.container).remove(); } }); })(jQuery);<file_sep><?php $page = (int) $_SERVER['QUERY_STRING']; if (empty($page)) { $page = 1; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>De-Pagify Demo</title> <link rel="stylesheet" href="http://uxdriven.com/static/blueprint/screen.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="http://uxdriven.com/static/blueprint/print.css" type="text/css" media="print"> <!--[if lt IE 8]><link rel="stylesheet" href="http://uxdriven.com/static/blueprint/ie.css" type="text/css" media="screen, projection"><![endif]--> <link rel="stylesheet" href="http://uxdriven.com/static/blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" type="text/javascript" charset="utf-8"></script> <script src="https://github.com/ericclemmons/de-pagify/raw/master/depagify.jquery.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> var depagify = function() { jQuery('#content').depagify('#pages a:last', { delay: 500, // Wait 500ms between subsequent requests filter: '.post', // Only include .post objects threshold: '#footer', // When #footer is in view effect: jQuery(this).slideDown, events: { request: function() { // Remove the navigation jQuery('#pages', this).remove(); }, success: function() { console.log('Another page loaded!'); } } }); }; </script> </head> <body> <div class="container"> <h1>Welcome to the De-Pagify Demo</h1> <button onClick="javascript:depagify();">De-Pagify</button> <div id="header"> <blockquote> <p>I'm tons of filler, like very other site, so we can enjoy sexy scrolling.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </blockquote> </div> <hr /> <div id="content"> <div class="post"> <h3> Imagine I'm the #<?= $page ?> post on the page </h3> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </div> <div id="pages"> <strong><?= $page ?></strong> <?php if ($page < 10) : ?><a href="?<?= ++$page ?>">Next &raquo;</a><?php endif; ?> </script> </div> </div> <hr /> <div id="footer"> <blockquote> <p>I'm the site's footer.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </blockquote> </div> </div> </body> </html>
daf1b5c1db62b979972919728b9d147e4c74bf12
[ "JavaScript", "PHP", "Markdown" ]
4
JavaScript
ericclemmons/de-pagify
34b757e508d60d1beeb10d3926b50647bced0a76
5b3ac32d18d1c02e8c5220fb8e739ab258405fe4
refs/heads/master
<file_sep>package ir.droidhub.mobilebazz.adpter; import android.widget.Filter; import ir.droidhub.mobilebazz.sql.obj.MyObj; import java.util.ArrayList; import java.util.List; /** * Created by MI3 on 4/29/2016. */ class DogsFilter extends Filter { private AutoCompleteDogsAdapter adapter; private List<MyObj> originalList; private List<MyObj> filteredList; DogsFilter(AutoCompleteDogsAdapter adapter, List<MyObj> originalList) { super(); this.adapter = adapter; this.originalList = originalList; this.filteredList = new ArrayList<>(); } @Override protected FilterResults performFiltering(CharSequence constraint) { filteredList.clear(); final FilterResults results = new Filter.FilterResults(); if (constraint == null || constraint.length() == 0) { filteredList.addAll(originalList); } else { final String filterPattern = constraint.toString().toLowerCase().trim(); // Your filtering logic goes in here for (final MyObj myObj : originalList) { // if (MyObj.title.toLowerCase().contains(filterPattern)) { filteredList.add(myObj); // } } } results.values = filteredList; results.count = filteredList.size(); return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { adapter.filteredDogs.clear(); adapter.filteredDogs.addAll((List<MyObj>) results.values); adapter.notifyDataSetChanged(); } }<file_sep>package ir.droidhub.mobilebazz.cntdb; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class SqlBaseCnt { public static String DB_PATH; public static String DB_NAME = "content.db"; //Table h_post public static final String TBL_NAME_H_POST = "h_post"; public static final String TBL_H_POST_POST_ID = "post_id"; public static final String TBL_H_POST_POST_AUTHOR = "post_author"; public static final String TBL_H_POST_POST_DATE = "post_date"; public static final String TBL_H_POST_POST_CONTENT = "post_content"; public static final String TBL_H_POST_POST_TITLE = "post_title"; public static final String TBL_H_POST_COMMENT_COUNT = "comment_count"; public static final String TBL_H_POST_COMMENT_STATUS = "comment_status"; public static final String TBL_H_POST_POST_PIC = "post_pic"; //Table h_post_cat public static final String TBL_NAME_H_POST_CAT = "h_post_cat"; public static final String TBL_H_POST_CAT_POST_ID = "post_id"; public static final String TBL_H_POST_CAT_TERM_TAXONOMY_ID = "term_taxonomy_id"; //Table h_comment public static final String TBL_NAME_H_COMMENT = "h_comment"; public static final String TBL_H_COMMENT_POST_ID = "comment_id"; public static final String TBL_H_COMMENT_COMMENT_POST_ID = "comment_post_id"; public static final String TBL_H_COMMENT_COMMENT_AUTHOR = "comment_author"; public static final String TBL_H_COMMENT_COMMENT_DATE = "comment_date"; public static final String TBL_H_COMMENT_COMMENT_CONTENT = "comment_content"; public static final String TBL_H_COMMENT_COMMENT_PARENT = "comment_parent"; //Table h_cats public static final String TBL_NAME_H_CATS = "h_cats"; public static final String TBL_H_CATS_TERM_TAXONOMY_ID = "term_id"; public static final String TBL_H_CATS_NAME = "name"; public static final String TBL_H_CATS_PARENT = "parent"; public static final String TBL_H_CATS_COUNT = "count"; public static final String TBL_H_CATS_DESCRIPTION = "description"; //Table h_appost public static final String TBL_NAME_H_APPOST = "h_appost"; public static final String TBL_H_APPOST_POST_ID = "post_id"; public static final String TBL_H_APPOST_POST_AUTHOR = "post_author"; public static final String TBL_H_APPOST_POST_DATE = "post_date"; public static final String TBL_H_APPOST_POST_CONTENT = "post_content"; public static final String TBL_H_APPOST_POST_TITLE = "post_title"; public static final String TBL_H_APPOST_COMMENT_COUNT = "comment_count"; public static final String TBL_H_APPOST_COMMENT_STATUS = "comment_status"; public static final String TBL_H_APPOST_POST_PIC = "post_pic"; public static final String TBL_H_APPOST_POST_ORDER= "post_order"; public static final String TBL_H_APPOST_POST_MENU= "menu"; Context mycontext; public SqlBaseCnt(Context context) { mycontext = context; } public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and empty database will be created into // the default system path // of your application so we are gonna be able to overwrite that // database with our database. try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } // //////////////////////////////////////////////////////////////////////////////////////////////// public boolean checkDataBase() { SQLiteDatabase checkDB = null; try { DB_PATH = "/data/data/" + mycontext.getApplicationContext().getPackageName() + "/"; // Log.i("Place", "Path:" + DB_PATH); String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE); } catch (SQLiteException e) { // database does't exist yet. } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false; } // //////////////////////////////////////////////////////////////////////////////////////////////// private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = mycontext.getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); // Log.i("Place", "Copy Succ!!!"); } } <file_sep>package ir.droidhub.mobilebazz.pref; import java.util.HashSet; import java.util.Set; import android.content.Context; public class Pref { private static final String PREF="pref"; public static final String PREFS_SEARCH_HISTORY = "SearchHistory"; Context context; public Pref(Context context) { // TODO Auto-generated constructor stub this.context = context; } public static Set<String> GetLastSearch(Context context){ return context.getSharedPreferences(PREF,Context.MODE_PRIVATE) .getStringSet(PREFS_SEARCH_HISTORY, new HashSet<String>()); } public static void SetLastSearch(Set<String> value,Context context){ context.getSharedPreferences(PREF,Context.MODE_PRIVATE) .edit().putStringSet(PREFS_SEARCH_HISTORY,value).apply(); } public static boolean getIsSetPermission(Context context){ return context.getSharedPreferences(PREF,Context.MODE_PRIVATE) .getBoolean(PREFS_SEARCH_HISTORY, false); } public static void setIsSetPermission(boolean value,Context context){ context.getSharedPreferences(PREF,Context.MODE_PRIVATE) .edit().putBoolean(PREFS_SEARCH_HISTORY,value).apply(); } } <file_sep>package ir.droidhub.mobilebazz; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import ir.droidhub.mobilebazz.api.LinkMaker; import ir.droidhub.mobilebazz.api.Parse; import ir.droidhub.mobilebazz.adpter.AdpComment; import ir.droidhub.mobilebazz.adpter.AdpFragmentPager; import ir.droidhub.mobilebazz.adpter.FragmentCreator; import ir.droidhub.mobilebazz.api.GetSetting; import ir.droidhub.mobilebazz.api.HTMLBuilder; import ir.droidhub.mobilebazz.api.Net; import ir.droidhub.mobilebazz.api.view.ExtensiblePageIndicator; import ir.droidhub.mobilebazz.api.view.HamiWebView; import ir.droidhub.mobilebazz.api.web.AsyncDataNet; import ir.droidhub.mobilebazz.cntdb.ObjAppPost; import ir.droidhub.mobilebazz.cntdb.ObjComment; import ir.droidhub.mobilebazz.cntdb.ObjPost; import ir.droidhub.mobilebazz.cntdb.SqlBaseCnt; import ir.droidhub.mobilebazz.cntdb.SqlSourceCnt; import java.util.ArrayList; import java.util.List; public class v extends AppCompatActivity { private HamiWebView webView; private TextView Title, PostTitle; private GetSetting getSetting; //ActionBar private LinearLayout headerPost, mainLayout; private Toolbar toolbar; private Context context; private Typeface FontApp, Iconfont; private ActionBar actionBar; private String typePost; private ObjPost post, nPost, NotifPost; private ObjAppPost appPost; private ViewPager pager; private AdpFragmentPager adpPager; private ExtensiblePageIndicator ViewPagerIndicator; private List<String> images; private int CommentChecker; private static int NEWCOMMENT = 0; // if send new comment: parent is zero(0) private static int COMMENT_COUNT = 100; private static final String CommentStatusKey = "open"; //Main ListView commentList; TextView PostCat, PostDate, PostAuthor, SendNewComment, CommentTitle; AdpComment adpComment; LinearLayout LayoutTitleCommentList; DrawerLayout drawerLayout; List<ObjComment> lstComment = new ArrayList<>(); private String myTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.act_view); if (getIntent() != null && (getIntent().getFlags() & // Releated to Open post from notification Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) { finish(); return; } context = v.this; getSetting = new GetSetting(context); FontApp = getSetting.getFontApp(); Iconfont = Typeface.createFromAsset(getAssets(), "font/fontawesome-webfont.ttf"); int postID = getIntent().getExtras().getInt("id"); //get Selected Post Id// typePost = getIntent().getExtras().getString("parentList"); //get parent// int CommentCount = getIntent().getExtras().getInt("commentCount"); //get commentCount// Findview(); ActionBar(); adpComment = new AdpComment(context, R.layout.list_comment, lstComment); commentList.setAdapter(adpComment); if (typePost.equals("mainPost")) showPost(postID, CommentCount); else if (typePost.equals("appPost")) showAppost(postID, CommentCount); else if (typePost.equals("notification")) gNotifPost(postID); myTitle = PostTitle.getText().toString(); Listener(postID); } private void Listener(final int postId) { SendNewComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (Net.Is(context)) NewComment(postId); else OfflineSnackBar(); } }); } private int headerGallery(String url_content) { images = HTMLBuilder.GetGallery(url_content); //get image tag adpPager = new AdpFragmentPager(getSupportFragmentManager()); FragmentCreator fmc = new FragmentCreator(); for (int i = 0; i < images.size(); i++) adpPager.addFragment(fmc.newInstance(android.R.color.transparent, images.get(i), images, PostTitle.getText().toString()) ); pager.setAdapter(adpPager); ViewPagerIndicator.initViewPager(pager); if (images.size() < 2) ViewPagerIndicator.setVisibility(View.GONE); if (images.size() == 0) pager.setVisibility(View.GONE); return images.size(); } private void showNotifPost() { if (nPost == null) return; CheckComment(nPost.getPost_id(), nPost.getComment_count() , nPost.getComment_status()); PostCat.setText(getResources().getString(R.string.category) + getCategory(nPost.getPost_id())); PostTitle.setText(nPost.getPost_title()); PostDate.setText(getSetting.date(nPost.getPost_date())); PostAuthor.setText(getResources().getString(R.string.author) + nPost.getPost_author()); int img = headerGallery(nPost.getPost_content()); PostTitle.setText(nPost.getPost_title()); String str = HTMLBuilder.getHtmlForShow(nPost, img); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setDomStorageEnabled(true); settings.setDefaultTextEncodingName("utf-8"); webView.setHorizontalScrollBarEnabled(false); webView.setVerticalScrollBarEnabled(false); webView.setWebViewClient(new MyWebViewClient()); webView.loadDataWithBaseURL("", str, "text/html", "utf-8", ""); } private void showPost(int PostId, int commentCount) { post = gPost(PostId); if (post == null) return; CheckComment(PostId, commentCount, post.getComment_status()); PostCat.setText(getResources().getString(R.string.category) + " : " + getCategory(PostId)); PostTitle.setText(post.getPost_title()); PostDate.setText(getSetting.date(post.getPost_date())); PostAuthor.setText(getResources().getString(R.string.author) + post.getPost_author()); int img = headerGallery(post.getPost_content()); PostTitle.setText(post.getPost_title()); String str = HTMLBuilder.getHtmlForShow(post, img); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setDomStorageEnabled(true); settings.setDefaultTextEncodingName("utf-8"); webView.setHorizontalScrollBarEnabled(false); webView.setVerticalScrollBarEnabled(false); webView.setWebViewClient(new MyWebViewClient()); webView.loadDataWithBaseURL("", str, "text/html", "utf-8", ""); } private ObjPost gPost(int PostId) { List<ObjPost> Post; SqlSourceCnt db = new SqlSourceCnt(context); db.open(); Post = db.GetPost(SqlBaseCnt.TBL_H_POST_CAT_POST_ID + "=" + PostId); db.close(); if (Post.size() > 0) return Post.get(0); else return null; } private void showAppost(int PostId, int commentCount) { appPost = gAppPost(PostId); if (appPost == null) return; CheckComment(PostId, commentCount, appPost.getComment_status()); PostCat.setText(getResources().getString(R.string.category) + getCategory(PostId)); PostTitle.setText(appPost.getPost_title()); PostDate.setText(getSetting.date(appPost.getPost_date())); PostAuthor.setText(getResources().getString(R.string.author) + appPost.getPost_author()); int img = headerGallery(appPost.getPost_content()); PostTitle.setText(appPost.getPost_title()); String str = HTMLBuilder.getHtmlForShow(appPost, img); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setDomStorageEnabled(true); settings.setDefaultTextEncodingName("utf-8"); webView.setHorizontalScrollBarEnabled(false); webView.setVerticalScrollBarEnabled(false); webView.setWebViewClient(new MyWebViewClient()); webView.loadDataWithBaseURL("", str, "text/html", "utf-8", ""); } private ObjAppPost gAppPost(int PostId) { List<ObjAppPost> appPost; SqlSourceCnt db = new SqlSourceCnt(context); db.open(); appPost = db.GetAppPost(SqlBaseCnt.TBL_H_APPOST_POST_ID + "='" + PostId + "'"); db.close(); if (appPost.size() > 0) return appPost.get(0); else return null; } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.indexOf(".png") > 0 || url.indexOf(".jpg") > 0) { Intent gallery_intent = new Intent(context, g.class); gallery_intent.putStringArrayListExtra("images", (ArrayList<String>) images); startActivity(gallery_intent); return true; } if (Net.Is(context)) { Intent browser = new Intent(context, b.class); browser.putExtra("post_url", url); startActivity(browser); return true; } else OfflineSnackBar(); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } } @SuppressLint("NewApi") public void ActionBar() { actionBar = getSupportActionBar(); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); View v = getLayoutInflater().inflate(R.layout.actionbar_actview, null); actionBar.setCustomView(v); toolbar = (Toolbar) v.getParent(); toolbar.setContentInsetsAbsolute(0, 0); Title = (TextView) v.findViewById(R.id.textView_title_actionbar_actview); Title.setText(getSetting.getActionBarTitle());//Set Text Of Title Title.setTypeface(FontApp); Title.setTextSize(15); //Set Color of Title Action Bar Title.setTextColor(Color.parseColor(getSetting.getActionBarTextColor())); //Set Color of Action Bar///// v.setBackgroundColor(Color.parseColor(getSetting.getActionBarColorBackground())); actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(getSetting.getActionBarColorBackground()))); //Set Color of Action Bar///// } private void Findview() { commentList = (ListView) findViewById(R.id.listView_comment); // Adding Layout for Header of Listview LayoutInflater inflater = getLayoutInflater(); ViewGroup header = (ViewGroup) inflater.inflate(R.layout.act_view_header, commentList, false); commentList.addHeaderView(header, null, true); pager = (ViewPager) header.findViewById(R.id.view_pager_actview); ViewPagerIndicator = (ExtensiblePageIndicator) header.findViewById(R.id.flexibleIndicator); webView = (HamiWebView) header.findViewById(R.id.webView_post_content); PostTitle = (TextView) header.findViewById(R.id.textview_post_title); PostTitle.setTextColor(Color.parseColor(getSetting.getHeaderTextColor())); headerPost = (LinearLayout) header.findViewById(R.id.linearLayout_post_header); headerPost.setBackgroundColor(Color.parseColor(getSetting.getHeaderBackground())); mainLayout = (LinearLayout) header.findViewById(R.id.linearlayout_actView); PostDate = (TextView) header.findViewById(R.id.textView_post_date); PostCat = (TextView) header.findViewById(R.id.textView_post_cat); PostAuthor = (TextView) header.findViewById(R.id.textView_post_author); CommentTitle = (TextView) header.findViewById(R.id.textview_listcomment_title); SendNewComment = (TextView) header.findViewById(R.id.textView_listcomment_titleSendNewComment); LayoutTitleCommentList = (LinearLayout) findViewById(R.id.LinearLayout_listcomment_newComment); drawerLayout = (DrawerLayout) findViewById(R.id.actView_drawer_layout_post); PostCat.setTypeface(FontApp); PostTitle.setTypeface(FontApp); PostDate.setTypeface(FontApp); PostAuthor.setTypeface(FontApp); CommentTitle.setTypeface(FontApp); SendNewComment.setTypeface(FontApp); // Reading & replacing data from database(AppSetting) drawerLayout.setBackgroundColor(Color.parseColor(getSetting.getMainColorBackground())); PostTitle.setTextColor(Color.parseColor(getSetting.getHeaderTextColor())); headerPost = (LinearLayout) header.findViewById(R.id.linearLayout_post_header); headerPost.setBackgroundColor(Color.parseColor(getSetting.getHeaderBackground())); LayoutTitleCommentList.setBackgroundColor(Color.parseColor(getSetting.getHeaderBackground())); SendNewComment.setTextColor(Color.parseColor(getSetting.getHeaderTextColor())); CommentTitle.setTextColor(Color.parseColor(getSetting.getHeaderTextColor())); commentList.setBackgroundColor(Color.TRANSPARENT); SendNewComment.setText(getResources().getString(R.string.sendNewComment)); CommentTitle.setText(getResources().getString(R.string.comments)); } @Override protected void onDestroy() { webView.destroy(); super.onDestroy(); } private ObjPost gNotifPost(final int postId) { AsyncDataNet AsyncPost = new AsyncDataNet(context, LinkMaker.getNotifPost(postId)); AsyncPost.setonDone(new AsyncDataNet.onComplete() { @Override public void onDone(String result, int token) { try { nPost = Parse.getNotifPost(result); showNotifPost(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(Exception e, int token) { OfflineSnackBar(); } }); AsyncPost.execute(); return NotifPost; } private void OfflineSnackBar() { Snackbar e_snackBar = Snackbar.make(findViewById(R.id.actView_drawer_layout_post), getResources().getString(R.string.offline_mode) , Snackbar.LENGTH_LONG); TextView tv = (TextView) (e_snackBar.getView()).findViewById(android.support.design.R.id.snackbar_text); tv.setTypeface(FontApp); e_snackBar.show(); } private String getCategory(int PostId) { List<String> mycat; String category = ""; SqlSourceCnt db = new SqlSourceCnt(context); db.open(); mycat = db.GetCatName(PostId); db.close(); if (mycat.size() == 0) PostCat.setVisibility(View.INVISIBLE); else for (int i = 0; i < mycat.size(); i++) { category += mycat.get(i); if (i < mycat.size() - 1) category += ","; } return category; } private void NewComment(final int PostId) { final Dialog sendComment = new Dialog(context); sendComment.requestWindowFeature(Window.FEATURE_NO_TITLE); sendComment.setContentView(R.layout.dlg_comment); sendComment.setCancelable(false); final Button send = (Button) sendComment.findViewById(R.id.button_comment_send); final Button cancel = (Button) sendComment.findViewById(R.id.button_comment_cancel); final EditText name = (EditText) sendComment.findViewById(R.id.editText_comment_dialog_name); TextInputLayout lName = (TextInputLayout) sendComment.findViewById(R.id.input_layout_name); final EditText email = (EditText) sendComment.findViewById(R.id.editText_comment_dialog_email); TextInputLayout lImail = (TextInputLayout) sendComment.findViewById(R.id.input_layout_email); final EditText message = (EditText) sendComment.findViewById(R.id.editText_comment_dialog_commentContent); TextInputLayout lMessage = (TextInputLayout) sendComment.findViewById(R.id.input_layout_textLongMessage); final TextView title = (TextView) sendComment.findViewById(R.id.textView_dlg_title); title.setText(getResources().getString(R.string.sendNewComment)); title.setTypeface(FontApp); send.setTypeface(FontApp); cancel.setTypeface(FontApp); name.setTypeface(FontApp); email.setTypeface(FontApp); message.setTypeface(FontApp); lName.setTypeface(FontApp); lImail.setTypeface(FontApp); lMessage.setTypeface(FontApp); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendComment.dismiss(); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String mName, mEmail, mMessage; mName = name.getText().toString(); mEmail = email.getText().toString(); mMessage = message.getText().toString(); if (mName.length() < 3) Toast.makeText(context, getResources().getString(R.string.incorrectName), Toast.LENGTH_SHORT).show(); else if (!checkEmail(mEmail)) Toast.makeText(context, getResources().getString(R.string.incorrectEmail), Toast.LENGTH_SHORT).show(); else if (mMessage.length() < 3) Toast.makeText(context, getResources().getString(R.string.incorrectText), Toast.LENGTH_SHORT).show(); else { String url = LinkMaker.sendCommentLINK(PostId, mName, mEmail, "url", mMessage, NEWCOMMENT, 0, "", ""); AsyncDataNet AsyncSendComment = new AsyncDataNet(context, url); AsyncSendComment.setonDone(new AsyncDataNet.onComplete() { @Override public void onDone(String result, int token) { int mResult = 0; try { mResult = Parse.SendComment(result); } catch (Exception e) { } if (mResult == 1) Toast.makeText(context, getResources().getString(R.string.sendSuccessfully), Toast.LENGTH_SHORT).show(); else Toast.makeText(context, getResources().getString(R.string.sendError), Toast.LENGTH_SHORT).show(); } @Override public void onError(Exception e, int token) { sendComment.dismiss(); OfflineSnackBar(); } }); AsyncSendComment.execute(); sendComment.dismiss(); } } }); sendComment.show(); } private void CheckComment(int PostId, int CommentCount, String CommentStatus) { if (Net.Is(context) && CommentCount > 0 && (getSetting.getIsShowComment())) GetMyComment(PostId); if (!getSetting.getIsSetComment()) { SendNewComment.setVisibility(View.INVISIBLE); if (CommentCount > 0) LayoutTitleCommentList.setVisibility(View.VISIBLE); else LayoutTitleCommentList.setVisibility(View.INVISIBLE); } else { if (CommentStatus.toLowerCase().equals(CommentStatusKey.toLowerCase())) { // check comment status SendNewComment.setVisibility(View.VISIBLE); LayoutTitleCommentList.setVisibility(View.VISIBLE); } else { SendNewComment.setVisibility(View.INVISIBLE); if (CommentCount > 0) LayoutTitleCommentList.setVisibility(View.VISIBLE); else LayoutTitleCommentList.setVisibility(View.INVISIBLE); } } } public void GetMyComment(final int PostId) { int lastCount = lstComment.size(); AsyncDataNet AsyncComment = new AsyncDataNet(context, LinkMaker.getCommentLINK(COMMENT_COUNT, lastCount, PostId)); AsyncComment.setonDone(new AsyncDataNet.onComplete() { @Override public void onDone(String result, int token) { try { lstComment.addAll(Parse.getCommentPost(result, PostId)); CommentChecker = Parse.getCommentPost(result, PostId).size(); SqlSourceCnt db = new SqlSourceCnt(context); db.open(); db.UpdateComment(lstComment); // reforming data db.close(); adpComment = new AdpComment(context, R.layout.list_comment, getCommentOfflin(PostId)); commentList.setAdapter(adpComment); } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(Exception e, int token) { OfflineSnackBar(); } }); AsyncComment.execute(); } private List<ObjComment> getCommentOfflin(int PostId) { List<ObjComment> lst = new ArrayList<>(); SqlSourceCnt db = new SqlSourceCnt(context); db.open(); lst.addAll(db.GetComment(SqlBaseCnt.TBL_H_COMMENT_COMMENT_POST_ID + "=" + PostId)); db.close(); return lst; } private boolean checkEmail(String email) { // Email Verification int length = email.length(); if (length < 4) return false; else for (int i = 0; i < length; i++) { if (String.valueOf(email.charAt(i)).equals("@")) { return true; } } return false; } } <file_sep>package ir.droidhub.mobilebazz.api.web; import android.content.ContentValues; public class CData { //Properties int id; String url; String local; //Statics public static final String[] COL={SqlBase.CD_ID, SqlBase.CD_URL, SqlBase.CD_LOCAL}; public CData() { // TODO Auto-generated constructor stub } public CData(int id,String url,String local) { setId(id); setLocal(local); setUrl(url); } //Setters public void setId(int id) { this.id = id; } public void setLocal(String local) { this.local = local; } public void setUrl(String url) { this.url = url; } //Getters public int getId() { return id; } public String getLocal() { return local; } public String getUrl() { return url; } public ContentValues getCV(){ ContentValues cv=new ContentValues(); cv.put(SqlBase.CD_URL, getUrl()); cv.put(SqlBase.CD_LOCAL, getLocal()); return cv; } } <file_sep>package ir.droidhub.mobilebazz.adpter; /** * Created by MI3 on 4/28/2016. */ import android.content.Context; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import ir.droidhub.mobilebazz.api.GetFont; import ir.droidhub.mobilebazz.R; import ir.droidhub.mobilebazz.api.cash_pic.ImageLoader; import ir.droidhub.mobilebazz.sql.obj.MyObj; import java.util.List; public class AdpBest extends RecyclerView.Adapter<AdpBest.viewholder> { private List<MyObj> lst; static Context context; private static Typeface fontApp; private ImageLoader imageLoader; public AdpBest(Context context, List<MyObj> lst){ this.lst = lst; AdpBest.context = context; GetFont f = new GetFont(context); imageLoader=new ImageLoader(context); } static class viewholder extends RecyclerView.ViewHolder { TextView title; ImageView img; viewholder(View itemView) { super(itemView); title = (TextView) itemView.findViewById(R.id.list_best_title); img = (ImageView) itemView.findViewById(R.id.list_best_img); // Color Header Text title.setTypeface(fontApp); } } @Override public viewholder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.list_best, parent, false); return new viewholder(v); } @Override public void onBindViewHolder(viewholder view, int position) { imageLoader.DisplayImageNoAnim(lst.get(position).getLst(), view.img); view.title.setText(lst.get(position).getTitle()); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } @Override public int getItemCount() { return lst.size(); } } <file_sep>package ir.droidhub.mobilebazz.adpter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.TextView; import ir.droidhub.mobilebazz.ActShow; import ir.droidhub.mobilebazz.R; import ir.droidhub.mobilebazz.api.cash_pic.ImageLoader; import ir.droidhub.mobilebazz.sql.obj.MyObj; import java.util.ArrayList; import java.util.List; /** * Created by MI3 on 4/29/2016. */ public class AutoCompleteDogsAdapter extends ArrayAdapter<MyObj> { private final List<MyObj> dogs; Context context; public List<MyObj> filteredDogs = new ArrayList<>(); ImageLoader imageLoader; ViewHolder view; LayoutInflater inflater; public AutoCompleteDogsAdapter(Context context, List<MyObj> dogs) { super(context, 0, dogs); this.dogs = dogs; this.context = context; imageLoader=new ImageLoader(context); inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return filteredDogs.size(); } @Override public Filter getFilter() { return new DogsFilter(this, dogs); } @Override public View getView(final int position, View convertView, ViewGroup parent) { // Get the data item from filtered list. if(convertView==null){ convertView = inflater.inflate(R.layout.list_search_suggests, parent, false); view = new ViewHolder(); // MyObj dog = filteredDogs.get(position); view.tvName = (TextView) convertView.findViewById(R.id.search_title); view.ivIcon = (ImageView) convertView.findViewById(R.id.search_img); convertView.setTag(view); } else view = (ViewHolder) convertView.getTag(); view.tvName.setText(dogs.get(position).getTitle()); imageLoader.DisplayImageNoAnim(dogs.get(position).getLst(),view.ivIcon); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { context.startActivity(new Intent(context , ActShow.class).putExtra("name" , dogs.get(position).getTitle())); } }); return convertView; } static class ViewHolder { TextView tvName; ImageView ivIcon; } }<file_sep>package ir.droidhub.mobilebazz.sql.obj; public class Company3 { String ItemOne , Title , ItemTwo; public Company3( String ItemOne ,String Title ,String ItemTwo) { this.ItemOne = ItemOne; this.Title = Title; this.ItemTwo = ItemTwo; } public String GetItemName() { return this.ItemOne; } public String GetTitle() { return this.Title; } public String GetItemTwo() { return this.ItemTwo; } } <file_sep>package ir.droidhub.mobilebazz; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import ir.droidhub.mobilebazz.api.GetSetting; public class b extends AppCompatActivity { private ProgressBar progressBar; private WebView browser; private Typeface FontApp, Iconfont; private Context context; private GetSetting getSetting; private TextView title, close; private LinearLayout actionBar; private SwipeRefreshLayout swipeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.act_browser); context = b.this; getSetting = new GetSetting(context); findView(); browser.loadUrl(getIntent().getExtras().getString("post_url")); browser.setWebViewClient(new MyWebViewClient()); listener(); } private void listener() { browser.setWebChromeClient(new WebChromeClient() { @SuppressLint("NewApi") public void onProgressChanged(WebView view, int progress) { if (progress < 100 && progressBar.getVisibility() == ProgressBar.GONE) { progressBar.setVisibility(ProgressBar.VISIBLE); swipeLayout.setRefreshing(false); } progressBar.setProgress(progress); if (progress == 100) { title.setText(view.getTitle()); progressBar.setVisibility(ProgressBar.GONE); swipeLayout.setRefreshing(false); } } }); close.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(context, v.class ).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); } }); swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeLayout.setRefreshing(true); browser.loadUrl(browser.getUrl()); } }); } private void findView() { FontApp = getSetting.getFontApp(); Iconfont = Typeface.createFromAsset(getAssets(), "font/fontawesome-webfont.ttf"); actionBar = (LinearLayout) findViewById(R.id.linearlayout_actBrowser); actionBar.setBackgroundColor(Color.parseColor(getSetting.getActionBarColorBackground())); progressBar = (ProgressBar) findViewById(R.id.progress_loader); browser = (WebView) findViewById(R.id.actWebview); WebSettings webSettings = browser.getSettings(); webSettings.setJavaScriptEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webSettings.setDisplayZoomControls(false); } webSettings.setBuiltInZoomControls(true); webSettings.setDomStorageEnabled(true); title = (TextView) findViewById(R.id.textview_Actbrowser_Title); title.setTypeface(FontApp); close = (TextView) findViewById(R.id.textview_Actbrowser_close); close.setTypeface(Iconfont); close.setText(R.string.fa_times); close.setTextColor(Color.parseColor(getSetting.getActionBarTextColor())); title.setTextColor(Color.parseColor(getSetting.getActionBarTextColor())); swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); swipeLayout.setColorSchemeResources( android.R.color.holo_blue_dark, android.R.color.holo_green_dark, android.R.color.holo_orange_dark, android.R.color.holo_red_dark); } @Override protected void onDestroy() { browser.getSettings().setBuiltInZoomControls(true); browser.destroy(); super.onDestroy(); } @Override public void onBackPressed() { if (browser.canGoBack()) { browser.goBack(); } else { super.onBackPressed(); } } private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } } } <file_sep>package ir.droidhub.mobilebazz.sql.obj; public class Company { String name; int picname; public Company( String name ,int picname) { this.name = name; this.picname = picname; } public String GetName() { return this.name; } public int GetPicName() { return this.picname; } } <file_sep>package ir.droidhub.mobilebazz; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.design.widget.Snackbar; import android.support.v4.view.GravityCompat; import android.support.v4.view.ScrollingView; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewTreeObserver; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AutoCompleteTextView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import ir.droidhub.mobilebazz.adpter.AdpBest; import ir.droidhub.mobilebazz.adpter.AutoCompleteDogsAdapter; import ir.droidhub.mobilebazz.api.Exit; import ir.droidhub.mobilebazz.api.GetFont; import ir.droidhub.mobilebazz.api.RecyclerItemClickListener; import ir.droidhub.mobilebazz.api.RubyService; import ir.droidhub.mobilebazz.api.SearchArrowDrawable; import ir.droidhub.mobilebazz.api.URLs; import ir.droidhub.mobilebazz.api.s; import ir.droidhub.mobilebazz.api.viewPager_autoScroll.CustomPagerAdp; import ir.droidhub.mobilebazz.sql.Jsons; import ir.droidhub.mobilebazz.sql.SQLbase; import ir.droidhub.mobilebazz.sql.SQLsource; import com.activeandroid.ActiveAndroid; import com.activeandroid.query.Select; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout; import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import ir.droidhub.mobilebazz.adpter.AdpDrawerList; import ir.droidhub.mobilebazz.api.GridSpacingItemDecoration; import ir.droidhub.mobilebazz.api.viewPager_autoScroll.AutoScrollViewPager; import ir.droidhub.mobilebazz.sql.obj.MyObj; import ir.droidhub.mobilebazz.sql.obj.ObjDrawer; import ir.droidhub.mobilebazz.sql.obj.ObjMobile; import ir.droidhub.mobilebazz.sql.obj.ObjSoc; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ActMain extends Activity implements DrawerLayout.DrawerListener { public static final String BASELINK_PHONES = "http://droidhub.ir/phones/"; public static final String BASELINK_COMPANY = "http://droidhub.ir/company/"; private static final String TAG = "MOBILEBAZZ"; private static boolean Loading = true; private static int sizeChecker = 10; private static int COUNT_POST = 40; private static int pageCount = 0; private int count_scroller; // private RelativeLayout blog_layout; // private List<ObjPost> listBlog = new ArrayList<>(); // private List<ObjPost> listBlog_tmp = new ArrayList<>(); private Snackbar snackBar; Context context; RecyclerView soc, mobile; LinearLayoutManager layout_mobile, layout_soc; private DrawerLayout mDrawerLayout; List<MyObj> mList = new ArrayList<>(); List<MyObj> cList = new ArrayList<>(); List<ObjDrawer> lst_drawer = new ArrayList<ObjDrawer>(); AutoScrollViewPager Slider; CustomPagerAdp sliderAdp; TextView mobile_best, mobile_cat, cpu_best, cpu_cat; List<ObjMobile> mobile_suggests = new ArrayList<>(); List<ObjSoc> cpu_suggests = new ArrayList<>(); List<MyObj> suggest_list = new ArrayList<>(); ProgressBar search_pb; List<ObjSoc> lst_cpu; String[] cpu_company = {"allwinner_icon", "exynos_icon", "hisilicon_icon", "intel_icon", "mediatek_icon", "nvidia_icon", "qualcomm_icon", "rockchip_icon"}; AdpBest adpBest_mobile, adpBest_cpu; AutoCompleteDogsAdapter adpSuggest; private ImageView close_search, clear_search; private CardView search_cardView; private AutoCompleteTextView search_input; private SwipyRefreshLayout swipeRefreshLayout; private ProgressBar best_mobs_progress; // private TextView title_blog; // private RecyclerView blog; // private LinearLayoutManager layout_blog; // private AdpBlog adpBlog; Typeface fontApp; private Tracker mTracker; @Override protected void onResume() { super.onResume(); mTracker.setScreenName("Image~" + "Mobilebazz_MainActivity"); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); } private boolean checkWriteExternalPermission() { PackageManager pm = context.getPackageManager(); int hasPerm = pm.checkPermission( android.Manifest.permission.WRITE_EXTERNAL_STORAGE, context.getPackageName()); return hasPerm != PackageManager.PERMISSION_GRANTED; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); ActiveAndroid.initialize(this); setContentView(R.layout.main); context = ActMain.this; if ( (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && checkWriteExternalPermission() ) startActivity(new Intent(this, ActPermission.class)); mTracker = ((s) getApplication()).getDefaultTracker(); fontApp = new GetFont(context).yekan; findViewsById(); drawerList(); showSearchBar(); slider(); prepareSearchList(); loadBestMobs(); loadBestCPUs(); listener(); } private void prepareSearchList() { suggest_list = new ArrayList<MyObj>(); adpSuggest = new AutoCompleteDogsAdapter(context, suggest_list); search_input.setAdapter(adpSuggest); } private void loadBestCPUs() { lst_cpu = new ArrayList<>(); SQLsource db = new SQLsource(context); db.open(); lst_cpu.addAll(db.GetSoc(SQLbase.TBL_SOC, SQLbase.TBL_fav + "=" + 1)); // lst_mobile.addAll(db.GetMob(SQLbase.TBL_Mobile, SQLbase.TBL_MOBILE_cache_image + "=" + 1)); db.close(); for (int i = 0; i < lst_cpu.size(); i++) cList.add(new MyObj(BASELINK_COMPANY + String.valueOf(cpu_company[lst_cpu.get(i).GetCompany()]) + ".png", lst_cpu.get(i).GetNameModel())); adpBest_cpu = new AdpBest(context, cList); soc.setAdapter(adpBest_cpu); } private void loadBestMobs() { best_mobs_progress.setVisibility(View.VISIBLE); Retrofit retrofit = new Retrofit.Builder() .baseUrl(URLs.BASE_URL).addConverterFactory(GsonConverterFactory.create()) .build(); RubyService rubyService = retrofit.create(RubyService.class); Call<List<ObjMobile>> mobs = rubyService.listMobs(); mobs.enqueue(new Callback<List<ObjMobile>>() { @Override public void onResponse(Call<List<ObjMobile>> call, Response<List<ObjMobile>> response) { Log.i(TAG, "onResponse2: " + call.request().headers()); Log.i(TAG, "onResponse3: " + call.request().tag()); Log.i(TAG, "onResponse4: " + call.request().isHttps()); Log.i(TAG, "onResponse5: " + response.raw().toString()); Jsons jsons = new Select().from(Jsons.class).where("id = ?", 1).executeSingle(); if (jsons != null) { Log.i(TAG, "onResponse: Json before exists"); } else { Log.i(TAG, "onResponse: Json created"); new Jsons(Mobile2Json(response.body())).save(); } showBestMobs(response.body()); } @Override public void onFailure(Call<List<ObjMobile>> call, Throwable t) { Log.i(TAG, "onFailure: getMessage" + t.getMessage()); Log.i(TAG, "onFailure: getCause" + t.getCause()); Jsons jsons = new Select().from(Jsons.class).where("id = ?", 1).executeSingle(); if (jsons != null) { Log.i(TAG, "onResponse: Json exists"); try { ArrayList<ObjMobile> ls = new ArrayList<ObjMobile>(); ls.addAll(getMobs(jsons.getContent())); showBestMobs(ls); } catch (JSONException e) { e.printStackTrace(); } } else { Log.i(TAG, "onResponse: Json not exists"); } } }); } private void showBestMobs(List<ObjMobile> body) { for (int i = 0; i < body.size(); i++) { mList.add(new MyObj(BASELINK_PHONES + String.valueOf( body.get(i).GetImage()), body.get(i).GetTitle())); } adpBest_mobile = new AdpBest(context, mList); mobile.setAdapter(adpBest_mobile); swipeRefreshLayout.setRefreshing(false); best_mobs_progress.setVisibility(View.INVISIBLE); } public static List<ObjMobile> getMobs(String jsonData) throws JSONException { List<ObjMobile> lst = new ArrayList<>(); if (jsonData.equals("null")) return lst; JSONArray jArr = new JSONArray(jsonData); for (int i = 0; i < jArr.length(); i++) { JSONObject obj = jArr.getJSONObject(i); lst.add(new ObjMobile(obj.getInt("id"), obj.getString("title"), obj.getString("category"), obj.getString("image"), obj.getString("twognetwork"), obj.getString("threegnetwork"), obj.getString("fourgnetwork"), obj.getString("sim"), obj.getString("announced"), obj.getString("status"), obj.getString("dimensions"), obj.getString("weight"), "obj.getString(\"_type\")", obj.getString("size"), obj.getString("multitouch"), obj.getString("protection"), obj.getString("alerttypes"), obj.getString("loudspeaker"), obj.getString("jack") , obj.getString("cardslot"), obj.getString("phonebook"), obj.getString("callrecords"), obj.getString("internal") , obj.getString("gprs"), obj.getString("edge"), obj.getString("speed"), obj.getString("wlan") , obj.getString("bluetooth"), obj.getString("nfc"), obj.getString("infraredport"), obj.getString("usb") , "obj.getString(\"primary\")", obj.getString("features"), obj.getString("video"), obj.getString("secondary") , obj.getString("os"), obj.getString("chipset"), obj.getString("cpu"), obj.getString("gpu") , obj.getString("sensors"), obj.getString("messaging"), obj.getString("browser"), obj.getString("radio") , obj.getString("games"), obj.getString("clock"), obj.getString("alarm"), obj.getString("gps") , obj.getString("java"), obj.getString("colors"), "obj.getString(\"battrey\")", obj.getString("standby") , obj.getString("talktime"), obj.getString("bodyfeatures"), obj.getString("otherfeatures"), obj.getString("price"), obj.getString("cache_image"))); } return lst; } private String Mobile2Json(List<ObjMobile> body) { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < body.size(); i++) { JSONObject object = new JSONObject(); try { object.put("id", body.get(i).GetId()); object.put("title", body.get(i).GetTitle()); object.put("category", body.get(i).GetCategory()); object.put("image", body.get(i).GetImage()); object.put("twognetwork", body.get(i).GetTwognetwork()); object.put("threegnetwork", body.get(i).GetThreegnetwork()); object.put("fourgnetwork", body.get(i).GetFourgnetwork()); object.put("sim", body.get(i).GetSime()); object.put("announced", body.get(i).GetAnnounced()); object.put("status", body.get(i).GetStatus()); object.put("dimensions", body.get(i).GetDimensions()); object.put("weight", body.get(i).GetWeight()); object.put("_type", body.get(i).GetType()); object.put("size", body.get(i).GetSize()); object.put("multitouch", body.get(i).GetMultitouch()); object.put("protection", body.get(i).GetProtection()); object.put("alerttypes", body.get(i).GetAlerttypes()); object.put("loudspeaker", body.get(i).GetLoudspeaker()); object.put("jack", body.get(i).GetJack()); object.put("cardslot", body.get(i).GetCardslot()); object.put("phonebook", body.get(i).GetPhonebook()); object.put("callrecords", body.get(i).GetCallrecords()); object.put("internal", body.get(i).GetInternal()); object.put("gprs", body.get(i).GetGprs()); object.put("edge", body.get(i).GetEdge()); object.put("speed", body.get(i).GetSpeed()); object.put("wlan", body.get(i).GetWlan()); object.put("bluetooth", body.get(i).GetBluetooth()); object.put("nfc", body.get(i).GetNfc()); object.put("infraredport", body.get(i).GetInfraredport()); object.put("usb", body.get(i).GetUsb()); object.put("primary", body.get(i).GetPrimary()); object.put("features", body.get(i).GetFeatures()); object.put("video", body.get(i).GetVideo()); object.put("secondary", body.get(i).GetSecondary()); object.put("os", body.get(i).GetOs()); object.put("chipset", body.get(i).GetChipset()); object.put("cpu", body.get(i).GetCpu()); object.put("gpu", body.get(i).GetGpu()); object.put("sensors", body.get(i).GetSensors()); object.put("messaging", body.get(i).GetMessaging()); object.put("browser", body.get(i).GetBrowser()); object.put("radio", body.get(i).GetRadio()); object.put("games", body.get(i).GetGames()); object.put("clock", body.get(i).GetClock()); object.put("alarm", body.get(i).GetAlarm()); object.put("gps", body.get(i).GetGps()); object.put("java", body.get(i).GetJava()); object.put("colors", body.get(i).GetColors()); object.put("battrey", body.get(i).GetBattrey()); object.put("standby", body.get(i).GetStandby()); object.put("talktime", body.get(i).GetTalktime()); object.put("bodyfeatures", body.get(i).GetBodyfeatures()); object.put("otherfeatures", body.get(i).GetOtherfeatures()); object.put("price", body.get(i).GetPrice()); object.put("cache_image", body.get(i).GetCache_image()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.i(TAG, "Mobile2Json: " + object.toString()); jsonArray.put(object); } return jsonArray.toString(); } private void drawerList() { mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); ListView mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerLayout.setDrawerListener(this); String[] titles = context.getResources().getStringArray(R.array.option); lst_drawer.add(new ObjDrawer(titles[1], R.string.material_share)); lst_drawer.add(new ObjDrawer(titles[2], R.string.material_send_comment)); lst_drawer.add(new ObjDrawer(titles[3], R.string.material_about_us)); lst_drawer.add(new ObjDrawer(titles[4], R.string.material_exit)); AdpDrawerList adpDrawerList = new AdpDrawerList(context, R.layout.list_drawer, lst_drawer); mDrawerList.setAdapter(adpDrawerList); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); } private void slider() { List<ObjMobile> lst = new ArrayList<>(); List<MyObj> images = new ArrayList<>(); SQLsource db = new SQLsource(context); db.open(); Random r = new Random(); int i1 = r.nextInt(9 - 1) + 1; lst.addAll(db.GetMob(SQLbase.TBL_Mobile, SQLbase.TBL_MOBILE_title + " Like '%" + i1 + "%'")); db.close(); for (int i = 0; i < lst.size(); i++) images.add(new MyObj(BASELINK_PHONES + lst.get(i).GetImage(), lst.get(i).GetTitle())); sliderAdp = new CustomPagerAdp(context, images); Slider.setAdapter(sliderAdp); Slider.setAutoScrollDurationFactor(5); // set change pic time Slider.setInterval(5000); // set show time Slider.startAutoScroll(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { setArrow(); } @Override public void onDrawerClosed(View drawerView) { setHamburger(); } @Override public void onDrawerStateChanged(int newState) { } private class DrawerItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { mDrawerLayout.closeDrawer(GravityCompat.END); if (position == 0) { ApplicationInfo app = getApplicationContext().getApplicationInfo(); String filePath = app.sourceDir; Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("*/*"); sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filePath))); startActivity(Intent.createChooser(sharingIntent, "ارسال " + getResources().getString(R.string.app_name) + " با")); } else if (position == 1) { startActivity(new Intent(Intent.ACTION_EDIT, Uri.parse("http://cafebazaar.ir/app/" + getBaseContext().getPackageName() + "/?l=fa"))); } else if (position == 2) { Intent about = new Intent(getBaseContext(), ActAbout.class); startActivity(about); } else if (position == 3) { Exit(); } } } private void Exit() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) this.finishAffinity(); else finish(); } private void listener() { final ScrollView sw = (ScrollView) findViewById(R.id.scrollView_main); sw.setSmoothScrollingEnabled(true); sw.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { int scrollY = sw.getScrollY(); // For ScrollView int scrollX = sw.getScrollX(); // For HorizontalScrollView // DO SOMETHING WITH THE SCROLL COORDINATES if(sw.getTop()==scrollY){ // reaches the top end swipeRefreshLayout.setEnabled(true); Log.i(TAG, "onScrollChange: Reach to TOP"); }else { swipeRefreshLayout.setEnabled(false); } } }); swipeRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() { @Override public void onRefresh(SwipyRefreshLayoutDirection direction) { loadBestMobs(); } }); // listBlog = new ArrayList<>(); // adpBlog = new AdpBlog(context, listBlog); // blog.setAdapter(adpBlog); // if (Net.Is(context) && listBlog.size() == 0) // GetPost(LinkMaker.getPostLINK(COUNT_POST, listBlog.size())); /* blog.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); int threshold = 1; int lastItemVisable = 1; count_scroller = adpBlog.getItemCount(); lastItemVisable = layout_blog.findLastVisibleItemPosition(); if (newState == 0) { // Checking for rich to end of recyclerView if (lastItemVisable >= count_scroller - threshold && pageCount < 2) { // For checking Scroll And Show Loading . if ((COUNT_POST - sizeChecker == 0) && !Loading) {//internet Loading = true; GetPost(LinkMaker.getPostLINK(COUNT_POST, listBlog.size())); } } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } }); blog.addOnItemTouchListener( new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(context, v.class); intent.putExtra("id", listBlog.get(position).getPost_id()); intent.putExtra("parentList", "mainPost"); intent.putExtra("commentCount", listBlog.get(position).getComment_count()); startActivity(intent); } }) );*/ search_input.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(final CharSequence s, int start, int before, int count) { getSuggestList(s.toString()); } @Override public void afterTextChanged(final Editable s) { clear_search.setVisibility(View.VISIBLE); if (s.length() <= 0) { setHamburger(); flg = true; } else if (flg) { setArrow(); flg = false; } } }); clear_search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { search_input.setText(""); } }); close_search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (mIsSearchArrowHamburgerState == SearchArrowDrawable.STATE_HAMBURGER) { mDrawerLayout.openDrawer(GravityCompat.END); setArrow(); } else if (mIsSearchArrowHamburgerState == SearchArrowDrawable.STATE_ARROW) { mDrawerLayout.closeDrawer(GravityCompat.END); setHamburger(); search_input.setText(""); } } }); cpu_cat.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent cat = new Intent(context, ActCat.class); cat.putExtra("key", 1); startActivity(cat); } }); mobile_cat.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent cat = new Intent(context, ActCat.class); cat.putExtra("key", 2); startActivity(cat); } }); soc.addOnItemTouchListener(new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { startActivity(new Intent(context, ActShow.class).putExtra("name", cList.get(position).getTitle())); } })); mobile.addOnItemTouchListener(new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { startActivity(new Intent(context, ActShow.class).putExtra("name", mList.get(position).getTitle())); } })); } boolean flg = true; private void hideSearchBar() { search_cardView.animate().translationY(-search_cardView.getHeight()).setInterpolator(new AccelerateInterpolator(2)); // search_cardView.setVisibility(View.INVISIBLE); } private void showSearchBar() { search_cardView.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)); search_cardView.setVisibility(View.VISIBLE); } private void getSuggestList(final String s) { search_pb.setVisibility(View.VISIBLE); mobile_suggests = new ArrayList<>(); cpu_suggests = new ArrayList<>(); suggest_list = new ArrayList<>(); final SQLsource db = new SQLsource(context); db.open(); mobile_suggests.addAll(db.GetMob(SQLbase.TBL_Mobile, SQLbase.TBL_MOBILE_title + " Like '%" + s + "%'")); cpu_suggests.addAll(db.GetSoc(SQLbase.TBL_SOC, SQLbase.TBL_name + " Like '%" + s + "%' or " + SQLbase.TBL_nameModel + " Like '%" + s + "%'")); db.close(); for (int i = 0; i < mobile_suggests.size(); i++) suggest_list.add(new MyObj(BASELINK_PHONES + String.valueOf(mobile_suggests.get(i).GetImage()), mobile_suggests.get(i).GetTitle())); for (int i = 0; i < cpu_suggests.size(); i++) suggest_list.add(new MyObj(BASELINK_COMPANY + String.valueOf(cpu_company[cpu_suggests.get(i).GetCompany()]) + ".png", cpu_suggests.get(i).GetNameModel())); search_pb.setVisibility(View.INVISIBLE); search_input.setAdapter(new AutoCompleteDogsAdapter(context, suggest_list)); } private int mAnimationDuration = 300; private SearchArrowDrawable mSearchArrow; private float mIsSearchArrowHamburgerState = SearchArrowDrawable.STATE_HAMBURGER; private void setArrow() { mSearchArrow.setVerticalMirror(false); mSearchArrow.animate(SearchArrowDrawable.STATE_ARROW, mAnimationDuration); mIsSearchArrowHamburgerState = SearchArrowDrawable.STATE_ARROW; } private void setHamburger() { mSearchArrow.setVerticalMirror(true); mSearchArrow.animate(SearchArrowDrawable.STATE_HAMBURGER, mAnimationDuration); mIsSearchArrowHamburgerState = SearchArrowDrawable.STATE_HAMBURGER; } private void findViewsById() { best_mobs_progress = (ProgressBar) findViewById(R.id.progress_recyclerview_main_mobile); best_mobs_progress.setVisibility(View.INVISIBLE); swipeRefreshLayout = (SwipyRefreshLayout) findViewById(R.id.swipe_container); // blog_layout = (RelativeLayout)findViewsById(R.id.relativelayout_blog); RelativeLayout main = (RelativeLayout) findViewById(R.id.main_layout); main.setBackgroundColor(getResources().getColor(R.color.maincolor)); search_pb = (ProgressBar) findViewById(R.id.search_progressbar); search_pb.setVisibility(View.INVISIBLE); GetFont f = new GetFont(context); search_input = (AutoCompleteTextView) findViewById(R.id.search_input); search_input.setTypeface(f.yekan); search_cardView = (CardView) this.findViewById(R.id.card_search); search_cardView.setVisibility(View.INVISIBLE); close_search = (ImageView) this.findViewById(R.id.iv_bottom_search); mSearchArrow = new SearchArrowDrawable(context); close_search.setImageDrawable(mSearchArrow); clear_search = (ImageView) this.findViewById(R.id.iv_bottom_clear); clear_search.setVisibility(View.INVISIBLE); Slider = (AutoScrollViewPager) findViewById(R.id.viewpager_slider); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); soc = (RecyclerView) findViewById(R.id.recyclerview_main_soc); mobile = (RecyclerView) findViewById(R.id.recyclerview_main_mobile); // blog = (RecyclerView) findViewsById(R.id.recyclerview_main_blog); mobile_best = (TextView) findViewById(R.id.textview_mobile_best); mobile_cat = (TextView) findViewById(R.id.textview_mobile_cat); cpu_best = (TextView) findViewById(R.id.textview_cpu_best); cpu_cat = (TextView) findViewById(R.id.textview_cpu_cat); // title_blog = (TextView) findViewsById(R.id.textview_blog_title); // title_blog.setTypeface(f.yekan); mobile_best.setTypeface(f.yekan); mobile_cat.setTypeface(f.yekan); cpu_best.setTypeface(f.yekan); cpu_cat.setTypeface(f.yekan); layout_mobile = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false); layout_soc = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false); // layout_blog = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false); soc.addItemDecoration(new GridSpacingItemDecoration(10)); mobile.addItemDecoration(new GridSpacingItemDecoration(10)); // blog.addItemDecoration(new GridSpacingItemDecoration(10)); // blog.setLayoutManager(layout_blog); soc.setLayoutManager(layout_soc); mobile.setLayoutManager(layout_mobile); } /* private void GetPost(String getLinkPost) { snackBar = Snackbar.make(findViewsById(R.id.drawer_layout), getResources().getString(R.string.loading) , Snackbar.LENGTH_INDEFINITE); TextView tv = (TextView) (snackBar.getView()).findViewsById(android.support.design.R.id.snackbar_text); tv.setTypeface(fontApp); snackBar.show(); AsyncDataNet AsyncPost = new AsyncDataNet(context, getLinkPost); AsyncPost.setonDone(new AsyncDataNet.onComplete() { @Override public void onDone(String result, int token) { try { // listBlog_tmp.clear(); // listBlog_tmp.addAll(Parse.getPost(result)); // Convert Jsons To List // sizeChecker = listBlog_tmp.size(); // For checking Scroll And Show Loading . // listBlog.addAll(listBlog_tmp); // Thread thread = new Thread(new Runnable() { // @Override // public void run() { // // SqlSourceCnt db = new SqlSourceCnt(context); // db.open(); // db.UpdatePost(listBlog_tmp); // reforming data // db.close(); // Loading = false; // snackBar.dismiss(); // // ActMain.this.runOnUiThread(new Runnable() { // @Override // public void run() { // // adpBlog.notifyDataSetChanged(); // // // // if(adpBlog.getItemCount()==0) { // blog_layout.setVisibility(View.GONE); // } // // // // } // }); // // } // }); // thread.start(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(Exception e, int token) { OfflineError(); OfflinePost(); snackBar.dismiss(); Loading = true; } }); AsyncPost.execute(); } */ private void OfflineError() { Snackbar e_snackBar = Snackbar.make(findViewById(R.id.drawer_layout), getResources().getString(R.string.offline_mode) , Snackbar.LENGTH_LONG); TextView txt_snackbar = (TextView) (e_snackBar.getView()).findViewById(android.support.design.R.id.snackbar_text); txt_snackbar.setTypeface(fontApp); e_snackBar.show(); } // private void OfflinePost() { // // listBlog = new ArrayList<>(); // // // SqlSourceCnt db = new SqlSourceCnt(context); // db.open(); // listBlog.addAll(db.GetPost("")); // db.close(); // // adpBlog.notifyDataSetChanged(); // // if(adpBlog.getItemCount()==0) { // blog_layout.setVisibility(View.GONE); // } // // } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) mDrawerLayout.closeDrawer(GravityCompat.END); else Exit.exitSnack(context, findViewById(R.id.drawer_layout), fontApp); } } <file_sep>package ir.droidhub.mobilebazz.api; import android.content.Context; import android.graphics.Typeface; import ir.droidhub.mobilebazz.appdb.ObjSetting; import ir.droidhub.mobilebazz.appdb.SqlBaseApp; import ir.droidhub.mobilebazz.appdb.SqlSourceApp; import ir.droidhub.mobilebazz.cntdb.ObjPost; public class GetSetting { private static final String MainColorBackground = "CLR_MBG"; private static final String ActionBarTitle = "TXT_ACTT"; private static final String ActionBarColorBackground = "CLR_ACTBG"; private static final String ActionBarTextColor = "CLR_ACTTX"; private static final String HeaderBackground = "CLR_LISTHBG"; private static final String HeaderTextColor = "CLR_LISTHTX"; private static final String SummryBackground = "CLR_LISTSBG"; private static final String SummryTextColor = "CLR_LISTSTX"; private static final String FooterBackground = "CLR_LISTFBG"; private static final String FooterTextColor = "CLR_LISTFTX"; private static final String isSetComment = "BOL_SETCOM"; private static final String isShowComment = "BOL_SHOWCOM"; private static final String CollectionData = "BOL_STA"; private static final String TypeShowDate = "NUM_CALTYPE"; public static final String LastVersion = "TXT_LASTANDRVER"; private static final String SplashTime = "NUM_SPLASHT"; private static final String RightMenuTitle = "TXT_MNRTI"; private static final String RightMenuIcon = "TXT_MNRIC"; private static final String LeftMenuSubject = "NUM_MNLTYPE"; private static final String LeftMenuTitle = "TXT_MNLTI"; private static final String LeftMenuIcon = "TXT_MNLIC"; private static final String TypeShowList = "NUM_LVT"; private static final String IconSearchLocation = "NUM_SRCHP"; private static final String IconSearch = "NUM_SRCHIC"; private static final String IconSearchColor = "CLR_SRCHIC"; private static final String FontApp = "NUM_FMAIN"; public static final String YES = "YES"; static Context context; static ObjSetting lst; public GetSetting(Context context) { this.context = context; } public String getFooterBackground() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + FooterBackground + "'").get(0); db.close(); return lst.getValue(); } public String getMainColorBackground() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + MainColorBackground + "'").get(0); db.close(); return lst.getValue(); } public String getActionBarTitle() { SqlSourceApp db = new SqlSourceApp(GetSetting.context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + ActionBarTitle + "'").get(0); db.close(); return lst.getValue(); } public String getActionBarColorBackground() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + ActionBarColorBackground + "'").get(0); db.close(); return lst.getValue(); } public String getActionBarTextColor() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + ActionBarTextColor + "'").get(0); db.close(); return lst.getValue(); } public String getHeaderBackground() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + HeaderBackground + "'").get(0); db.close(); return lst.getValue(); } public String getHeaderTextColor() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + HeaderTextColor + "'").get(0); db.close(); return lst.getValue(); } public String getSummryBackground() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + SummryBackground + "'").get(0); db.close(); return lst.getValue(); } public String getSummryTextColor() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + SummryTextColor + "'").get(0); db.close(); return lst.getValue(); } public String getFooterTextColor() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + FooterTextColor + "'").get(0); db.close(); return lst.getValue(); } public boolean getIsSetComment() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + isSetComment + "'").get(0); db.close(); if(lst.getValue().equals(YES)) return true; return false; } public boolean getIsShowComment() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + isShowComment + "'").get(0); db.close(); if (lst.getValue().equals(YES)) return true; return false; } public boolean getCollectionData() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + CollectionData + "'").get(0); db.close(); if(lst.getValue().equals(YES)) return true; return false; } public String getTypeShowDate() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + TypeShowDate + "'").get(0); db.close(); return lst.getValue(); } public String getLastVersion() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + LastVersion + "'").get(0); db.close(); return lst.getValue(); } public String getSplashTime() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + SplashTime + "'").get(0); db.close(); return lst.getValue(); } public String getRightMenuTitle() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + RightMenuTitle + "'").get(0); db.close(); return lst.getValue(); } public String getRightMenuIcon() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + RightMenuIcon + "'").get(0); db.close(); return lst.getValue(); } public int getLeftMenuSubject() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + LeftMenuSubject + "'").get(0); db.close(); return Integer.parseInt(lst.getValue()); } public String getLeftMenuTitle() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + LeftMenuTitle + "'").get(0); db.close(); return lst.getValue(); } public String getLeftMenuIcon() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + LeftMenuIcon + "'").get(0); db.close(); return lst.getValue(); } public String getTypeShowList() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + TypeShowList + "'").get(0); db.close(); return lst.getValue(); } public String getIconSearchLocation() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + IconSearchLocation + "'").get(0); db.close(); return lst.getValue(); } public String getIconSearch() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + IconSearch + "'").get(0); db.close(); return lst.getValue(); } public String getIconSearchColor() { SqlSourceApp db = new SqlSourceApp(context); db.open(); lst = db.getSetting(SqlBaseApp.TBL_NAME_H_SETTINGS, SqlBaseApp.TBL_column_name + " = " + "'" + IconSearchColor + "'").get(0); db.close(); return lst.getValue(); } public Typeface getFontApp() { return Typeface.createFromAsset(context.getAssets(), "font/koodak.ttf"); } public String date(String date) { switch (Integer.parseInt(getTypeShowDate())) { case 1: { return ObjPost.getShortDate(date); } case 2: { return ObjPost.getDate_Gregorain(date); } case 3: { return ObjPost.getDate_BeforeTime(date, context); } } return ""; } } <file_sep>package ir.droidhub.mobilebazz.api.web; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class SqlSource { //Variables SQLiteDatabase db; Context mycontext; public SqlSource(Context context) { mycontext=context; } public void open(){ db=new SqlBase(mycontext).getWritableDatabase(); } public void close(){ db.close(); } public CData getCData(String url){ CData cd=null; Cursor crs=db.query(SqlBase.TABLE_CDATA, CData.COL, SqlBase.CD_URL+" like '"+url+"'", null, null, "", ""); crs.moveToFirst(); if (!crs.isAfterLast()) cd=new CData(crs.getInt(0), crs.getString(1), crs.getString(2)); return cd; } public void cData(CData cdata){ db.insert(SqlBase.TABLE_CDATA, null, cdata.getCV()); } } <file_sep>package ir.droidhub.mobilebazz.adpter; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import ir.droidhub.mobilebazz.R; import ir.droidhub.mobilebazz.api.GetSetting; import ir.droidhub.mobilebazz.api.view.TouchImageView; import com.squareup.picasso.Picasso; /** * Created by Ali on 4/3/2016. */ @SuppressLint("ValidFragment") public class FragmentPagerZoomer extends Fragment { private static final String ARG_SECTION_NUMBER = "section-icon"; private Context context; public FragmentPagerZoomer(Context context) { this.context = context; } public FragmentPagerZoomer newInstance(String icon) { FragmentPagerZoomer fragment = new FragmentPagerZoomer(context); Bundle args = new Bundle(); args.putString(ARG_SECTION_NUMBER, icon); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main_zoom, container, false); TouchImageView image = (TouchImageView) rootView.findViewById(R.id.iv_icon_zoom); GetSetting getSetting = new GetSetting(context); image.setBackgroundColor(Color.parseColor(getSetting.getMainColorBackground())); Picasso.with(rootView.getContext()).load(getArguments().getString(ARG_SECTION_NUMBER)).into(image); return rootView; } } <file_sep>package ir.droidhub.mobilebazz.adpter; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import ir.droidhub.mobilebazz.api.GetFont; import ir.droidhub.mobilebazz.api.HTMLBuilder; import ir.droidhub.mobilebazz.R; import ir.droidhub.mobilebazz.api.GetSetting; import ir.droidhub.mobilebazz.api.cash_pic.ImageLoader; import ir.droidhub.mobilebazz.cntdb.ObjPost; import ir.droidhub.mobilebazz.cntdb.SqlSourceCnt; import java.util.List; class AdpBlog extends RecyclerView.Adapter<AdpBlog.viewholder> { private List<ObjPost> lst; static Context context; private static Typeface FontApp; private static GetSetting getSetting; private ImageLoader imageLoader; public AdpBlog(Context context, List<ObjPost> lst){ this.lst = lst; AdpBlog.context = context; getSetting = new GetSetting(context); FontApp = new GetFont(context).yekan; imageLoader=new ImageLoader(context); Typeface iconfont = Typeface.createFromAsset(context.getAssets(), "font/fontawesome-webfont.ttf"); } static class viewholder extends RecyclerView.ViewHolder { TextView PostTitle, PostDate, PostContent, PostCategory; ImageView img_content; LinearLayout background; viewholder(View itemView) { super(itemView); PostDate = (TextView) itemView.findViewById(R.id.list_post_four_date); PostTitle = (TextView) itemView.findViewById(R.id.list_post_four_title); PostCategory = (TextView) itemView.findViewById(R.id.list_post_four_cat); img_content = (ImageView) itemView.findViewById(R.id.list_post_four_img); PostContent = (TextView) itemView.findViewById(R.id.list_post_four_content); background = (LinearLayout) itemView.findViewById(R.id.list_post_four_background); // Color Background background.setBackgroundColor(Color.parseColor(getSetting.getSummryBackground())); // Color Title PostTitle.setTextColor(Color.parseColor(getSetting.getSummryTextColor())); // Color Text Summry PostContent.setTextColor(Color.parseColor(getSetting.getFooterTextColor())); // Color Text Header PostCategory.setTextColor(Color.parseColor(getSetting.getHeaderTextColor())); PostDate.setTextColor(Color.parseColor(getSetting.getHeaderTextColor())); PostTitle.setTypeface(FontApp); PostDate.setTypeface(FontApp); PostCategory.setTypeface(FontApp); PostContent.setTypeface(FontApp); } } @Override public viewholder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.list_blog, parent, false); return new viewholder(v); } @Override public void onBindViewHolder(viewholder view, int position) { view.PostDate.setText(getSetting.date(lst.get(position).getPost_date())); String txt_html = HTMLBuilder.getTextForList(lst.get(position)); if (txt_html.equals("")) { view.PostContent.setVisibility(View.GONE); } else { view.PostContent.setVisibility(View.VISIBLE); view.PostContent.setText(txt_html); } String indexImg = HTMLBuilder.getIndexImage(lst.get(position)); if (indexImg.equals("")) { view.img_content.setVisibility(View.GONE); } else { view.img_content.setVisibility(View.VISIBLE); imageLoader.DisplayImage(indexImg,view.img_content); } view.PostTitle.setText(lst.get(position).getPost_title()); view.PostCategory.setText(getCategory( lst.get(position).getPost_id(), context, view.PostCategory)); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } @Override public int getItemCount() { return lst.size(); } private String getCategory(int PostId, Context ctx, TextView PostCat) { List<String> mycat; String category = ""; SqlSourceCnt db = new SqlSourceCnt(ctx); db.open(); mycat = db.GetCatName(PostId); db.close(); if (mycat.size() == 0) PostCat.setVisibility(View.INVISIBLE); else for (int i = 0; i < mycat.size(); i++) { category += mycat.get(i); if (i < mycat.size() - 1) category += ","; } return category; } } <file_sep>package ir.droidhub.mobilebazz.sql; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; public class SQLbase { public static String DB_PATH; public static String DB_NAME = "cpu"; //Table public static final String TBL_SOC = "soc"; public static final String TBL_Mobile = "phones"; // Content public static final String TBL_id = "_id"; public static final String TBL_name = "name"; public static final String TBL_nameModel = "name_model"; public static final String TBL_dateRelease = "date_release"; public static final String TBL_cpuCore = "cpu_core"; public static final String TBL_architecture = "architecture"; public static final String TBL_versionArchitecture = "version_architecture"; public static final String TBL_sizeArchitecture= "size_architecture"; public static final String TBL_frequence = "frequence"; public static final String TBL_cacheMemory = "cache_memory"; public static final String TBL_typeRam = "type_ram"; public static final String TBL_freqRam = "freq_ram"; public static final String TBL_graphic = "graphic"; public static final String TBL_numberCoreGraphic = "number_core_graphic"; public static final String TBL_FreqGraphic = "freq_graphic"; public static final String TBL_powerProcessingGraphic = "power_processing_graphic"; public static final String TBL_fav = "fav"; public static final String TBL_company = "company"; // Content mobile public static final String TBL_MOBILE_id = "_id"; public static final String TBL_MOBILE_title = "title"; public static final String TBL_MOBILE_category = "category"; public static final String TBL_MOBILE_image = "image"; public static final String TBL_MOBILE_2gnetwork = "twognetwork"; public static final String TBL_MOBILE_3gnetwork = "threegnetwork"; public static final String TBL_MOBILE_4gnetwork = "fourgnetwork"; public static final String TBL_MOBILE_sim= "sim"; public static final String TBL_MOBILE_announced = "announced"; public static final String TBL_MOBILE_status = "status"; public static final String TBL_MOBILE_dimensions = "dimensions"; public static final String TBL_MOBILE_weight = "weight"; public static final String TBL_MOBILE_type = "type"; public static final String TBL_MOBILE_size = "size"; public static final String TBL_MOBILE_multitouch = "multitouch"; public static final String TBL_MOBILE_protection = "protection"; public static final String TBL_MOBILE_alerttypes = "alerttypes"; public static final String TBL_MOBILE_loudspeaker = "loudspeaker"; public static final String TBL_MOBILE_jak = "jack"; public static final String TBL_MOBILE_cardslot = "cardslot"; public static final String TBL_MOBILE_phonebook = "phonebook"; public static final String TBL_MOBILE_callrecords = "callrecords"; public static final String TBL_MOBILE_internal = "internal"; public static final String TBL_MOBILE_gprs = "gprs"; public static final String TBL_MOBILE_edge = "edge"; public static final String TBL_MOBILE_speed = "speed"; public static final String TBL_MOBILE_wlan = "wlan"; public static final String TBL_MOBILE_bluetooth = "bluetooth"; public static final String TBL_MOBILE_nfc = "nfc"; public static final String TBL_MOBILE_infraredport = "infraredport"; public static final String TBL_MOBILE_usb = "usb"; public static final String TBL_MOBILE_primary = "_primary"; public static final String TBL_MOBILE_features = "features"; public static final String TBL_MOBILE_video = "video"; public static final String TBL_MOBILE_secondary = "secondary"; public static final String TBL_MOBILE_os = "os"; public static final String TBL_MOBILE_chipset = "chipset"; public static final String TBL_MOBILE_cpu = "cpu"; public static final String TBL_MOBILE_gpu = "gpu"; public static final String TBL_MOBILE_sensors = "sensors"; public static final String TBL_MOBILE_messaging = "messaging"; public static final String TBL_MOBILE_browser = "browser"; public static final String TBL_MOBILE_radio = "radio"; public static final String TBL_MOBILE_games = "games"; public static final String TBL_MOBILE_clock = "clock"; public static final String TBL_MOBILE_alarm = "alarm"; public static final String TBL_MOBILE_gps = "gps"; public static final String TBL_MOBILE_java = "java"; public static final String TBL_MOBILE_colors = "colors"; public static final String TBL_MOBILE_battrey = "battery"; public static final String TBL_MOBILE_standby = "standby"; public static final String TBL_MOBILE_talktime = "talktime"; public static final String TBL_MOBILE_bodyfeatures = "bodyfeatures"; public static final String TBL_MOBILE_otherfeatures = "otherfeatures"; public static final String TBL_MOBILE_price = "price"; public static final String TBL_MOBILE_cache_image = "cache_image"; Context myContext; public SQLbase(Context context) { myContext = context; } public void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist } else { // By calling this method and empty database will be created into // the default system path // of your application so we are gonna be able to overwrite that // database with our database. try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } // //////////////////////////////////////////////////////////////////////////////////////////////// public boolean checkDataBase() { SQLiteDatabase checkDB = null; try { DB_PATH = "/data/data/" + myContext.getApplicationContext().getPackageName() + "/"; Log.i("Place", "Path:" + DB_PATH); String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE); } catch (SQLiteException e) { // database does't exist yet. } if (checkDB != null) { checkDB.close(); } return checkDB != null ? true : false; } // //////////////////////////////////////////////////////////////////////////////////////////////// private void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = myContext.getAssets().open(DB_NAME); // Path to the just created empty db String outFileName = DB_PATH + DB_NAME; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); Log.i("Place", "Copy Succ!!!"); } } <file_sep>include ':app', 'circualreveal-release', 'fab', ':permission' <file_sep>package ir.droidhub.mobilebazz; import android.content.Context; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.graphics.Palette; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; //import ir.droidhub.fab.TextDrawer; import ir.droidhub.mobilebazz.adpter.AdpShow; import ir.droidhub.mobilebazz.api.GetFont; import ir.droidhub.mobilebazz.sql.SQLbase; import ir.droidhub.mobilebazz.sql.SQLsource; import ir.droidhub.mobilebazz.sql.obj.MyObj; import ir.droidhub.mobilebazz.sql.obj.ObjMobile; import ir.droidhub.mobilebazz.sql.obj.ObjSoc; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import static ir.droidhub.mobilebazz.ActMain.BASELINK_COMPANY; import static ir.droidhub.mobilebazz.ActMain.BASELINK_PHONES; /** * Created by <NAME> on 4/29/2016. */ public class ActShow extends AppCompatActivity { private static final String TAG = "MOBILEBAZZ"; private String[] cpu_company = {"allwinner_icon", "exynos_icon", "hisilicon_icon", "intel_icon", "mediatek_icon", "nvidia_icon", "qualcomm_icon", "rockchip_icon"}; private CollapsingToolbarLayout collapsingLayout; private ObjMobile mobile; private ObjSoc cpu; private Context context; private ImageView image; List<MyObj> myobj = new ArrayList<>(); private RecyclerView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.act_product); context = ActShow.this; findview(); String name = getIntent().getExtras().getString("name"); SQLsource db = new SQLsource(context); db.open(); if (db.GetMob(SQLbase.TBL_Mobile, SQLbase.TBL_MOBILE_title + "='" + name + "'").size() > 0) mobile = db.GetMob(SQLbase.TBL_Mobile, SQLbase.TBL_MOBILE_title + "='" + name + "'").get(0); else if (db.GetSoc(SQLbase.TBL_SOC, SQLbase.TBL_nameModel + "='" + name + "'").size() > 0) cpu = db.GetSoc(SQLbase.TBL_SOC, SQLbase.TBL_nameModel + "='" + name + "'").get(0); db.close(); if (mobile != null) { collapsingLayout.setTitle(mobile.GetTitle()); Picasso.with(this).load( BASELINK_PHONES +String.valueOf(mobile.GetImage()) ).into(image, new Callback() { @Override public void onSuccess() { Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap(); Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() { public void onGenerated(Palette palette) { } }); } @Override public void onError() { } }); String [] title_mobile = {"نام","تاریخ عرضه ","وزن","ابعاد","اندازه صفحه نمایش", "نوع صفحه نمایش","محافظ صفحه نمایش","حافظه داخلی و رم","حافظه جانبی","وای فای","2G","3G","4G","بلوتوث","NFC" ,"USB","دوربین پشت","امکانات دوربین","ضبط ویدئو","دوربین جلو","سیستم عامل", "چیپ ست","پردازنده","گرافیک","سنسورها","GPS","باطری","حداکثر زمان اماده به کار", "حداکثر زمان مکالمه"}; String[] items_mobile = {mobile.GetTitle(),mobile.GetAnnounced(),mobile.GetWeight(),mobile.GetDimensions(), mobile.GetSize(), mobile.GetType(),mobile.GetProtection(),mobile.GetInternal(),mobile.GetCardslot(),mobile.GetWlan(), mobile.GetTwognetwork(),mobile.GetThreegnetwork(),mobile.GetFourgnetwork(),mobile.GetBluetooth(), mobile.GetNfc(),mobile.GetUsb(),mobile.GetPrimary(),mobile.GetVideo(),mobile.GetFeatures(), mobile.GetSecondary(),mobile.GetOs(),mobile.GetCpu(),mobile.GetGpu(),mobile.GetSensors(),mobile.GetGps(), mobile.GetBattrey(),mobile.GetStandby(),mobile.GetCallrecords()}; for(int i=0;i<items_mobile.length;i++) myobj.add(new MyObj(items_mobile[i],title_mobile[i])); } else if (cpu != null) { collapsingLayout.setTitle(cpu.GetName()); Picasso.with(this).load( BASELINK_COMPANY + String.valueOf(cpu_company[cpu.GetCompany()]) + ".png" ).into(image, new Callback() { @Override public void onSuccess() { Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap(); Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() { public void onGenerated(Palette palette) { } }); } @Override public void onError() { } }); String[] items_cpu={cpu.GetName(),cpu.GetNameModel(), cpu.GetDateRelease(),cpu.GetCpuCore(),cpu.GetArchitecture(), cpu.GetVersionArchitecture(),cpu.GetSizeArchitecture(), cpu.GetFrequence(),cpu.GetCacheMemory(),cpu.GetTypeRam(), cpu.GetFreqRam(),cpu.GetGraphic(),cpu.GetNumberCoreGraphic(), cpu.GetFreqGraphic(),cpu.GetPowerProcessingGraphic()+" GigaFlaps"}; String[] title_cpu ={ "نام", "نام مدل", "تاریخ عرضه", "تعداد هسته های cpu", "نوع معماری", "ورژن معماری", "سایز معماری", "فرکانس", "کش حافظه", "نوع رم", "فرکانس رم", "گرافیک", "تعداد هسته های گرافیکی", "فرکانس گرافیک", "توان پردازشی گرافیک"}; for(int i=0;i<items_cpu.length;i++) myobj.add(new MyObj(items_cpu[i],title_cpu[i])); } AdpShow adpShow = new AdpShow(context , myobj); list.setAdapter(adpShow); } private void findview() { GetFont getFont = new GetFont(context); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_product); setSupportActionBar(toolbar); // TextDrawer textDrawer = new TextDrawer(context); // textDrawer.setTypeface(getFont.material); // textDrawer.setTextColor(getResources().getColor(R.color.white)); // textDrawer.setText(getResources().getString(R.string.material_back)); // textDrawer.setTextSize(25); // // toolbar.setNavigationIcon(textDrawer); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); collapsingLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_product); collapsingLayout.setBackgroundColor(getResources().getColor(R.color.white)); collapsingLayout.setExpandedTitleColor(getResources().getColor(R.color.transparent)); collapsingLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.white)); image = (ImageView) findViewById(R.id.image_product); list = (RecyclerView) findViewById(R.id.recyclerview_product); list.setHasFixedSize(true); LinearLayoutManager lm=new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false); list.setLayoutManager(lm); } @Override public boolean dispatchTouchEvent(MotionEvent motionEvent) { try { return super.dispatchTouchEvent(motionEvent); } catch (NullPointerException e) { return false; } } } <file_sep>package ir.droidhub.mobilebazz.adpter; import android.content.Context; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import ir.droidhub.mobilebazz.R; import ir.droidhub.mobilebazz.api.GetFont; import ir.droidhub.mobilebazz.api.cash_pic.ImageLoader; import ir.droidhub.mobilebazz.sql.obj.MyObj; import java.util.List; public class AdpCat extends RecyclerView.Adapter<AdpCat.viewholder> { private List<MyObj> lst; static Context context; private static Typeface FontApp; private ImageLoader imageLoader; public AdpCat(Context context, List<MyObj> lst){ this.lst = lst; AdpCat.context = context; imageLoader=new ImageLoader(context); GetFont f = new GetFont(context); } static class viewholder extends RecyclerView.ViewHolder { // TextView PostTitle; ImageView img; viewholder(View itemView) { super(itemView); // PostTitle = (TextView) itemView.findViewById(R.id.list_cat_title); img = (ImageView) itemView.findViewById(R.id.list_cat_img); // Color Header Text // PostTitle.setTypeface(FontApp); } } @Override public viewholder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.list_cat, parent, false); return new viewholder(v); } @Override public void onBindViewHolder(viewholder view, int position) { imageLoader.DisplayImageNoAnim(lst.get(position).getLst(), view.img); // view.PostTitle.setText(lst.get(position).getTitle()); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } @Override public int getItemCount() { return lst.size(); } } <file_sep>package ir.droidhub.mobilebazz.api; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ScrollView; /** * Created by Ali on 4/30/2016. */ public abstract class HidingScrollListener implements ScrollView.OnScrollChangeListener { private static final int HIDE_THRESHOLD = 20; private int scrolledDistance = 0; private boolean controlsVisible = true; @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) { onHide(); controlsVisible = false; scrolledDistance = 0; } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) { onShow(); controlsVisible = true; scrolledDistance = 0; } if((controlsVisible && scrollY>0) || (!controlsVisible && scrollY<0)) { scrolledDistance += scrollY; } } //// @Override // public void onScrolled(RecyclerView recyclerView, int dx, int dy) { // super.onScrollChange(recyclerView, dx, dy); // // if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) { // onHide(); // controlsVisible = false; // scrolledDistance = 0; // } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) { // onShow(); // controlsVisible = true; // scrolledDistance = 0; // } // // if((controlsVisible && dy>0) || (!controlsVisible && dy<0)) { // scrolledDistance += dy; // } // } public abstract void onHide(); public abstract void onShow(); }<file_sep>package ir.droidhub.mobilebazz.appdb; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class SqlSourceApp { SqlBaseApp base; SQLiteDatabase db; Context mycontext; public SqlSourceApp(Context context) { base = new SqlBaseApp(context); mycontext = context; } public void open() { try { base.createDataBase(); } catch (IOException e) { e.printStackTrace(); } db = SQLiteDatabase.openDatabase(SqlBaseApp.DB_PATH + SqlBaseApp.DB_NAME,null, SQLiteDatabase.OPEN_READWRITE); } public void close() { db.close(); } public List<ObjSetting> getSetting(String tbl_name, String where) { String[] col_ind = {SqlBaseApp.TBL_column_name , SqlBaseApp.TBL_column_value , SqlBaseApp.TBL_column_time}; List<ObjSetting> lst = new ArrayList<ObjSetting>(); Cursor cursor = db.query(tbl_name, col_ind , where , null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { lst.add(new ObjSetting( cursor.getString(0), cursor.getString(1) , cursor.getInt(2))); cursor.moveToNext(); } if (!cursor.isClosed()) cursor.close(); return lst; } public void UpdateAppSettings(List<ObjSetting> lst){ db.delete(SqlBaseApp.TBL_NAME_H_SETTINGS, "", null); ContentValues cv = new ContentValues(); for(int i=0 ; i<lst.size() ; i++) { cv.put(SqlBaseApp.TBL_column_name, lst.get(i).getName()); cv.put(SqlBaseApp.TBL_column_value, lst.get(i).getValue()); cv.put(SqlBaseApp.TBL_column_time, lst.get(i).getTime()); db.insert(SqlBaseApp.TBL_NAME_H_SETTINGS, null, cv); } } } <file_sep>package ir.droidhub.mobilebazz.adpter; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import ir.droidhub.mobilebazz.api.LinkMaker; import ir.droidhub.mobilebazz.api.Net; import ir.droidhub.mobilebazz.api.Parse; import ir.droidhub.mobilebazz.R; import ir.droidhub.mobilebazz.api.GetSetting; import ir.droidhub.mobilebazz.api.web.AsyncDataNet; import ir.droidhub.mobilebazz.cntdb.ObjComment; import ir.droidhub.mobilebazz.cntdb.SqlBaseCnt; import ir.droidhub.mobilebazz.cntdb.SqlSourceCnt; import java.util.ArrayList; import java.util.List; public class AdpComment extends ArrayAdapter<ObjComment> { Context context; private List<ObjComment> lst; private LayoutInflater inflater; ViewHolder view; private Typeface FontApp, Iconfont; private GetSetting getSetting; public AdpComment(Context context, int resource, List<ObjComment> lst) { super(context, resource, lst); this.context = context; getSetting = new GetSetting(context); this.lst = lst; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); FontApp = getSetting.getFontApp(); Iconfont = Typeface.createFromAsset(context.getAssets(), "font/fontawesome-webfont.ttf"); } @NonNull @Override public View getView(final int position, View convertView, @NonNull ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.list_comment, null); view = new ViewHolder(); view.author = (TextView) convertView.findViewById(R.id.textView_comment_author); view.date = (TextView) convertView.findViewById(R.id.textView_comment_date); view.content = (TextView) convertView.findViewById(R.id.textView_CommentContent); view.replayContent = (TextView) convertView.findViewById(R.id.textView_ReplayCommentContent); view.replayIcon = (TextView) convertView.findViewById(R.id.textView_replayIcon); view.author.setTypeface(FontApp); view.date.setTypeface(FontApp); view.content.setTypeface(FontApp); view.replayContent.setTypeface(FontApp); view.replayIcon.setTypeface(Iconfont); view.replayIcon.setText(context.getResources().getString(R.string.fa_reply)); view.replayContent.setTextColor(Color.parseColor(getSetting.getActionBarColorBackground())); view.content.setTextColor(Color.parseColor(getSetting.getSummryTextColor())); if (getSetting.getIsSetComment()) { view.replayIcon.setVisibility(View.VISIBLE); } else { view.replayIcon.setVisibility(View.INVISIBLE); } convertView.setTag(view); } else view = (ViewHolder) convertView.getTag(); view.author.setText(lst.get(position).getComment_author()); view.date.setText(getSetting.date(lst.get(position).getComment_date())); view.content.setText(lst.get(position).getComment_content()); int myparent; if (lst.get(position).getComment_parent() == 0) { view.replayContent.setVisibility(View.GONE); view.content.setText(lst.get(position).getComment_content()); myparent = 0; } else { myparent = lst.get(position).getComment_parent(); SqlSourceCnt db = new SqlSourceCnt(context); db.open(); List<ObjComment> question = new ArrayList<>(); question.addAll(db.GetComment(SqlBaseCnt.TBL_H_COMMENT_POST_ID + "='" + myparent + "'")); db.close(); if (question.size() > 0) { String contentReplay = getWords(question.get(0).getComment_content()); lst.get(position).replay = context.getResources().getString(R.string.ansTo) + " : " + question.get(0).getComment_author() + "\n" + contentReplay; view.replayContent.setVisibility(View.VISIBLE); view.replayContent.setText(lst.get(position).replay); } else { lst.get(position).replay = context.getResources().getString(R.string.textRemoved) + "\n"; view.replayContent.setVisibility(View.VISIBLE); view.replayContent.setText(lst.get(position).replay); } } view.replayIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (Net.Is(context)) NewRepalyComment(lst.get(position).getComment_post_id(), position); } }); return convertView; } private static class ViewHolder { TextView author, date, content, replayContent, replayIcon; } private String getWords(String Statement) { String str = ""; String spt = " "; String[] split = Statement.split(spt); for (int i = 0; i < split.length; i++) { str += split[i] + " "; if (i == 5) return str + "..."; } return str; } private void NewRepalyComment(final int postID, final int parent) { final int CommentParent = lst.get(parent).getComment_id(); final Dialog sendComment = new Dialog(context); sendComment.requestWindowFeature(Window.FEATURE_NO_TITLE); //before sendComment.setContentView(R.layout.dlg_comment); sendComment.setCancelable(false); final Button send = (Button) sendComment.findViewById(R.id.button_comment_send); final Button cancel = (Button) sendComment.findViewById(R.id.button_comment_cancel); final EditText name = (EditText) sendComment.findViewById(R.id.editText_comment_dialog_name); TextInputLayout lName = (TextInputLayout) sendComment.findViewById(R.id.input_layout_name); final EditText email = (EditText) sendComment.findViewById(R.id.editText_comment_dialog_email); TextInputLayout lImail = (TextInputLayout) sendComment.findViewById(R.id.input_layout_email); final EditText message = (EditText) sendComment.findViewById(R.id.editText_comment_dialog_commentContent); TextInputLayout lMessage = (TextInputLayout) sendComment.findViewById(R.id.input_layout_textLongMessage); final TextView title = (TextView) sendComment.findViewById(R.id.textView_dlg_title); title.setText(context.getResources().getString(R.string.ansTo) + " : " + lst.get(parent).getComment_author()); title.setTypeface(FontApp); sendComment.setTitle(": " + title); lName.setTypeface(FontApp); lImail.setTypeface(FontApp); lMessage.setTypeface(FontApp); send.setTypeface(FontApp); cancel.setTypeface(FontApp); name.setTypeface(FontApp); email.setTypeface(FontApp); message.setTypeface(FontApp); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendComment.dismiss(); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String mName, mEmail, mMessage; mName = name.getText().toString(); mEmail = email.getText().toString(); mMessage = message.getText().toString(); if (mName.length() < 3) Toast.makeText(context, context.getResources().getString(R.string.incorrectName), Toast.LENGTH_SHORT).show(); else if (!checkEmail(mEmail)) Toast.makeText(context, context.getResources().getString(R.string.incorrectEmail), Toast.LENGTH_SHORT).show(); else if (mMessage.length() < 3) Toast.makeText(context, context.getResources().getString(R.string.incorrectText), Toast.LENGTH_SHORT).show(); String url = LinkMaker.sendCommentLINK(postID, mName, mEmail, "url", mMessage, CommentParent, 0, "", ""); AsyncDataNet AsyncSendComment = new AsyncDataNet(context, url); AsyncSendComment.setonDone(new AsyncDataNet.onComplete() { @Override public void onDone(String result, int token) { int mResult = 0; try { mResult = Parse.SendComment(result); } catch (Exception e) { } if (mResult == 1) Toast.makeText(context, context.getResources().getString(R.string.sendSuccessfully), Toast.LENGTH_SHORT).show(); else Toast.makeText(context, context.getResources().getString(R.string.sendError), Toast.LENGTH_SHORT).show(); } @Override public void onError(Exception e, int token) { Toast.makeText(context, context.getResources().getString(R.string.ErrorConnection), Toast.LENGTH_SHORT).show(); } }); AsyncSendComment.execute(); sendComment.dismiss(); } }); sendComment.show(); } private boolean checkEmail(String email) { // Email Verification int length = email.length(); Log.i("0", "length" + length); if (length < 4) return false; else for (int i = 0; i < length; i++) { if (String.valueOf(email.charAt(i)).equals("@")) { Log.i("0", "char" + i + " = " + email.charAt(i)); return true; } } return false; } } <file_sep>package ir.droidhub.mobilebazz.cntdb; public class ObjPostCat { public int post_id; public int term_taxonomy_id; public ObjPostCat(int post_id, int term_taxonomy_id){ this.post_id = post_id; this.term_taxonomy_id = term_taxonomy_id; } public int getPost_id(){return this.post_id;} public int getTerm_taxonomy_id(){return this.term_taxonomy_id;} }
4ec85701d7e811f4526807c157ca6fa81030d20c
[ "Java", "Gradle" ]
23
Java
rezaiyan/mobilebazz_frontEnd
ea37aa06ebad69ac8008b4d4f81f3288c85f1429
234b95d54de79476e8991c1d22ed9282242add02
refs/heads/master
<file_sep>import torch as K import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import copy from olbr.agents.basic import BackwardDyn import pdb def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) def hard_update(target, source): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) class PPO_BD(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, eps=None, max_grad_norm=None, use_clipped_value_loss=True, out_func=K.sigmoid, discrete=True, agent_id=0, object_Qfunc=None, backward_dyn=None, object_policy=None, reward_fun=None, masked_with_r=False, dtype=K.float32, device="cuda", ): super(PPO_BD, self).__init__() self.observation_space = observation_space self.action_space = action_space optimizer, lr = optimizer actor_lr, _ = lr self.clip_param = clip_param self.ppo_epoch = ppo_epoch self.num_mini_batch = num_mini_batch self.value_loss_coef = value_loss_coef self.entropy_coef = entropy_coef self.max_grad_norm = max_grad_norm self.use_clipped_value_loss = use_clipped_value_loss self.discrete = discrete self.agent_id = agent_id self.object_Qfunc = object_Qfunc self.object_policy = object_policy self.dtype = dtype self.device = device self.masked_with_r = masked_with_r self.gamma = 0.98 self.tau = 0.05 self.loss_func = F.mse_loss # model initialization self.entities = [] # actors and critics self.actors = [] self.critics = [] self.optims = [] self.actors.append(Actor(observation_space, action_space[agent_id], discrete, out_func).to(device)) self.critics.append(Critic(observation_space, None).to(device)) self.optims.append(optimizer(self.critics[0].parameters(), lr=actor_lr, eps=eps)) self.optims[0].add_param_group({"params": self.actors[0].parameters()}) self.entities.extend(self.actors) self.entities.extend(self.critics) self.entities.extend(self.optims) # backward dynamics model if backward_dyn is not None: self.backward = backward_dyn self.backward_optim = optimizer(self.backward.parameters(), lr = actor_lr) self.entities.append(self.backward) self.entities.append(self.backward_optim) # Learnt Q function for object if self.object_Qfunc is not None: self.object_Qfunc_target = copy.deepcopy(self.object_Qfunc) self.object_Qfunc_optim = optimizer(self.object_Qfunc.parameters(), lr = actor_lr) self.entities.append(self.object_Qfunc) self.entities.append(self.object_Qfunc_target) self.entities.append(self.object_Qfunc_optim) # Learnt policy for object if self.object_policy is not None: self.object_policy_target = copy.deepcopy(self.object_policy) self.object_policy_optim = optimizer(self.object_policy.parameters(), lr = actor_lr) self.entities.append(self.object_policy) self.entities.append(self.object_policy_target) self.entities.append(self.object_policy_optim) if reward_fun is not None: self.get_obj_reward = reward_fun else: self.get_obj_reward = self.reward_fun print('clipped between -1 and 0, and masked with abs(r), and + r') def to_cpu(self): for entity in self.entities: if type(entity) != type(self.optims[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.optims[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False): with K.no_grad(): value = self.critics[0](state.to(self.device)) action_dist = self.actors[0](state.to(self.device)) if exploration: action = action_dist.sample() else: action = action_dist.mode() #action = action.clamp(int(self.action_space[self.agent_id].low[0]), int(self.action_space[self.agent_id].high[0])) return value, action, action_dist.log_probs(action) def get_obj_action(self, state, exploration=False): self.object_policy.eval() with K.no_grad(): mu = self.object_policy(state.to(self.device)) self.object_policy.train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[1].low[0]), int(self.action_space[1].high[0])) return mu def evaluate_actions(self, state, action, get_preactivations=False): value = self.critics[0](state.to(self.device)) action_dist = self.actors[0](state.to(self.device)) action_log_probs = action_dist.log_probs(action) dist_entropy = action_dist.entropies().mean() if get_preactivations: action_preactivations = self.actors[0].get_preactivations(state.to(self.device)) else: action_preactivations = None return value, action_log_probs, dist_entropy, action_preactivations def reward_fun(self, state, next_state): with K.no_grad(): action = self.backward(state.to(self.device), next_state.to(self.device)) opt_action = self.object_policy(state.to(self.device)) reward = self.object_Qfunc(state.to(self.device), action) - self.object_Qfunc(state.to(self.device), opt_action) return reward.clamp(min=-1.0, max=0.0) def update(self, rollouts): advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1] advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5) value_loss_epoch = 0 action_loss_epoch = 0 dist_entropy_epoch = 0 for e in range(self.ppo_epoch): data_generator = rollouts.feed_forward_generator(advantages, self.num_mini_batch, mini_batch_size=None) for sample in data_generator: obs_batch, actions_batch, value_preds_batch, return_batch, old_action_log_probs_batch, adv_targ = sample # Reshape to do in a single forward pass for all steps values, action_log_probs, dist_entropy, action_preactivations = self.evaluate_actions(obs_batch, actions_batch, False) ratio = K.exp(action_log_probs - old_action_log_probs_batch) surr1 = ratio * adv_targ surr2 = K.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * adv_targ action_loss = -K.min(surr1, surr2).mean() #action_loss += (action_preactivations**2).mean()*0.001 if self.use_clipped_value_loss: value_pred_clipped = value_preds_batch + (values - value_preds_batch).clamp(-self.clip_param, self.clip_param) value_losses = (values - return_batch).pow(2) value_losses_clipped = (value_pred_clipped - return_batch).pow(2) value_loss = 0.5 * K.max(value_losses, value_losses_clipped).mean() else: value_loss = 0.5 * (return_batch - values).pow(2).mean() self.optims[0].zero_grad() (value_loss * self.value_loss_coef + action_loss - dist_entropy * self.entropy_coef).backward() nn.utils.clip_grad_norm_(self.critics[0].parameters(), self.max_grad_norm) nn.utils.clip_grad_norm_(self.actors[0].parameters(), self.max_grad_norm) self.optims[0].step() value_loss_epoch += value_loss.item() action_loss_epoch += action_loss.item() dist_entropy_epoch += dist_entropy.item() num_updates = self.ppo_epoch * self.num_mini_batch value_loss_epoch /= num_updates action_loss_epoch /= num_updates dist_entropy_epoch /= num_updates return value_loss_epoch, action_loss_epoch, dist_entropy_epoch def update_backward(self, batch, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[1] is not None: s2 = normalizer[1].preprocess(s2) s2_ = normalizer[1].preprocess(s2_) a2_pred = self.backward(s2, s2_) loss_backward = self.loss_func(a2_pred, a2) self.backward_optim.zero_grad() loss_backward.backward() self.backward_optim.step() return loss_backward.item() def update_object_parameters(self, batch, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[1] is not None: s2 = normalizer[1].preprocess(s2) s2_ = normalizer[1].preprocess(s2_) s, s_, a = s2, s2_, a2 a_ = self.object_policy_target(s_) r = K.tensor(batch['r'], dtype=self.dtype, device=self.device).unsqueeze(1) Q = self.object_Qfunc(s, a) V = self.object_Qfunc_target(s_, a_).detach() target_Q = (V * self.gamma) + r target_Q = target_Q.clamp(-1./(1.-self.gamma), 0.) loss_critic = self.loss_func(Q, target_Q) self.object_Qfunc_optim.zero_grad() loss_critic.backward() self.object_Qfunc_optim.step() a = self.object_policy(s) loss_actor = -self.object_Qfunc(s, a).mean() loss_actor += (self.object_policy(s)**2).mean()*1 self.object_policy_optim.zero_grad() loss_actor.backward() self.object_policy_optim.step() return loss_critic.item(), loss_actor.item() def update_object_target(self): soft_update(self.object_policy_target, self.object_policy, self.tau) soft_update(self.object_Qfunc_target, self.object_Qfunc, self.tau) <file_sep>import numpy as np import scipy as sc import time import imageio import torch as K import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import gym_wmgds as gym from olbr.algorithms import DDPG from olbr.experience import ReplayMemory, Transition, Normalizer from olbr.exploration import Noise from olbr.utils import Saver, Summarizer, get_noise_scale, get_params, running_mean from olbr.agents.basic import Actor from olbr.agents.basic import Critic import pdb import matplotlib import matplotlib.pyplot as plt device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 def init(config): if config['resume'] != '': resume_path = config['resume'] saver = Saver(config) config, start_episode, save_dict = saver.resume_ckpt() config['resume'] = resume_path else: start_episode = 0 #hyperparameters ENV_NAME = config['env_id'] #'simple_spread' SEED = config['random_seed'] # 1 GAMMA = config['gamma'] # 0.95 TAU = config['tau'] # 0.01 ACTOR_LR = config['plcy_lr'] # 0.01 CRITIC_LR = config['crtc_lr'] # 0.01 MEM_SIZE = config['buffer_length'] # 1000000 REGULARIZATION = config['regularization'] # True NORMALIZED_REWARDS = config['reward_normalization'] # True env = gym.make(ENV_NAME) env.seed(SEED) observation_space = env.observation_space.spaces['observation'].shape[0] + env.observation_space.spaces['desired_goal'].shape[0] action_space = env.action_space if env.action_space.low[0] == -1 and env.action_space.high[0] == 1: OUT_FUNC = K.tanh elif env.action_space.low[0] == 0 and env.action_space.high[0] == 1: OUT_FUNC = K.sigmoid else: OUT_FUNC = K.sigmoid K.manual_seed(SEED) np.random.seed(SEED) MODEL = DDPG if config['verbose'] > 1: # utils summaries = (Summarizer(config['dir_summary_train'], config['port'], config['resume']), Summarizer(config['dir_summary_test'], config['port'], config['resume'])) saver = Saver(config) else: summaries = None saver = None #exploration initialization noise = Noise(action_space.shape[0], sigma=0.2, eps=0.3) #noise = OUNoise(action_space.shape[0]) #model initialization optimizer = (optim.Adam, (ACTOR_LR, CRITIC_LR)) # optimiser func, (actor_lr, critic_lr) loss_func = F.mse_loss model = MODEL(observation_space, action_space, optimizer, Actor, Critic, loss_func, GAMMA, TAU, out_func=OUT_FUNC, discrete=False, regularization=REGULARIZATION, normalized_rewards=NORMALIZED_REWARDS) if config['resume'] != '': for i, param in enumerate(save_dict['model_params']): model.entities[i].load_state_dict(param) #memory initilization memory = ReplayMemory(MEM_SIZE) normalizer = (Normalizer(), None) experiment_args = (env, memory, noise, config, summaries, saver, start_episode, normalizer) return model, experiment_args def rollout(env, model, noise, normalizer=None, render=False, nb_objects=1): trajectory = [] # monitoring variables episode_reward = 0 frames = [] env.env.nb_objects = nb_objects state = env.reset() achieved_init = state['achieved_goal'] for i_step in range(env._max_episode_steps): model.to_cpu() obs = K.tensor(state['observation'][0], dtype=K.float32).unsqueeze(0) goal = K.tensor(state['desired_goal'], dtype=K.float32).unsqueeze(0) obs_goal = K.cat([obs, goal], dim=-1) # Observation normalization if normalizer[0] is not None: obs_goal = normalizer[0].preprocess_with_update(obs_goal) #_ = normalizer.preprocess_with_update(obs_goal) action = model.select_action(obs_goal, noise) next_state, reward, done, info = env.step(action.squeeze(0).numpy()) reward = K.tensor(reward, dtype=dtype).view(1,1) if normalizer[1] is not None: reward = normalizer[1].preprocess_with_update(reward) # for monitoring episode_reward += reward trajectory.append((state.copy(), action, reward, next_state.copy(), done)) # Move to the next state state = next_state # Record frames if render: frames.append(env.render(mode='rgb_array')[0]) #achieved_final = state['achieved_goal'] #moved_step[np.where(np.logical_and(np.linalg.norm((achieved_init - achieved_final), axis=1) > 1e-4, moved_step==-1))[0]] = i_step achieved_final = state['achieved_goal'] moved_index = np.concatenate((K.zeros(1), np.where((achieved_init[1::] != achieved_final[1::]).all(axis=1))[0]+1)).astype(int) #moved_index = np.where(np.linalg.norm((achieved_init - achieved_final), axis=1) > 1e-4)[0] if render: print(moved_index) return trajectory, episode_reward, info['is_success'], frames, moved_index def run(model, experiment_args, train=True): total_time_start = time.time() env, memory, noise, config, summaries, saver, start_episode, normalizer = experiment_args start_episode = start_episode if train else 0 NUM_EPISODES = config['n_episodes'] if train else config['n_episodes_test'] EPISODE_LENGTH = env._max_episode_steps #config['episode_length'] if train else config['episode_length_test'] episode_reward_all = [] episode_success_all = [] critic_losses = [] actor_losses = [] max_nb_objects = config['max_nb_objects'] for i_episode in range(start_episode, NUM_EPISODES): episode_time_start = time.time() #noise.scale = get_noise_scale(i_episode, config) if train: for i_cycle in range(50): trajectories = [] moved_indices = [] for i_rollout in range(1): # Initialize the environment and state nb_objects = np.random.randint(1, max_nb_objects+1) trajectory, _, _, _, moved_index = rollout(env, model, noise, normalizer, render=(i_cycle%10==1000), nb_objects=nb_objects) trajectories.append(trajectory) moved_indices.append(moved_index) for trajectory, moved_index in zip(trajectories, moved_indices): T = len(trajectory) - 1 t_samples = np.random.randint(T, size=(max_nb_objects,T)) future_offset = np.random.uniform(size=(max_nb_objects,T)) * (T - t_samples) future_offset = future_offset.astype(int) her_sample = (np.random.uniform(size=(max_nb_objects,T)) < 0.8) future_t = (t_samples + 1 + future_offset) # for i_step in range(len(trajectory)): # state, action, reward, next_state, done = trajectory[i_step] # obs = K.tensor(state['observation'][0], dtype=K.float32).unsqueeze(0) # goal = K.tensor(state['desired_goal'], dtype=K.float32).unsqueeze(0) # next_obs = K.tensor(next_state['observation'][0], dtype=K.float32).unsqueeze(0) # next_achieved = K.tensor(next_state['achieved_goal'][0], dtype=K.float32).unsqueeze(0) # # regular sample # obs_goal = K.cat([obs, goal], dim=-1) # if done: # next_obs_goal = None # else: # next_obs_goal = K.cat([next_obs, goal], dim=-1) # memory.push(obs_goal, action, next_obs_goal, reward) # <-- end loop: i_step for i_object in moved_index: for i_step in t_samples[i_object]: state, action, reward, next_state, done = trajectory[i_step] #pdb.set_trace() obs = K.tensor(state['observation'][i_object], dtype=K.float32).unsqueeze(0) goal = K.tensor(state['desired_goal'], dtype=K.float32).unsqueeze(0) next_obs = K.tensor(next_state['observation'][i_object], dtype=K.float32).unsqueeze(0) next_achieved = K.tensor(next_state['achieved_goal'][i_object], dtype=K.float32).unsqueeze(0) if her_sample[i_object, i_step]: _, _, _, next_state, _ = trajectory[future_t[i_object, i_step]] aux_goal = K.tensor(next_state['achieved_goal'][i_object], dtype=K.float32).unsqueeze(0) obs_goal = K.cat([obs, aux_goal], dim=-1) if done: next_obs_goal = None else: next_obs_goal = K.cat([next_obs, aux_goal], dim=-1) reward = env.compute_reward(next_achieved, aux_goal, None) reward = K.tensor(reward, dtype=dtype).view(1,1) if normalizer[1] is not None: reward = normalizer[1].preprocess_with_update(reward) else: # regular sample obs_goal = K.cat([obs, goal], dim=-1) if done: next_obs_goal = None else: next_obs_goal = K.cat([next_obs, goal], dim=-1) memory.push(obs_goal, action, next_obs_goal, reward) # <-- end loop: i_step # <-- end loop: i_object # <-- end loop: i_rollout for i_batch in range(40): if len(memory) > config['batch_size']-1: model.to_cuda() batch = Transition(*zip(*memory.sample(config['batch_size']))) critic_loss, actor_loss = model.update_parameters(batch, normalizer) if i_batch == 39: critic_losses.append(critic_loss) actor_losses.append(actor_loss) #print(normalizer.get_stats()) # <-- end loop: i_cycle plot_durations(np.asarray(critic_losses), np.asarray(actor_losses)) #pdb.set_trace() episode_reward_cycle = [] episode_succeess_cycle = [] for i_rollout in range(10): # Initialize the environment and state render = config['render'] > 0 and i_episode % config['render'] == 0 _, episode_reward, success, frames, _ = rollout(env, model, noise=False, normalizer=normalizer, render=render, nb_objects=1) # Save gif dir_monitor = config['dir_monitor_train'] if train else config['dir_monitor_test'] if config['render'] > 0 and i_episode % config['render'] == 0: imageio.mimsave('{}/{}.gif'.format(dir_monitor, i_episode), frames) episode_reward_cycle.append(episode_reward) episode_succeess_cycle.append(success) # <-- end loop: i_rollout ### MONITORIRNG ### episode_reward_all.append(np.mean(episode_reward_cycle)) episode_success_all.append(np.mean(episode_succeess_cycle)) plot_durations(np.asarray(episode_reward_all), np.asarray(episode_success_all)) if config['verbose'] > 0: # Printing out if (i_episode+1)%1 == 0: print("==> Episode {} of {}".format(i_episode + 1, NUM_EPISODES)) print(' | Id exp: {}'.format(config['exp_id'])) print(' | Exp description: {}'.format(config['exp_descr'])) print(' | Env: {}'.format(config['env_id'])) print(' | Process pid: {}'.format(config['process_pid'])) print(' | Tensorboard port: {}'.format(config['port'])) print(' | Episode total reward: {}'.format(episode_reward)) print(' | Running mean of total reward: {}'.format(episode_reward_all[-1])) print(' | Success rate: {}'.format(episode_success_all[-1])) #print(' | Running mean of total reward: {}'.format(running_mean(episode_reward_all)[-1])) print(' | Time episode: {}'.format(time.time()-episode_time_start)) print(' | Time total: {}'.format(time.time()-total_time_start)) if config['verbose'] > 0: ep_save = i_episode+1 if (i_episode == NUM_EPISODES-1) else None is_best_save = None is_best_avg_save = None if (not train) or ((np.asarray([ep_save, is_best_save, is_best_avg_save]) == None).sum() == 3): to_save = False else: model.to_cpu() saver.save_checkpoint(save_dict = {'model_params': [entity.state_dict() for entity in model.entities]}, episode = ep_save, is_best = is_best_save, is_best_avg = is_best_avg_save ) to_save = True #if (i_episode+1)%100 == 0: # summary = summaries[0] if train else summaries[1] # summary.update_log(i_episode, # episode_reward, # list(episode_reward.reshape(-1,)), # critic_loss = critic_loss, # actor_loss = actor_loss, # to_save = to_save # ) # <-- end loop: i_episode if train: print('Training completed') else: print('Test completed') return episode_reward_all # set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() def plot_durations(p, r): plt.figure(2) plt.clf() plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(p) plt.plot(r) plt.pause(0.001) # pause a bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf()) if __name__ == '__main__': monitor_macddpg_p2 = [] monitor_macddpg_p2_test = [] for i in range(0,5): config = get_params(args=['--exp_id','MACDDPG_P2_120K_'+ str(i+1), '--random_seed', str(i+1), '--agent_alg', 'MACDDPG', '--protocol_type', str(2), '--n_episodes', '120000', '--verbose', '2', ] ) model, experiment_args = init(config) env, memory, ounoise, config, summaries, saver, start_episode = experiment_args tic = time.time() monitor = run(model, experiment_args, train=True) monitor_test = run(model, experiment_args, train=False) toc = time.time() env.close() for summary in summaries: summary.close() monitor_macddpg_p2.append(monitor) monitor_macddpg_p2_test.append(monitor_test) np.save('./monitor_macddpg_p2.npy', monitor_macddpg_p2) np.save('./monitor_macddpg_p2_test.npy', monitor_macddpg_p2_test) print(toc-tic)<file_sep>import torch as K import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from olbr.agents.basic import BackwardDyn import pdb class PPO_BD(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, eps=None, max_grad_norm=None, use_clipped_value_loss=True, out_func=K.sigmoid, discrete=True, object_Qfunc=None, backward_dyn=None, object_policy=None, reward_fun=None, masked_with_r=False, rnd_models=None, pred_th=0.0002, dtype=K.float32, device="cuda", ): super(PPO_BD, self).__init__() self.observation_space = observation_space self.action_space = action_space optimizer, lr = optimizer actor_lr, _ = lr self.clip_param = clip_param self.ppo_epoch = ppo_epoch self.num_mini_batch = num_mini_batch self.value_loss_coef = value_loss_coef self.entropy_coef = entropy_coef self.max_grad_norm = max_grad_norm self.use_clipped_value_loss = use_clipped_value_loss self.discrete = discrete self.object_Qfunc = object_Qfunc self.object_policy = object_policy self.dtype = dtype self.device = device self.masked_with_r = masked_with_r self.pred_th = pred_th # model initialization self.entities = [] # actors and critics self.actors = [] self.critics = [] self.optims = [] self.actors.append(Actor(observation_space, action_space[0], discrete, out_func).to(device)) self.critics.append(Critic(observation_space, None).to(device)) self.optims.append(optimizer(self.critics[0].parameters(), lr=actor_lr, eps=eps)) self.optims[0].add_param_group({"params": self.actors[0].parameters()}) self.entities.extend(self.actors) self.entities.extend(self.critics) self.entities.extend(self.optims) # backward dynamics model if backward_dyn is not None: self.backward = backward_dyn self.backward.eval() self.entities.append(self.backward) # Learnt Q function for object if self.object_Qfunc is not None: self.object_Qfunc.eval() self.entities.append(self.object_Qfunc) # Learnt policy for object if self.object_policy is not None: self.object_policy.eval() self.entities.append(self.object_policy) if reward_fun is not None: self.get_obj_reward = reward_fun else: self.get_obj_reward = self.reward_fun if rnd_models is not None: self.rnd_model = rnd_models[0] self.rnd_target = rnd_models[1] self.entities.append(self.rnd_model) self.entities.append(self.rnd_target) print('rnd_based_coverage') def to_cpu(self): for entity in self.entities: if type(entity) != type(self.optims[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.optims[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False): with K.no_grad(): value = self.critics[0](state.to(self.device)) action_dist = self.actors[0](state.to(self.device)) if exploration: action = action_dist.sample() else: action = action_dist.mode() #action = action.clamp(int(self.action_space[0].low[0]), int(self.action_space[0].high[0])) return value, action, action_dist.log_probs(action) def evaluate_actions(self, state, action, get_preactivations=False): value = self.critics[0](state.to(self.device)) action_dist = self.actors[0](state.to(self.device)) action_log_probs = action_dist.log_probs(action) dist_entropy = action_dist.entropies().mean() if get_preactivations: action_preactivations = self.actors[0].get_preactivations(state.to(self.device)) else: action_preactivations = None return value, action_log_probs, dist_entropy, action_preactivations def reward_fun(self, state, next_state): with K.no_grad(): action = self.backward(state.to(self.device), next_state.to(self.device)) opt_action = self.object_policy(state.to(self.device)) reward = self.object_Qfunc(state.to(self.device), action) - self.object_Qfunc(state.to(self.device), opt_action) return reward.clamp(min=-1.0, max=0.0) def get_pred_error(self, next_state): with K.no_grad(): target = self.rnd_target(next_state) pred = self.rnd_model(next_state) error = F.mse_loss(pred, target, reduction='none').mean(1) return error def update(self, rollouts): advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1] advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5) value_loss_epoch = 0 action_loss_epoch = 0 dist_entropy_epoch = 0 for e in range(self.ppo_epoch): data_generator = rollouts.feed_forward_generator(advantages, self.num_mini_batch, mini_batch_size=None) for sample in data_generator: obs_batch, actions_batch, value_preds_batch, return_batch, old_action_log_probs_batch, adv_targ = sample # Reshape to do in a single forward pass for all steps values, action_log_probs, dist_entropy, action_preactivations = self.evaluate_actions(obs_batch, actions_batch, False) ratio = K.exp(action_log_probs - old_action_log_probs_batch) surr1 = ratio * adv_targ surr2 = K.clamp(ratio, 1.0 - self.clip_param, 1.0 + self.clip_param) * adv_targ action_loss = -K.min(surr1, surr2).mean() #action_loss += (action_preactivations**2).mean()*0.001 if self.use_clipped_value_loss: value_pred_clipped = value_preds_batch + (values - value_preds_batch).clamp(-self.clip_param, self.clip_param) value_losses = (values - return_batch).pow(2) value_losses_clipped = (value_pred_clipped - return_batch).pow(2) value_loss = 0.5 * K.max(value_losses, value_losses_clipped).mean() else: value_loss = 0.5 * (return_batch - values).pow(2).mean() self.optims[0].zero_grad() (value_loss * self.value_loss_coef + action_loss - dist_entropy * self.entropy_coef).backward() nn.utils.clip_grad_norm_(self.critics[0].parameters(), self.max_grad_norm) nn.utils.clip_grad_norm_(self.actors[0].parameters(), self.max_grad_norm) self.optims[0].step() value_loss_epoch += value_loss.item() action_loss_epoch += action_loss.item() dist_entropy_epoch += dist_entropy.item() num_updates = self.ppo_epoch * self.num_mini_batch value_loss_epoch /= num_updates action_loss_epoch /= num_updates dist_entropy_epoch /= num_updates return value_loss_epoch, action_loss_epoch, dist_entropy_epoch<file_sep>import numpy as np import scipy as sc import time import imageio import torch as K import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import gym_wmgds as gym from olbr.algorithms import DDPG, DDPGC from olbr.experience import ReplayMemory, Transition, Normalizer from olbr.exploration import Noise, OUNoise from olbr.utils import Saver, Summarizer, get_noise_scale, get_params, running_mean from olbr.agents.basic import Actor from olbr.agents.basic import CriticReg as Critic import pdb device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 def init(config): if config['resume'] != '': resume_path = config['resume'] saver = Saver(config) config, start_episode, save_dict = saver.resume_ckpt() config['resume'] = resume_path else: start_episode = 0 #hyperparameters ENV_NAME = config['env_id'] #'simple_spread' SEED = config['random_seed'] # 1 GAMMA = config['gamma'] # 0.95 TAU = config['tau'] # 0.01 ACTOR_LR = config['plcy_lr'] # 0.01 CRITIC_LR = config['crtc_lr'] # 0.01 MEM_SIZE = config['buffer_length'] # 1000000 REGULARIZATION = config['regularization'] # True NORMALIZED_REWARDS = config['reward_normalization'] # True env = gym.make(ENV_NAME) env.seed(SEED) observation_space = env.observation_space.shape[0] action_space = env.action_space OUT_FUNC = K.sigmoid K.manual_seed(SEED) np.random.seed(SEED) MODEL = DDPG if config['verbose'] > 1: # utils summaries = (Summarizer(config['dir_summary_train'], config['port'], config['resume']), Summarizer(config['dir_summary_test'], config['port'], config['resume'])) saver = Saver(config) else: summaries = None saver = None #exploration initialization noise = Noise(action_space.shape[0], sigma=0.2, eps=0.3, max_u=env.action_space.high[0]) #noise = OUNoise(action_space.shape[0]) #model initialization optimizer = (optim.Adam, (ACTOR_LR, CRITIC_LR)) # optimiser func, (actor_lr, critic_lr) loss_func = F.mse_loss model = MODEL(observation_space, action_space, optimizer, Actor, Critic, loss_func, GAMMA, TAU, out_func=OUT_FUNC, discrete=False, regularization=REGULARIZATION, normalized_rewards=NORMALIZED_REWARDS) if config['resume'] != '': for i, param in enumerate(save_dict['model_params']): model.entities[i].load_state_dict(param) #memory initilization memory = ReplayMemory(MEM_SIZE) experiment_args = (env, memory, noise, config, summaries, saver, start_episode) return model, experiment_args def rollout(env, model, noise, normalizer=None, render=False): trajectory = [] # monitoring variables episode_reward = 0 frames = [] obs = env.reset() nb_step = 100#env._max_episode_steps for i_step in range(nb_step): model.to_cpu() obs = K.tensor(obs, dtype=K.float32).unsqueeze(0) # Observation normalization if normalizer is not None: obs = normalizer.preprocess_with_update(obs) action = model.select_action(obs, noise) next_obs, reward, done, info = env.step(action.squeeze(0).numpy()) reward = K.tensor(reward, dtype=dtype).view(1,1) # for monitoring episode_reward += reward done = 1 if (i_step == (nb_step - 1)) else 0 trajectory.append((obs, action, reward, K.tensor(next_obs, dtype=K.float32).unsqueeze(0), done)) # Move to the next state obs = next_obs # Record frames if render: frames.append(env.render(mode='rgb_array')[0]) success = 0 if (info.get('is_success') is None) else info.get('is_success') return trajectory, episode_reward, success, frames def run(model, experiment_args, train=True): total_time_start = time.time() env, memory, noise, config, summaries, saver, start_episode = experiment_args #normalizer = Normalizer() start_episode = start_episode if train else 0 NUM_EPISODES = config['n_episodes'] if train else config['n_episodes_test'] EPISODE_LENGTH = 100#env._max_episode_steps #config['episode_length'] if train else config['episode_length_test'] episode_reward_all = [] episode_success_all = [] for i_episode in range(start_episode, NUM_EPISODES): episode_time_start = time.time() #noise.scale = get_noise_scale(i_episode, config) if train: for i_cycle in range(25): trajectories = [] for i_rollout in range(16): # Initialize the environment and state trajectory, _, _, _ = rollout(env, model, noise, render=0) trajectories.append(trajectory) for trajectory in trajectories: for i_step in range(len(trajectory)): obs, action, reward, next_obs, done = trajectory[i_step] if done: next_obs = None memory.push(obs, action, next_obs, reward) for _ in range(40): if len(memory) > config['batch_size']-1: model.to_cuda() batch = Transition(*zip(*memory.sample(config['batch_size']))) critic_loss, actor_loss = model.update_parameters(batch) #print(normalizer.get_stats()) # <-- end loop: i_cycle episode_reward_cycle = [] episode_succeess_cycle = [] for i_rollout in range(10): # Initialize the environment and state render = config['render'] > 0 and i_episode % config['render'] == 0 _, episode_reward, success, frames = rollout(env, model, noise=False, normalizer=None, render=render) # Save gif dir_monitor = config['dir_monitor_train'] if train else config['dir_monitor_test'] if config['render'] > 0 and i_episode % config['render'] == 0: imageio.mimsave('{}/{}.gif'.format(dir_monitor, i_episode), frames) episode_reward_cycle.append(episode_reward) episode_succeess_cycle.append(success) # <-- end loop: i_rollout ### MONITORIRNG ### episode_reward_all.append(np.mean(episode_reward_cycle)) episode_success_all.append(np.mean(episode_succeess_cycle)) if config['verbose'] > 0: # Printing out if (i_episode+1)%1 == 0: print("==> Episode {} of {}".format(i_episode + 1, NUM_EPISODES)) print(' | Id exp: {}'.format(config['exp_id'])) print(' | Exp description: {}'.format(config['exp_descr'])) print(' | Env: {}'.format(config['env_id'])) print(' | Process pid: {}'.format(config['process_pid'])) print(' | Tensorboard port: {}'.format(config['port'])) print(' | Episode total reward: {}'.format(episode_reward)) print(' | Running mean of total reward: {}'.format(episode_reward_all[-1])) print(' | Success rate: {}'.format(episode_success_all[-1])) #print(' | Running mean of total reward: {}'.format(running_mean(episode_reward_all)[-1])) print(' | Time episode: {}'.format(time.time()-episode_time_start)) print(' | Time total: {}'.format(time.time()-total_time_start)) if config['verbose'] > 0: ep_save = i_episode+1 if (i_episode == NUM_EPISODES-1) else None is_best_save = None is_best_avg_save = None if (not train) or ((np.asarray([ep_save, is_best_save, is_best_avg_save]) == None).sum() == 3): to_save = False else: model.to_cpu() saver.save_checkpoint(save_dict = {'model_params': [entity.state_dict() for entity in model.entities]}, episode = ep_save, is_best = is_best_save, is_best_avg = is_best_avg_save ) to_save = True #if (i_episode+1)%100 == 0: # summary = summaries[0] if train else summaries[1] # summary.update_log(i_episode, # episode_reward, # list(episode_reward.reshape(-1,)), # critic_loss = critic_loss, # actor_loss = actor_loss, # to_save = to_save # ) # <-- end loop: i_episode if train: print('Training completed') else: print('Test completed') return episode_reward_all if __name__ == '__main__': monitor_macddpg_p2 = [] monitor_macddpg_p2_test = [] for i in range(0,5): config = get_params(args=['--exp_id','MACDDPG_P2_120K_'+ str(i+1), '--random_seed', str(i+1), '--agent_alg', 'MACDDPG', '--protocol_type', str(2), '--n_episodes', '120000', '--verbose', '2', ] ) model, experiment_args = init(config) env, memory, ounoise, config, summaries, saver, start_episode = experiment_args tic = time.time() monitor = run(model, experiment_args, train=True) monitor_test = run(model, experiment_args, train=False) toc = time.time() env.close() for summary in summaries: summary.close() monitor_macddpg_p2.append(monitor) monitor_macddpg_p2_test.append(monitor_test) np.save('./monitor_macddpg_p2.npy', monitor_macddpg_p2) np.save('./monitor_macddpg_p2_test.npy', monitor_macddpg_p2_test) print(toc-tic)<file_sep>import numpy as np import scipy as sc import time import torch as K from olbr.utils import get_params as get_params, running_mean, get_exp_params from olbr.main_cher import init, run from olbr.main_q_v2 import init as init_q from olbr.main_q_v2 import run as run_q from olbr.main_q_rnd import init as init_q_rnd from olbr.main_q_rnd import run as run_q_rnd import matplotlib.pyplot as plt import os import pickle import sys import olbr K.set_num_threads(1) device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 exp_config = get_exp_params(sys.argv[1:]) filepath = exp_config['filepath'] os.chdir(filepath) suffix = '' if exp_config['env'] == 'PushSide': env_name_list = ['FetchPushObstacleSideGapMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PushMiddle': env_name_list = ['FetchPushObstacleMiddleGapMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PushDouble': env_name_list = ['FetchPushObstacleDoubleGapMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPShelf': env_name_list = ['FetchPickAndPlaceShelfMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPObstacle': env_name_list = ['FetchPickAndPlaceObstacleMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPHardest': env_name_list = ['FetchPickAndPlaceHardestMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPInsertion': env_name_list = ['FetchPickAndPlaceInsertionMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPNormal': env_name_list = ['FetchPickAndPlaceMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'All': env_name_list = ['FetchPushObstacleSideGapMulti{}-v1'.format(suffix), 'FetchPushObstacleMiddleGapMulti{}-v1'.format(suffix), 'FetchPushObstacleDoubleGapMulti{}-v1'.format(suffix), 'FetchPickAndPlaceShelfMulti{}-v1'.format(suffix), 'FetchPickAndPlaceObstacleMulti{}-v1'.format(suffix), 'FetchPickAndPlaceHardestMulti{}-v1'.format(suffix), 'FetchPickAndPlaceInsertionMulti{}-v1'.format(suffix), 'FetchPickAndPlaceMulti{}-v1'.format(suffix) ] for env_name in env_name_list: if exp_config['use_cher'] == 'True': use_cher = True print("training with CHER") else: use_cher = False print("training without CHER") if 'FetchPushObstacleDoubleGapMulti' in env_name: n_episodes = 200 gamma = 0.9875 else: n_episodes = 100 gamma = 0.98 for i_exp in range(int(exp_config['start_n_exp']), int(exp_config['n_exp'])): obj_rew = False object_Qfunc = None object_policy = None backward_dyn = None print("training without object based rewards") init_2 = init run_2 = run ####################### training robot ########################### model_name = 'DDPG_BD' exp_args2=['--env_id', env_name, '--exp_id', model_name + '_foorob_' + str(i_exp), '--random_seed', str(i_exp), '--agent_alg', model_name, '--verbose', '2', '--render', '0', '--gamma', str(gamma), '--n_episodes', str(n_episodes), '--n_cycles', '50', '--n_rollouts', '38', '--n_test_rollouts', '380', '--n_envs', '38', '--n_batches', '40', '--batch_size', '4864', '--obj_action_type', '0123456', '--max_nb_objects', '1', '--observe_obj_grp', 'False', ] config2 = get_params(args=exp_args2) model2, experiment_args2 = init_2(config2, agent='robot', her=use_cher, object_Qfunc=object_Qfunc, object_policy=object_policy, backward_dyn=backward_dyn, ) env2, memory2, noise2, config2, normalizer2, running_rintr_mean2 = experiment_args2 experiment_args2 = (env2, memory2, noise2, config2, normalizer2, running_rintr_mean2) monitor2, bestmodel = run_2(model2, experiment_args2, train=True) rob_name = env_name if use_cher: rob_name = rob_name + '_CHER_' else: rob_name = rob_name + '_' path = './ObT_models/batch1/' + rob_name + str(i_exp) try: os.makedirs(path) except OSError: print ("Creation of the directory %s failed" % path) else: print ("Successfully created the directory %s" % path) K.save(model2.critics[0].state_dict(), path + '/robot_Qfunc.pt') K.save(model2.actors[0].state_dict(), path + '/robot_policy.pt') K.save(bestmodel[0], path + '/robot_Qfunc_best.pt') K.save(bestmodel[1], path + '/robot_policy_best.pt') with open(path + '/normalizer.pkl', 'wb') as file: pickle.dump(normalizer2, file) with open(path + '/normalizer_best.pkl', 'wb') as file: pickle.dump(bestmodel[2], file) path = './ObT_models/batch1/monitor_' + rob_name + str(i_exp) + '.npy' np.save(path, monitor2) <file_sep>import torch as K import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from olbr.agents.basic import BackwardDyn, RandomNetDist import pdb def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) def hard_update(target, source): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) class DDPG_BD(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, reward_fun=None, clip_Q_neg=None, nb_critics=2, dtype=K.float32, device="cuda"): super(DDPG_BD, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device if isinstance(observation_space, (list, tuple)): observation_space = observation_space[0] self.observation_space = observation_space self.action_space = action_space self.clip_Q_neg = clip_Q_neg if clip_Q_neg is not None else -1./(1.-self.gamma) self.nb_critics = nb_critics # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] self.actors.append(Actor(observation_space, action_space[0], discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space[0], discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[0].parameters(), lr = actor_lr)) hard_update(self.actors_target[0], self.actors[0]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] for i_critic in range(self.nb_critics): self.critics.append(Critic(observation_space, action_space[0]).to(device)) self.critics_target.append(Critic(observation_space, action_space[0]).to(device)) self.critics_optim.append(optimizer(self.critics[i_critic].parameters(), lr = critic_lr)) for i_critic in range(self.nb_critics): hard_update(self.critics_target[i_critic], self.critics[i_critic]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) print('seperaate Qs for multiQ') def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False): self.actors[0].eval() with K.no_grad(): mu = self.actors[0](state.to(self.device)) self.actors[0].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[0].low[0]), int(self.action_space[0].high[0])) return mu def update_parameters(self, batch, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s1 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a1 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, 0:action_space] s1_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[0] is not None: s1 = normalizer[0].preprocess(s1) s1_ = normalizer[0].preprocess(s1_) s, s_, a = s1, s1_, a1 a_ = self.actors_target[0](s_) r = K.tensor(batch['r'], dtype=self.dtype, device=self.device) for i_critic in range(self.nb_critics): Q = self.critics[i_critic](s, a) V = self.critics_target[i_critic](s_, a_).detach() target_Q = (V * self.gamma) + r[:,i_critic:i_critic+1] target_Q = target_Q.clamp(self.clip_Q_neg, 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[i_critic].zero_grad() loss_critic.backward() self.critics_optim[i_critic].step() # actor update a = self.actors[0](s) loss_actor = 0. for i_critic in range(self.nb_critics): loss_actor += - self.critics[i_critic](s, a).mean() if self.regularization: loss_actor += (self.actors[0](s)**2).mean()*1 self.actors_optim[0].zero_grad() loss_actor.backward() self.actors_optim[0].step() return loss_critic.item(), loss_actor.item() def update_target(self): soft_update(self.actors_target[0], self.actors[0], self.tau) for i_critic in range(self.nb_critics): soft_update(self.critics_target[i_critic], self.critics[i_critic], self.tau) <file_sep>import torch as K import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from olbr.agents.basic import BackwardDyn, RandomNetDist import gym_wmgds as gym import pdb def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) def hard_update(target, source): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) class DDPG_BD(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, reward_fun=None, clip_Q_neg=None, nb_critics=2, dtype=K.float32, device="cuda"): super(DDPG_BD, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device #if isinstance(observation_space, (list, tuple)): # observation_space = observation_space[0] self.observation_space = observation_space self.action_space = action_space self.clip_Q_neg = clip_Q_neg if clip_Q_neg is not None else -1./(1.-self.gamma) self.nb_critics = nb_critics self.actor_action_space = gym.spaces.Box(action_space[0].low[0], action_space[0].high[0], shape=(action_space[0].shape[0]//2,), dtype='float32') # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] self.actors.append(Actor(observation_space[1], self.actor_action_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space[1], self.actor_action_space, discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[0].parameters(), lr = actor_lr)) self.actors.append(Actor(observation_space[1], self.actor_action_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space[1], self.actor_action_space, discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[1].parameters(), lr = actor_lr)) hard_update(self.actors_target[0], self.actors[0]) hard_update(self.actors_target[1], self.actors[1]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] for i_critic in range(self.nb_critics): self.critics.append(Critic(observation_space[0], action_space[0]).to(device)) self.critics_target.append(Critic(observation_space[0], action_space[0]).to(device)) self.critics_optim.append(optimizer(self.critics[i_critic].parameters(), lr = critic_lr)) for i_critic in range(self.nb_critics): hard_update(self.critics_target[i_critic], self.critics[i_critic]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) print('seperaate Qs for multiQ') def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False, goal_size=None): if goal_size is None: self.actors[0].eval() with K.no_grad(): mu = self.actors[0](state.to(self.device)) self.actors[0].train() else: self.actors[0].eval() self.actors[1].eval() goal = state[:,-goal_size::] obs = state[:,0:-goal_size] obs1 = K.cat([obs[:,0:obs.shape[1]//2], goal], dim=-1) obs2 = K.cat([obs[:,obs.shape[1]//2::], goal], dim=-1) with K.no_grad(): mu1 = self.actors[0](obs1.to(self.device)) mu2 = self.actors[1](obs2.to(self.device)) mu = K.cat([mu1,mu2], dim=-1) self.actors[0].train() self.actors[1].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[0].low[0]), int(self.action_space[0].high[0])) return mu def update_parameters(self, batch, normalizer=None): observation_space = self.observation_space[0] - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s1 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a1 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, 0:action_space] s1_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[0] is not None: s1 = normalizer[0].preprocess(s1) s1_ = normalizer[0].preprocess(s1_) s, s_, a = s1, s1_, a1 o1 = K.cat([s[:, 0:(observation_space//2)], s[:, observation_space::]], dim=-1) o2 = K.cat([s[:, (observation_space//2):observation_space], s[:, observation_space::]], dim=-1) o = [o1, o2] o1_ = K.cat([s_[:, 0:observation_space//2], s_[:, observation_space::]], dim=-1) o2_ = K.cat([s_[:, observation_space//2:observation_space], s_[:, observation_space::]], dim=-1) a1_ = self.actors_target[0](o1_) a2_ = self.actors_target[1](o2_) a_ = K.cat([a1_, a2_],dim=-1) r = K.tensor(batch['r'], dtype=self.dtype, device=self.device) for i_critic in range(self.nb_critics): Q = self.critics[i_critic](s, a) V = self.critics_target[i_critic](s_, a_).detach() target_Q = (V * self.gamma) + r[:,i_critic:i_critic+1] target_Q = target_Q.clamp(self.clip_Q_neg, 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[i_critic].zero_grad() loss_critic.backward() self.critics_optim[i_critic].step() # actor update for i_actor in range(2): a1 = self.actors[0](o[0]) a2 = self.actors[1](o[1]) a = K.cat([a1, a2],dim=-1) loss_actor = 0. for i_critic in range(self.nb_critics): loss_actor += - self.critics[i_critic](s, a).mean() if self.regularization: loss_actor += (self.actors[i_actor](o[i_actor])**2).mean()*1 self.actors_optim[i_actor].zero_grad() loss_actor.backward() self.actors_optim[i_actor].step() return loss_critic.item(), loss_actor.item() def update_target(self): soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.actors_target[1], self.actors[1], self.tau) for i_critic in range(self.nb_critics): soft_update(self.critics_target[i_critic], self.critics[i_critic], self.tau) <file_sep>import numpy as np import scipy as sc import time import pickle import os import sys import torch as K import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from olbr.utils import get_params as get_params, running_mean, get_exp_params from olbr.main_rnd import init, run, interfere from olbr.agents.basic import TrajectoryDyn device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 K.set_num_threads(1) class MyDataset(Dataset): def __init__(self, data): self.data = data def __len__(self): return len(self.data[0]) def __getitem__(self,idx): return self.data[0][idx], self.data[1][idx], self.data[2][idx], self.data[3][idx] exp_config = get_exp_params(sys.argv[1:]) filepath = exp_config['filepath'] os.chdir(filepath) suffix = '' if exp_config['env'] == 'PushSide': env_name_list = ['FetchPushObstacleSideGapMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PushMiddle': env_name_list = ['FetchPushObstacleMiddleGapMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PushDouble': env_name_list = ['FetchPushObstacleDoubleGapMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPShelf': env_name_list = ['FetchPickAndPlaceShelfMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPObstacle': env_name_list = ['FetchPickAndPlaceObstacleMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPHardest': env_name_list = ['FetchPickAndPlaceHardestMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPInsertion': env_name_list = ['FetchPickAndPlaceInsertionMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'PnPNormal': env_name_list = ['FetchPickAndPlaceMulti{}-v1'.format(suffix)] elif exp_config['env'] == 'All': env_name_list = ['FetchPushObstacleSideGapMulti{}-v1'.format(suffix), 'FetchPushObstacleMiddleGapMulti{}-v1'.format(suffix), 'FetchPushObstacleDoubleGapMulti{}-v1'.format(suffix), 'FetchPickAndPlaceShelfMulti{}-v1'.format(suffix), 'FetchPickAndPlaceObstacleMulti{}-v1'.format(suffix), 'FetchPickAndPlaceHardestMulti{}-v1'.format(suffix), 'FetchPickAndPlaceInsertionMulti{}-v1'.format(suffix), 'FetchPickAndPlaceMulti{}-v1'.format(suffix) ] for env_name in env_name_list: if 'FetchPushObstacleDoubleGapMulti' in env_name: n_episodes = 50 gamma = 0.9875 else: n_episodes = 25 gamma = 0.98 if env_name == 'FetchPushObstacleSideGapMulti-v1': path = './ObT_models/obj/push_side_7d_ep25/' elif env_name == 'FetchPushObstacleMiddleGapMulti-v1': path = './ObT_models/obj/push_middle_7d_ep25/' elif env_name == 'FetchPushObstacleDoubleGapMulti-v1': path = './ObT_models/obj/push_double_7d_ep50/' elif env_name == 'FetchPickAndPlaceShelfMulti-v1': path = './ObT_models/obj/pnp_shelf_7d_ep25/' elif env_name == 'FetchPickAndPlaceObstacleMulti-v1': path = './ObT_models/obj/pnp_obstacle_7d_ep25/' elif env_name == 'FetchPickAndPlaceHardestMulti-v1': path = './ObT_models/obj/pnp_hardest_7d_ep25/' elif env_name == 'FetchPickAndPlaceInsertionMulti-v1': path = './ObT_models/obj/pnp_insertion_7d_ep25/' print('object trajectory model will be created in') print(path) #training object policy model_name = 'DDPG_BD' exp_args=['--env_id', env_name, '--exp_id', model_name + '_foorob_' + str(0), '--random_seed', str(0), '--agent_alg', model_name, '--verbose', '2', '--render', '0', '--gamma', str(gamma), '--n_episodes', str(n_episodes), '--n_cycles', '50', '--n_rollouts', '38', '--n_test_rollouts', '380', '--n_envs', '38', '--n_batches', '40', '--batch_size', '4864', '--obj_action_type', '0123456', '--max_nb_objects', '1', '--observe_obj_grp', 'False', '--rob_policy', '02', '--buffer_length', '10000000', ] config = get_params(args=exp_args) model, experiment_args = init(config, agent='object', her=True, object_Qfunc=None, backward_dyn=None, object_policy=None) env, memory, noise, config, normalizer, agent_id = experiment_args monitor = run(model, experiment_args, train=True) try: os.makedirs(path) except OSError: print ("Creation of the directory %s failed" % path) else: print ("Successfully created the directory %s" % path) K.save(model.critics[0].state_dict(), path + 'object_Qfunc.pt') K.save(model.actors[0].state_dict(), path + 'object_policy.pt') K.save(model.backward.state_dict(), path + 'backward_dyn.pt') with open(path + 'normalizer.pkl', 'wb') as file: pickle.dump(normalizer, file) np.save(path + 'monitor', monitor) #generating object trajectories memory.clear_buffer() interfere(model, experiment_args) #creating the dataset from trajectories time_step = 1 horizon=n_episodes goal_len = memory.buffers['ag'].shape[2] ag_in_all = [] ag_out_all = [] g_in_all = [] step_in_all = [] for i_time in range(time_step,horizon+time_step,time_step): ag_in = memory.buffers['ag'][0:memory.current_size,0,0:goal_len] if i_time == horizon: ag_out = memory.buffers['g'][0:memory.current_size,0,0:goal_len] else: ag_out = memory.buffers['ag'][0:memory.current_size,i_time,0:goal_len] g_in = memory.buffers['g'][0:memory.current_size,0,0:goal_len] ag_in_all.append(ag_in.reshape(-1,goal_len).astype('float32')) ag_out_all.append(ag_out.reshape(-1,goal_len).astype('float32')) g_in_all.append(g_in.reshape(-1,goal_len).astype('float32')) step_in_all.append((np.ones_like(ag_in)[:,0]*i_time).astype('float32')) ag_in_all = np.asarray(ag_in_all).reshape(-1,goal_len) ag_out_all = np.asarray(ag_out_all).reshape(-1,goal_len) g_in_all = np.asarray(g_in_all).reshape(-1,goal_len) step_in_all = np.asarray(step_in_all).reshape(-1,1) ag_in_mean = memory.buffers['ag'][0:memory.current_size].mean((0,1)) ag_in_std = memory.buffers['ag'][0:memory.current_size].std((0,1)) g_in_mean = memory.buffers['g'][0:memory.current_size].mean((0,1)) g_in_std = memory.buffers['g'][0:memory.current_size].std((0,1)) step_in_all_mean = step_in_all.mean(0) step_in_all_std = step_in_all.std(0) obj_mean = [ag_in_mean, g_in_mean, step_in_all_mean] obj_std = [ag_in_std, g_in_std, step_in_all_std] with open(path + 'objGoal_mean.pkl', 'wb') as file: pickle.dump(obj_mean, file) with open(path + 'objGoal_std.pkl', 'wb') as file: pickle.dump(obj_std, file) train_split = 0.7 train_bound = int(train_split*len(ag_in_all)) idxs = np.random.permutation(len(ag_in_all)) train_idxs = idxs[0:train_bound] test_idxs = idxs[train_bound::] ag_in_all -= ag_in_mean ag_in_all /= (ag_in_std + 1e-5) g_in_all -= g_in_mean g_in_all /= (g_in_std + 1e-5) step_in_all -= step_in_all_mean step_in_all /= step_in_all_std train_data = (ag_in_all[train_idxs], g_in_all[train_idxs], step_in_all[train_idxs], ag_out_all[train_idxs]) test_data = (ag_in_all[test_idxs], g_in_all[test_idxs], step_in_all[test_idxs], ag_out_all[test_idxs]) train_dataset = MyDataset(train_data) test_dataset = MyDataset(test_data) train_loader = DataLoader(train_dataset, batch_size=128) test_loader = DataLoader(test_dataset, batch_size=128) #initialising the trajectory model model_objtraj = TrajectoryDyn(goal_len).to(device) optimizer = optim.Adam(model_objtraj.parameters()) #training the trajectory model nb_traj_epochs = 30 for epoch in range(nb_traj_epochs): # training running_loss = 0.0 total = 0. model_objtraj.train() for data in train_loader: # get the inputs X1, X2, X3, T = data X1 = X1.to(device) X2 = X2.to(device) X3 = X3.to(device) T = T.to(device) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize Y = model_objtraj(X1, X2, X3) loss = F.mse_loss(Y, T) loss.backward() optimizer.step() # print statistics total += T.size(0) running_loss += loss.item()#*T.size(0) #running_loss /= total # testing correct_Y = 0. total_test = 0. model_objtraj.eval() with K.no_grad(): for data in test_loader: # get the inputs X1, X2, X3, T = data X1 = X1.to(device) X2 = X2.to(device) X3 = X3.to(device) T = T.to(device) # Y = model_objtraj(X1, X2, X3) total_test += T.size(0) loss = F.mse_loss(Y, T) correct_Y += loss.item() #correct_Y /= total_test print('%d, loss: %.3f, acc = %.3f %%' % (epoch + 1, running_loss, correct_Y)) print('Finished Training of Object Trajectory Model') K.save(model_objtraj.state_dict(), path + 'objGoal_model.pt')<file_sep>import numpy as np import scipy as sc import time import torch as K from olbr.utils import get_params as get_params, running_mean, get_exp_params from olbr.main import init, run from olbr.main_ppo import init as init_ppo from olbr.main_ppo import run as run_ppo import matplotlib.pyplot as plt import os import pickle import sys filepath='/jmain01/home/JAD022/grm01/oxk28-grm01/Dropbox/Jupyter/notebooks/Reinforcement_Learning/' os.chdir(filepath) device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 exp_config = get_exp_params(sys.argv[1:]) if exp_config['env'] == 'Push': env_name = 'FetchPushMulti-v1' elif exp_config['env'] == 'PnP': env_name = 'FetchPickAndPlaceMulti-v1' if exp_config['multiseed'] == 'True': multiseed = True n_envs = 38 from olbr.main import init, run elif exp_config['multiseed'] == 'False': multiseed = False n_envs = 1 from olbr.main import init, run masked_with_r = exp_config['masked_with_r'] if exp_config['use_her'] == 'True': use_her = True else: use_her = False for i_exp in range(0,int(exp_config['n_exp'])): if exp_config['obj_rew'] == 'True': ####################### loading object ########################### model_name = 'DDPG_BD' exp_args=['--env_id', env_name, '--exp_id', model_name + '_fooobj_' + str(0), '--random_seed', str(0), '--agent_alg', model_name, '--verbose', '2', '--render', '0', '--gamma', '0.98', '--n_episodes', '20', '--n_cycles', '50', '--n_rollouts', '38', '--n_test_rollouts', '38', '--n_envs', str(n_envs), '--n_batches', '40', '--batch_size', '256', '--n_bd_batches', '400', '--obj_action_type', '012', '--max_nb_objects', '1', '--observe_obj_grp', 'False', '--rob_policy', '01', ] config = get_params(args=exp_args) model, experiment_args = init(config, agent='object', her=True, object_Qfunc=None, backward_dyn=None, object_policy=None) env, memory, noise, config, normalizer, agent_id = experiment_args #loading the object model if exp_config['env'] == 'Push': path = './models/obj/obj_push_xyz/' elif exp_config['env'] == 'PnP': path = './models/obj/obj_pnp_xyz/' model.critics[0].load_state_dict(K.load(path + 'object_Qfunc.pt')) model.backward.load_state_dict(K.load(path + 'backward_dyn.pt')) model.actors[0].load_state_dict(K.load(path + 'object_policy.pt')) with open(path + 'normalizer.pkl', 'rb') as file: normalizer = pickle.load(file) experiment_args = (env, memory, noise, config, normalizer, agent_id) obj_rew = True object_Qfunc = model.critics[0] backward_dyn = model.backward object_policy = model.actors[0] ####################### loading object ########################### elif exp_config['obj_rew'] == 'False': obj_rew = False object_Qfunc = None backward_dyn = None object_policy = None ####################### training robot ########################### if exp_config['rob_model'] == 'DDPG': model_name = 'DDPG_BD' exp_args2=['--env_id', env_name, '--exp_id', model_name + '_foorob_' + str(i_exp), '--random_seed', str(i_exp), '--agent_alg', model_name, '--verbose', '2', '--render', '0', '--gamma', '0.98', '--n_episodes', '50', '--n_cycles', '50', '--n_rollouts', '38', '--n_test_rollouts', '380', '--n_envs', str(n_envs), '--n_batches', '40', '--batch_size', '256', '--n_bd_batches', '400', '--obj_action_type', '012', '--max_nb_objects', '1', '--observe_obj_grp', 'False', '--rob_policy', '01', '--masked_with_r', masked_with_r, ] config2 = get_params(args=exp_args2) model2, experiment_args2 = init(config2, agent='robot', her=use_her, object_Qfunc=object_Qfunc, backward_dyn=backward_dyn, object_policy=object_policy ) env2, memory2, noise2, config2, normalizer2, agent_id2 = experiment_args2 if obj_rew: normalizer2[1] = normalizer[1] experiment_args2 = (env2, memory2, noise2, config2, normalizer2, agent_id2) monitor2 = run(model2, experiment_args2, train=True) elif exp_config['rob_model'] == 'PPO': model_name = 'PPO_BD' exp_args2=['--env_id', env_name, '--exp_id', model_name + '_foorob_' + str(i_exp), '--random_seed', str(i_exp), '--agent_alg', model_name, '--verbose', '2', '--render', '0', '--gamma', '0.98', '--n_episodes', '50', '--n_cycles', '50', '--n_rollouts', '38', '--n_batches', '4', '--batch_size', '256', '--reward_normalization', 'False', '--ai_object_rate', '0.0', '--obj_action_type', '012', '--max_nb_objects', '1', '--observe_obj_grp', 'True', '--masked_with_r', masked_with_r, '--n_test_rollouts', '100', '--plcy_lr', '3e-4', '--crtc_lr', '3e-4', '--ppo_epoch', '3', '--entropy_coef', '0.00', '--clip_param', '0.1', '--use_gae', "False" ] config2 = get_params(args=exp_args2) model2, experiment_args2 = init_ppo(config2, agent='robot', her=False, object_Qfunc=object_Qfunc, backward_dyn=backward_dyn, object_policy=object_policy ) env2, memory2, noise2, config2, normalizer2, agent_id2 = experiment_args2 normalizer2[1] = normalizer[1] experiment_args2 = (env2, memory2, noise2, config2, normalizer2, agent_id2) monitor2 = run_ppo(model2, experiment_args2, train=True) rob_name = exp_config['env'] if exp_config['rob_model'] == 'PPO': if obj_rew: rob_name = rob_name + '_v4_PPO_' else: rob_name = rob_name + '_PPO_' elif exp_config['rob_model'] == 'DDPG': if obj_rew: if use_her: rob_name = rob_name + '_v4_HER_' else: rob_name = rob_name + '_v4_DDPG_' else: if use_her: rob_name = rob_name + '_HER_' else: rob_name = rob_name + '_DDPG_' rob_name = rob_name + 'Norm_Slide_Clipped_Both_' if masked_with_r: rob_name = rob_name + 'Masked_PlusR' else: rob_name = rob_name + 'PlusR' if multiseed: rob_name = rob_name + '_Multiseed' else: rob_name = rob_name + '_Singleseed' path = './models/_recent/rob_model_' + rob_name + '_' + str(i_exp) try: os.makedirs(path) except OSError: print ("Creation of the directory %s failed" % path) else: print ("Successfully created the directory %s" % path) K.save(model2.critics[0].state_dict(), path + '/robot_Qfunc.pt') K.save(model2.actors[0].state_dict(), path + '/robot_policy.pt') if obj_rew: K.save(model2.object_Qfunc.state_dict(), path + '/object_Qfunc.pt') K.save(model2.backward.state_dict(), path + '/backward_dyn.pt') K.save(model2.object_policy.state_dict(), path + '/object_policy.pt') with open(path + '/normalizer.pkl', 'wb') as file: pickle.dump(normalizer2, file) path = './monitors/_recent/monitor_' + rob_name + '_' + str(i_exp) + '.npy' np.save(path, monitor2) <file_sep># Object Locomotion based Rewards <file_sep>import torch as K import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from olbr.exploration import gumbel_softmax from olbr.agents.basic import ForwardDynReg, AutoEncReg, AutoEncNextReg import pdb def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) def hard_update(target, source): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) class DDPG(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(DDPG, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] self.actors.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[0].parameters(), lr = actor_lr)) hard_update(self.actors_target[0], self.actors[0]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] self.critics.append(Critic(observation_space, action_space).to(device)) self.critics_target.append(Critic(observation_space, action_space).to(device)) self.critics_optim.append(optimizer(self.critics[0].parameters(), lr = critic_lr)) hard_update(self.critics_target[0], self.critics[0]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False): self.actors[0].eval() with K.no_grad(): mu = self.actors[0](state.to(self.device)) self.actors[0].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space.low[0]), int(self.action_space.high[0])) return mu def update_parameters(self, batch, normalizer=None): mask = K.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=K.uint8, device=self.device) V = K.zeros((len(batch.state), 1), device=self.device) s = K.cat(batch.state, dim=0).to(self.device) a = K.cat(batch.action, dim=0).to(self.device) r = K.cat(batch.reward, dim=0).to(self.device) s_ = K.cat([i.to(self.device) for i in batch.next_state if i is not None], dim=0) a_ = K.zeros_like(a)[:,0:s_.shape[0],] if normalizer[0] is not None: s = normalizer[0].preprocess(s) s_ = normalizer[0].preprocess(s_) if self.normalized_rewards: if normalizer[1] is not None: r = r #r = normalizer[1].preprocess(r) else: r -= r.mean() r /= r.std() Q = self.critics[0](s, a) a_ = self.actors_target[0](s_) V[mask] = self.critics_target[0](s_, a_).detach() #loss_critic = self.loss_func(Q, (V * self.gamma) + r) target_Q = (V * self.gamma) + r target_Q = target_Q.clamp(-1./(1.-self.gamma), 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[0].zero_grad() loss_critic.backward() K.nn.utils.clip_grad_norm_(self.critics[0].parameters(), 0.5) self.critics_optim[0].step() a = self.actors[0](s) loss_actor = -self.critics[0](s, a).mean() if self.regularization: #loss_actor += (self.actors[0].get_preactivations(s)**2).mean()*1 loss_actor += (self.actors[0](s)**2).mean()*1 self.actors_optim[0].zero_grad() loss_actor.backward() K.nn.utils.clip_grad_norm_(self.actors[0].parameters(), 0.5) self.actors_optim[0].step() soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) return loss_critic.item(), loss_actor.item() class DDPG_GAR(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(DDPG_GAR, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] self.actors.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[0].parameters(), lr = actor_lr)) hard_update(self.actors_target[0], self.actors[0]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] self.critics.append(Critic(observation_space, action_space).to(device)) self.critics_target.append(Critic(observation_space, action_space).to(device)) self.critics_optim.append(optimizer(self.critics[0].parameters(), lr = critic_lr)) hard_update(self.critics_target[0], self.critics[0]) self.critics.append(Critic(observation_space, action_space).to(device)) self.critics_target.append(Critic(observation_space, action_space).to(device)) self.critics_optim.append(optimizer(self.critics[1].parameters(), lr = critic_lr)) hard_update(self.critics_target[1], self.critics[1]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) # Forward Dynamics Network self.forward = AutoEncNextReg(observation_space, action_space).to(device) #self.forward = AutoEncReg(observation_space, action_space).to(device) #self.forward = ForwardDynReg(observation_space, action_space).to(device) self.forward_optim = optimizer(self.forward.parameters(), lr = critic_lr) self.entities.append(self.forward) self.entities.append(self.forward_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False): self.actors[0].eval() with K.no_grad(): mu = self.actors[0](state.to(self.device)) self.actors[0].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space.low[0]), int(self.action_space.high[0])) return mu def update_parameters(self, batch, normalizer=None): mask = K.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=K.uint8, device=self.device) V = K.zeros((len(batch.state), 1), device=self.device) s = K.cat(batch.state, dim=0).to(self.device) a = K.cat(batch.action, dim=0).to(self.device) r = K.cat(batch.reward, dim=0).to(self.device) s_ = K.cat([i.to(self.device) for i in batch.next_state if i is not None], dim=0) a_ = K.zeros_like(a)[:,0:s_.shape[0],] if self.normalized_rewards: if normalizer[1] is not None: r = r #r = normalizer[1].preprocess(r) else: r -= r.mean() r /= r.std() if normalizer[0] is not None: normed_s = normalizer[0].preprocess(s) normed_s_ = normalizer[0].preprocess(s_) #p = self.forward.get_intr_rewards(s,a) p = K.zeros_like(r) p[mask], M = self.forward.get_intr_rewards(normed_s_) if self.normalized_rewards: if normalizer[2] is not None: p = normalizer[2].preprocess_with_update(p.to('cpu')).to(self.device) else: p -= p.mean() p /= p.std() # extrinsic Q update Q = self.critics[0](normed_s, a) a_ = self.actors_target[0](normed_s_) V[mask] = self.critics_target[0](normed_s_, a_).detach() loss_critic = self.loss_func(Q, (V * self.gamma) + r + 0.1*p) self.critics_optim[0].zero_grad() loss_critic.backward() K.nn.utils.clip_grad_norm_(self.critics[0].parameters(), 0.5) self.critics_optim[0].step() # intrinsic Q update Q = self.critics[1](normed_s, a) V[mask] = self.critics_target[1](normed_s_, a_).detach() loss_critic = self.loss_func(Q, (V * self.gamma) + p) # in case of reward propagation #reg_critic = self.critics[0].GAR(1, 1, 0.000001) #loss_critic += reg_critic self.critics_optim[1].zero_grad() loss_critic.backward() K.nn.utils.clip_grad_norm_(self.critics[1].parameters(), 0.5) self.critics_optim[1].step() # actor update a = self.actors[0](normed_s) loss_actor = - self.critics[0](normed_s, a).mean() - 0.1*self.critics[1](normed_s, a).mean() #- self.critics[0].GAR(1, 1, 0.000001) if self.regularization: loss_actor += (self.actors[0].get_preactivations(normed_s)**2).mean()*1 self.actors_optim[0].zero_grad() loss_actor.backward() K.nn.utils.clip_grad_norm_(self.actors[0].parameters(), 0.5) self.actors_optim[0].step() soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) soft_update(self.critics_target[1], self.critics[1], self.tau) p = p.squeeze(1).cpu().numpy() r = r.squeeze(1).cpu().numpy() ind = np.argsort(p) return loss_critic.item(), loss_actor.item(), p[ind], r[ind], M def update_forward(self, batch, normalizer=None): mask = K.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=K.uint8, device=self.device) s = K.cat(batch.state, dim=0).to(self.device) a = K.cat(batch.action, dim=0).to(self.device) s_ = K.cat([i.to(self.device) for i in batch.next_state if i is not None], dim=0) if normalizer[0] is not None: s = normalizer[0].preprocess(s) s_ = normalizer[0].preprocess(s_) #pred = self.forward(s,a) pred = self.forward(s_) #loss_forward = self.loss_func(pred[mask], s_) loss_forward = self.loss_func(pred, s_) #loss_forward = self.loss_func(pred, K.cat([s, a], dim=1)) reg_forward = self.forward.GAR(0.03, 0.03, 0.001, False) #reg_forward = self.forward.GAR(1, 1, 1) loss_forward += reg_forward self.forward_optim.zero_grad() loss_forward.backward() #K.nn.utils.clip_grad_norm_(self.forward.parameters(), 0.5) self.forward_optim.step() return loss_forward.item()-reg_forward.item(), reg_forward.item() class HDDPG(object): def __init__(self, observation_space, action_space, goal_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(HDDPG, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.action_space = action_space self.goal_space = goal_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] self.actors.append(Actor(observation_space+goal_space.shape[0], action_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space+goal_space.shape[0], action_space, discrete, out_func).to(device)) self.actors.append(Actor(observation_space, goal_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, goal_space, discrete, out_func).to(device)) for i in range(len(self.actors)): self.actors_optim.append(optimizer(self.actors[i].parameters(), lr = actor_lr)) hard_update(self.actors_target[i], self.actors[i]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] self.critics.append(Critic(observation_space+goal_space.shape[0], action_space).to(device)) self.critics_target.append(Critic(observation_space+goal_space.shape[0], action_space).to(device)) self.critics.append(Critic(observation_space, goal_space).to(device)) self.critics_target.append(Critic(observation_space, goal_space).to(device)) for i in range(len(self.critics)): self.critics_optim.append(optimizer(self.critics[i].parameters(), lr = critic_lr)) hard_update(self.critics_target[i], self.critics[i]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_goal(self, state, exploration=False): self.actors[1].eval() with K.no_grad(): mu = self.actors[1](state.to(self.device)) self.actors[1].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) #mu = mu * K.tensor(self.goal_space.high[0], dtype=self.dtype, device=self.device) mu = mu.clamp(-1, 1) return mu def select_action(self, state, exploration=False): self.actors[0].eval() with K.no_grad(): mu = self.actors[0](state.to(self.device)) self.actors[0].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu * K.tensor(self.action_space.high[0], dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space.low[0]), int(self.action_space.high[0])) return mu def update_parameters(self, batch): for i in range(2): mask = K.tensor(tuple(map(lambda s: s is not None, batch[i].next_state)), dtype=K.uint8, device=self.device) V = K.zeros((len(batch[i].state), 1), device=self.device) s = K.cat(batch[i].state, dim=0).to(self.device) a = K.cat(batch[i].action, dim=0).to(self.device) r = K.cat(batch[i].reward, dim=0).to(self.device) s_ = K.cat([i.to(self.device) for i in batch[i].next_state if i is not None], dim=0) a_ = K.zeros_like(a)[:,0:s_.shape[0],] if self.normalized_rewards: r -= r.mean() r /= r.std() Q = self.critics[i](s, a) a_ = self.actors_target[i](s_) V[mask] = self.critics_target[i](s_, a_).detach() loss_critic = self.loss_func(Q, (V * self.gamma) + r) self.critics_optim[i].zero_grad() loss_critic.backward() K.nn.utils.clip_grad_norm_(self.critics[i].parameters(), 0.5) self.critics_optim[i].step() a = self.actors[i](s) loss_actor = -self.critics[i](s, a).mean() if self.regularization: loss_actor += (self.actors[i].get_preactivations(s)**2).mean()*1 self.actors_optim[i].zero_grad() loss_actor.backward() K.nn.utils.clip_grad_norm_(self.actors[i].parameters(), 0.5) self.actors_optim[i].step() soft_update(self.actors_target[i], self.actors[i], self.tau) soft_update(self.critics_target[i], self.critics[i], self.tau) return loss_critic.item(), loss_actor.item() class DDPGC(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(DDPGC, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] self.actors.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[0].parameters(), lr = actor_lr)) hard_update(self.actors_target[0], self.actors[0]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] self.critics.append(Critic(observation_space, action_space).to(device)) self.critics_target.append(Critic(observation_space, action_space).to(device)) self.critics_optim.append(optimizer(self.critics[0].parameters(), lr = critic_lr)) hard_update(self.critics_target[0], self.critics[0]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) # actors self.cactors = [] self.cactors_target = [] self.cactors_optim = [] self.cactors.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.cactors_target.append(Actor(observation_space, action_space, discrete, out_func).to(device)) self.cactors_optim.append(optimizer(self.cactors[0].parameters(), lr = actor_lr)) hard_update(self.cactors_target[0], self.cactors[0]) self.entities.extend(self.cactors) self.entities.extend(self.cactors_target) self.entities.extend(self.cactors_optim) # critics self.ccritics = [] self.ccritics_target = [] self.ccritics_optim = [] self.ccritics.append(Critic(observation_space, action_space).to(device)) self.ccritics_target.append(Critic(observation_space, action_space).to(device)) self.ccritics_optim.append(optimizer(self.ccritics[0].parameters(), lr = critic_lr)) hard_update(self.ccritics_target[0], self.ccritics[0]) self.entities.extend(self.ccritics) self.entities.extend(self.ccritics_target) self.entities.extend(self.ccritics_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, exploration=False): self.actors[0].eval() self.cactors[0].eval() with K.no_grad(): mu = self.actors[0](state.to(self.device)) cmu = self.cactors[0](state.to(self.device)) self.actors[0].train() self.cactors[0].train() mu = mu*(1 - cmu) mu = K.tensor(self.action_space.low[0], dtype=mu.dtype, device=mu.device) + mu*K.tensor((self.action_space.high[0]-self.action_space.low[0]), dtype=mu.dtype, device=mu.device) if exploration: mu += K.tensor(exploration.noise(), dtype=self.dtype, device=self.device) cmu += K.tensor(exploration.noise(), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space.low[0]), int(self.action_space.high[0])) return mu def update_parameters(self, batch): mask = K.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=K.uint8, device=self.device) V = K.zeros((len(batch.state), 1), device=self.device) s = K.cat(batch.state, dim=0).to(self.device) a = K.cat(batch.action, dim=0).to(self.device) r = K.cat(batch.reward, dim=0).to(self.device) s_ = K.cat([i.to(self.device) for i in batch.next_state if i is not None], dim=0) a_ = K.zeros_like(a)[:,0:s_.shape[0],] if self.normalized_rewards: r -= r.mean() r /= r.std() Q = self.critics[0](s, a) a_ = self.actors_target[0](s_) V[mask] = self.critics_target[0](s_, a_).detach() loss_critic = self.loss_func(Q, (V * self.gamma) + r) self.critics_optim[0].zero_grad() loss_critic.backward() K.nn.utils.clip_grad_norm_(self.critics[0].parameters(), 0.5) self.critics_optim[0].step() a = self.actors[0](s) loss_actor = -self.critics[0](s, a).mean() if self.regularization: loss_actor += (self.actors[0].get_preactivations(s)**2).mean()*1e-3 self.actors_optim[0].zero_grad() loss_actor.backward() K.nn.utils.clip_grad_norm_(self.actors[0].parameters(), 0.5) self.actors_optim[0].step() soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) mask = K.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=K.uint8, device=self.device) V = K.zeros((len(batch.state), 1), device=self.device) s = K.cat(batch.state, dim=0).to(self.device) a = K.cat(batch.action, dim=0).to(self.device) r = K.cat(batch.reward, dim=0).to(self.device) s_ = K.cat([i.to(self.device) for i in batch.next_state if i is not None], dim=0) a_ = K.zeros_like(a)[:,0:s_.shape[0],] if self.normalized_rewards: r -= r.mean() r /= r.std() Q = self.ccritics[0](s, a) a_ = self.cactors_target[0](s_) V[mask] = self.ccritics_target[0](s_, a_).detach() loss_critic = self.loss_func(Q, (V * self.gamma) + (1-r)) self.ccritics_optim[0].zero_grad() loss_critic.backward() K.nn.utils.clip_grad_norm_(self.ccritics[0].parameters(), 0.5) self.ccritics_optim[0].step() a = self.cactors[0](s) loss_actor = -self.ccritics[0](s, a).mean() if self.regularization: loss_actor += (self.cactors[0].get_preactivations(s)**2).mean()*1e-3 self.cactors_optim[0].zero_grad() loss_actor.backward() K.nn.utils.clip_grad_norm_(self.cactors[0].parameters(), 0.5) self.cactors_optim[0].step() soft_update(self.cactors_target[0], self.cactors[0], self.tau) soft_update(self.ccritics_target[0], self.ccritics[0], self.tau) return loss_critic.item(), loss_actor.item() # class MAHCDDPG(PARENT): # def __init__(self, num_agents, observation_space, action_space, medium_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, # discrete=True, regularization=False, normalized_rewards=False, communication=None, discrete_comm=True, Comm_Actor=None, Comm_Critic=None, dtype=K.float32, device="cuda"): # super().__init__(num_agents, observation_space, action_space, medium_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func, # discrete, regularization, normalized_rewards, communication, discrete_comm, Comm_Actor, Comm_Critic, dtype, device) # optimizer, lr = optimizer # actor_lr, critic_lr, comm_actor_lr, comm_critic_lr = lr # # model initialization # self.entities = [] # # actors # self.actors = [] # self.actors_target = [] # self.actors_optim = [] # for i in range(num_agents): # self.actors.append(Actor(observation_space+medium_space, action_space, discrete, out_func).to(device)) # self.actors_target.append(Actor(observation_space+medium_space, action_space, discrete, out_func).to(device)) # self.actors_optim.append(optimizer(self.actors[i].parameters(), actor_lr)) # for i in range(num_agents): # hard_update(self.actors_target[i], self.actors[i]) # self.entities.extend(self.actors) # self.entities.extend(self.actors_target) # self.entities.extend(self.actors_optim) # # critics # self.critics = [] # self.critics_target = [] # self.critics_optim = [] # for i in range(num_agents): # self.critics.append(Critic(observation_space+medium_space, action_space).to(device)) # self.critics_target.append(Critic(observation_space+medium_space, action_space).to(device)) # self.critics_optim.append(optimizer(self.critics[i].parameters(), lr = critic_lr)) # for i in range(num_agents): # hard_update(self.critics_target[i], self.critics[i]) # self.entities.extend(self.critics) # self.entities.extend(self.critics_target) # self.entities.extend(self.critics_optim) # # communication actors # self.comm_actors = [] # self.comm_actors_target = [] # self.comm_actors_optim = [] # for i in range(num_agents): # self.comm_actors.append(Comm_Actor(observation_space, 1, discrete_comm, K.sigmoid).to(device)) # self.comm_actors_target.append(Comm_Actor(observation_space, 1, discrete_comm, K.sigmoid).to(device)) # self.comm_actors_optim.append(optimizer(self.comm_actors[i].parameters(), lr = comm_actor_lr)) # for i in range(num_agents): # hard_update(self.comm_actors_target[i], self.comm_actors[i]) # self.entities.extend(self.comm_actors) # self.entities.extend(self.comm_actors_target) # self.entities.extend(self.comm_actors_optim) # # communication critics # self.comm_critics = [] # self.comm_critics_target = [] # self.comm_critics_optim = [] # for i in range(num_agents): # self.comm_critics.append(Comm_Critic(observation_space*num_agents, 1*num_agents).to(device)) # self.comm_critics_target.append(Comm_Critic(observation_space*num_agents, 1*num_agents).to(device)) # self.comm_critics_optim.append(optimizer(self.comm_critics[i].parameters(), lr = comm_critic_lr)) # for i in range(num_agents): # hard_update(self.comm_critics_target[i], self.comm_critics[i]) # print('amanin') # def select_comm_action(self, state, i_agent, exploration=False): # self.comm_actors[i_agent].eval() # with K.no_grad(): # mu = self.comm_actors[i_agent](state.to(self.device)) # self.actors[i_agent].train() # if self.discrete_comm: # mu = gumbel_softmax(mu, exploration=exploration) # else: # if exploration: # mu += K.tensor(exploration.noise(), dtype=self.dtype, device=self.device) # mu = mu.clamp(0, 1) # return mu # def update_parameters(self, batch, batch2, i_agent): # mask = K.tensor(tuple(map(lambda s: s is not None, batch.next_state)), dtype=K.uint8, device=self.device) # V = K.zeros((len(batch.state), 1), device=self.device) # s = K.cat(batch.state, dim=1).to(self.device) # a = K.cat(batch.action, dim=1).to(self.device) # r = K.cat(batch.reward, dim=1).to(self.device) # s_ = K.cat([i.to(self.device) for i in batch.next_state if i is not None], dim=1) # a_ = K.zeros_like(a)[:,0:s_.shape[1],] # m = K.cat(batch.medium, dim=1).to(self.device) # if self.normalized_rewards: # r -= r.mean() # r /= r.std() # Q = self.critics[i_agent](K.cat([s[[i_agent],], m], dim=-1), # a[[i_agent],]) # for i in range(self.num_agents): # a_[i,] = self.actors_target[i](K.cat([s_[[i],], m[:,mask,]], dim=-1)) # V[mask] = self.critics_target[i_agent](K.cat([s_[[i_agent],], m[:,mask,]], dim=-1), # a_[[i_agent],]).detach() # loss_critic = self.loss_func(Q, (V * self.gamma) + r[[i_agent],].squeeze(0)) # self.critics_optim[i_agent].zero_grad() # loss_critic.backward() # K.nn.utils.clip_grad_norm_(self.critics[i_agent].parameters(), 0.5) # self.critics_optim[i_agent].step() # for i in range(self.num_agents): # a[i,] = self.actors[i](K.cat([s[[i],], m], dim=-1)) # loss_actor = -self.critics[i_agent](K.cat([s[[i_agent],], m], dim=-1), # a[[i_agent],]).mean() # if self.regularization: # loss_actor += (self.actors[i_agent].get_preactivations(K.cat([s[[i_agent],], m], dim=-1))**2).mean()*1e-3 # self.actors_optim[i_agent].zero_grad() # loss_actor.backward() # K.nn.utils.clip_grad_norm_(self.actors[i_agent].parameters(), 0.5) # self.actors_optim[i_agent].step() # soft_update(self.actors_target[i_agent], self.actors[i_agent], self.tau) # soft_update(self.critics_target[i_agent], self.critics[i_agent], self.tau) # ## update of the communication part # mask = K.tensor(tuple(map(lambda s: s is not None, batch2.next_state)), dtype=K.uint8, device=self.device) # V = K.zeros((len(batch2.state), 1), device=self.device) # s = K.cat(batch2.state, dim=1).to(self.device) # r = K.cat(batch2.reward, dim=1).to(self.device) # s_ = K.cat([i.to(self.device) for i in batch2.next_state if i is not None], dim=1) # c = K.cat(batch2.comm_action, dim=1).to(self.device) # c_ = K.zeros_like(c)[:,0:s_.shape[1],] # if self.normalized_rewards: # r -= r.mean() # r /= r.std() # Q = self.comm_critics[i_agent](s, c) # for i in range(self.num_agents): # if self.discrete_comm: # c_[i,] = gumbel_softmax(self.comm_actors_target[i](s_[[i],]), exploration=False) # else: # c_[i,] = self.comm_actors_target[i](s_[[i],]) # V[mask] = self.comm_critics_target[i_agent](s_, c_).detach() # loss_critic = self.loss_func(Q, (V * self.gamma) + r[[i_agent],].squeeze(0)) # self.comm_critics_optim[i_agent].zero_grad() # loss_critic.backward() # K.nn.utils.clip_grad_norm_(self.comm_critics[i_agent].parameters(), 0.5) # self.comm_critics_optim[i_agent].step() # for i in range(self.num_agents): # if self.discrete_comm: # c[i,] = gumbel_softmax(self.comm_actors[i](s[[i],]), exploration=False) # else: # c[i,] = self.comm_actors[i](s[[i],]) # loss_actor = -self.comm_critics[i_agent](s, c).mean() # if self.regularization: # loss_actor += (self.comm_actors[i_agent].get_preactivations(s[[i_agent],])**2).mean()*1e-3 # self.comm_actors_optim[i_agent].zero_grad() # loss_actor.backward() # K.nn.utils.clip_grad_norm_(self.comm_actors[i_agent].parameters(), 0.5) # self.comm_actors_optim[i_agent].step() # soft_update(self.comm_actors_target[i_agent], self.comm_actors[i_agent], self.tau) # soft_update(self.comm_critics_target[i_agent], self.comm_critics[i_agent], self.tau) # return loss_critic.item(), loss_actor.item() <file_sep>import torch as K import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from olbr.agents.basic import BackwardDyn import pdb def soft_update(target, source, tau): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau) def hard_update(target, source): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data) class MADDPG(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(MADDPG, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.observation_space = observation_space self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] for i in range(2): self.actors.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[i].parameters(), lr = actor_lr)) for i in range(2): hard_update(self.actors_target[i], self.actors[i]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] for i in range(2): self.critics.append(Critic(observation_space*2, action_space[2]).to(device)) self.critics_target.append(Critic(observation_space*2, action_space[2]).to(device)) self.critics_optim.append(optimizer(self.critics[i].parameters(), lr = critic_lr)) for i in range(2): hard_update(self.critics_target[i], self.critics[i]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, i_agent, exploration=False): self.actors[i_agent].eval() with K.no_grad(): mu = self.actors[i_agent](state.to(self.device)) self.actors[i_agent].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[i_agent].low[0]), int(self.action_space[i_agent].high[0])) return mu def update_parameters(self, batch, i_agent, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] mask = K.tensor(tuple(map(lambda ai_object: ai_object==0, K.tensor(batch['o'][:,-1]))), dtype=K.uint8, device=self.device) V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s1 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a1 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, 0:action_space] a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] r = K.tensor(batch['r'], dtype=self.dtype, device=self.device).unsqueeze(1) s1_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[0] is not None: s1 = normalizer[0].preprocess(s1) s1_ = normalizer[0].preprocess(s1_) if normalizer[1] is not None: s2 = normalizer[1].preprocess(s2) s2_ = normalizer[1].preprocess(s2_) s = [s1, s2] a1_ = self.actors_target[0](s1_) a2_ = self.actors_target[1](s2_) a2_[mask] *= 0.00 # Critics # updating the critic of the robot Q = self.critics[i_agent](K.cat([s1,s2],dim=1), K.cat([a1,a2],dim=1)) V = self.critics_target[i_agent](K.cat([s1_,s2_],dim=1), K.cat([a1_,a2_],dim=1)).detach() target_Q = (V * self.gamma) + r target_Q = target_Q.clamp(-1./(1.-self.gamma), 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[i_agent].zero_grad() loss_critic.backward() self.critics_optim[i_agent].step() # Actors a1 = self.actors[0](s1) a2 = self.actors[1](s2) a2[mask] *= 0.00 loss_actor = -self.critics[i_agent](K.cat([s1,s2],dim=1), K.cat([a1,a2],dim=1)).mean() if self.regularization: loss_actor += (self.actors[i_agent](s[i_agent])**2).mean()*1 self.actors_optim[i_agent].zero_grad() loss_actor.backward() #K.nn.utils.clip_grad_norm_(self.actors[0].parameters(), 0.5) self.actors_optim[i_agent].step() return loss_critic.item(), loss_actor.item() def update_target(self): soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) soft_update(self.actors_target[1], self.actors[1], self.tau) soft_update(self.critics_target[1], self.critics[1], self.tau) class DDPG(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(DDPG, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.observation_space = observation_space self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] for i in range(2): self.actors.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[i].parameters(), lr = actor_lr)) for i in range(2): hard_update(self.actors_target[i], self.actors[i]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] for i in range(2): self.critics.append(Critic(observation_space, action_space[i]).to(device)) self.critics_target.append(Critic(observation_space, action_space[i]).to(device)) self.critics_optim.append(optimizer(self.critics[i].parameters(), lr = critic_lr)) for i in range(2): hard_update(self.critics_target[i], self.critics[i]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, i_agent, exploration=False): self.actors[i_agent].eval() with K.no_grad(): mu = self.actors[i_agent](state.to(self.device)) self.actors[i_agent].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[i_agent].low[0]), int(self.action_space[i_agent].high[0])) return mu def update_parameters(self, batch, i_agent, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] mask = K.tensor(tuple(map(lambda ai_object: ai_object==0, K.tensor(batch['o'][:,-1]))), dtype=K.uint8, device=self.device) V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s1 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a1 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, 0:action_space] a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] r = K.tensor(batch['r'], dtype=self.dtype, device=self.device).unsqueeze(1) s1_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[0] is not None: s1 = normalizer[0].preprocess(s1) s1_ = normalizer[0].preprocess(s1_) if normalizer[1] is not None: s2 = normalizer[1].preprocess(s2) s2_ = normalizer[1].preprocess(s2_) a1_ = self.actors_target[0](s1_) a2_ = self.actors_target[1](s2_) a2_[mask] *= 0.00 s = [s1, s2] s_ = [s1_, s2_] a = [a1, a2] a_ = [a1_, a2_] # Critics Q = self.critics[i_agent](s[i_agent], a[i_agent]) V = self.critics_target[i_agent](s_[i_agent], a_[i_agent]).detach() target_Q = (V * self.gamma) + r target_Q = target_Q.clamp(-1./(1.-self.gamma), 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[i_agent].zero_grad() loss_critic.backward() self.critics_optim[i_agent].step() # Actors a1 = self.actors[0](s1) a2 = self.actors[1](s2) a2[mask] *= 0.00 a = [a1, a2] loss_actor = -self.critics[i_agent](s[i_agent], a[i_agent]).mean() if self.regularization: loss_actor += (self.actors[i_agent](s[i_agent])**2).mean()*1 self.actors_optim[i_agent].zero_grad() loss_actor.backward() self.actors_optim[i_agent].step() return loss_critic.item(), loss_actor.item() def update_target(self): soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) soft_update(self.actors_target[1], self.actors[1], self.tau) soft_update(self.critics_target[1], self.critics[1], self.tau) class MADDPG_R(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(MADDPG_R, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.observation_space = observation_space self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] for i in range(2): self.actors.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[i].parameters(), lr = actor_lr)) for i in range(2): hard_update(self.actors_target[i], self.actors[i]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] for i in range(2): self.critics.append(Critic(observation_space, action_space[2]).to(device)) self.critics_target.append(Critic(observation_space, action_space[2]).to(device)) self.critics_optim.append(optimizer(self.critics[i].parameters(), lr = critic_lr)) for i in range(2): hard_update(self.critics_target[i], self.critics[i]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, i_agent, exploration=False): self.actors[i_agent].eval() with K.no_grad(): mu = self.actors[i_agent](state.to(self.device)) self.actors[i_agent].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[i_agent].low[0]), int(self.action_space[i_agent].high[0])) return mu def update_parameters(self, batch, i_agent, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] mask = K.tensor(tuple(map(lambda ai_object: ai_object==0, K.tensor(batch['o'][:,-1]))), dtype=K.uint8, device=self.device) V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s1 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a1 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, 0:action_space] a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] r = K.tensor(batch['r'], dtype=self.dtype, device=self.device).unsqueeze(1) s1_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) if normalizer[0] is not None: s1 = normalizer[0].preprocess(s1) s1_ = normalizer[0].preprocess(s1_) if normalizer[1] is not None: s2 = normalizer[1].preprocess(s2) s2_ = normalizer[1].preprocess(s2_) a1_ = self.actors_target[0](s1_) a2_ = self.actors_target[1](s2_) a2_[mask] *= 0.00 s = [s1, s2] s_ = [s1_, s2_] # Critics Q = self.critics[i_agent](s[i_agent], K.cat([a1, a2],dim=1)) V = self.critics_target[i_agent](s_[i_agent], K.cat([a1_, a2_],dim=1)).detach() target_Q = (V * self.gamma) + r target_Q = target_Q.clamp(-1./(1.-self.gamma), 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[i_agent].zero_grad() loss_critic.backward() self.critics_optim[i_agent].step() # Actors a1 = self.actors[0](s1) a2 = self.actors[1](s2) a2[mask] *= 0.00 loss_actor = -self.critics[i_agent](s[i_agent], K.cat([a1, a2],dim=1)).mean() if self.regularization: loss_actor += (self.actors[i_agent](s[i_agent])**2).mean()*1 self.actors_optim[i_agent].zero_grad() loss_actor.backward() self.actors_optim[i_agent].step() return loss_critic.item(), loss_actor.item() def update_target(self): soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) soft_update(self.actors_target[1], self.actors[1], self.tau) soft_update(self.critics_target[1], self.critics[1], self.tau) class MADDPG_RAE(object): def __init__(self, observation_space, action_space, optimizer, Actor, Critic, loss_func, gamma, tau, out_func=K.sigmoid, discrete=True, regularization=False, normalized_rewards=False, dtype=K.float32, device="cuda"): super(MADDPG_RAE, self).__init__() optimizer, lr = optimizer actor_lr, critic_lr = lr self.loss_func = loss_func self.gamma = gamma self.tau = tau self.out_func = out_func self.discrete = discrete self.regularization = regularization self.normalized_rewards = normalized_rewards self.dtype = dtype self.device = device self.observation_space = observation_space self.action_space = action_space # model initialization self.entities = [] # actors self.actors = [] self.actors_target = [] self.actors_optim = [] for i in range(2): self.actors.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_target.append(Actor(observation_space, action_space[i], discrete, out_func).to(device)) self.actors_optim.append(optimizer(self.actors[i].parameters(), lr = actor_lr)) for i in range(2): hard_update(self.actors_target[i], self.actors[i]) self.entities.extend(self.actors) self.entities.extend(self.actors_target) self.entities.extend(self.actors_optim) # critics self.critics = [] self.critics_target = [] self.critics_optim = [] for i in range(2): self.critics.append(Critic(observation_space, action_space[2]).to(device)) self.critics_target.append(Critic(observation_space, action_space[2]).to(device)) self.critics_optim.append(optimizer(self.critics[i].parameters(), lr = critic_lr)) for i in range(2): hard_update(self.critics_target[i], self.critics[i]) self.entities.extend(self.critics) self.entities.extend(self.critics_target) self.entities.extend(self.critics_optim) # backward dynamics model self.backward = BackwardDyn(3, action_space[1]).to(device) self.backward_optim = optimizer(self.backward.parameters(), lr = critic_lr) self.entities.append(self.backward) self.entities.append(self.backward_optim) def to_cpu(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cpu() self.device = 'cpu' def to_cuda(self): for entity in self.entities: if type(entity) != type(self.actors_optim[0]): entity.cuda() self.device = 'cuda' def select_action(self, state, i_agent, exploration=False): self.actors[i_agent].eval() with K.no_grad(): mu = self.actors[i_agent](state.to(self.device)) self.actors[i_agent].train() if exploration: mu = K.tensor(exploration.get_noisy_action(mu.cpu().numpy()), dtype=self.dtype, device=self.device) mu = mu.clamp(int(self.action_space[i_agent].low[0]), int(self.action_space[i_agent].high[0])) return mu def update_parameters(self, batch, i_agent, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] mask = K.tensor(tuple(map(lambda ai_object: ai_object==0, K.tensor(batch['o'][:,-1]))), dtype=K.uint8, device=self.device) V = K.zeros((len(batch['o']), 1), dtype=self.dtype, device=self.device) s1 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a1 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, 0:action_space] a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] r = K.tensor(batch['r'], dtype=self.dtype, device=self.device).unsqueeze(1) s1_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, 0:observation_space], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) s2__ = K.cat([K.tensor(batch['o_3'], dtype=self.dtype, device=self.device)[:, observation_space:], K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) ag = K.tensor(batch['ag'], dtype=self.dtype, device=self.device) ag_2 = K.tensor(batch['ag_2'], dtype=self.dtype, device=self.device) ag_3 = K.tensor(batch['ag_3'], dtype=self.dtype, device=self.device) if normalizer[0] is not None: s1 = normalizer[0].preprocess(s1) s1_ = normalizer[0].preprocess(s1_) if normalizer[1] is not None: s2 = normalizer[1].preprocess(s2) s2_ = normalizer[1].preprocess(s2_) s2__ = normalizer[1].preprocess(s2__) a1_ = self.actors_target[0](s1_) a2_ = self.actors_target[1](s2_) #a2_[mask] = self.estimate_obj_action(s2_[mask], s2__[mask]) a2_[mask] = self.estimate_obj_action(ag_2[mask], ag_3[mask]) s = [s1, s2] s_ = [s1_, s2_] # Critics Q = self.critics[i_agent](s[i_agent], K.cat([a1, a2],dim=1)) V = self.critics_target[i_agent](s_[i_agent], K.cat([a1_, a2_],dim=1)).detach() target_Q = (V * self.gamma) + r target_Q = target_Q.clamp(-1./(1.-self.gamma), 0.) loss_critic = self.loss_func(Q, target_Q) self.critics_optim[i_agent].zero_grad() loss_critic.backward() self.critics_optim[i_agent].step() # Actors a1 = self.actors[0](s1) a2 = self.actors[1](s2) #a2_[mask] = self.estimate_obj_action(s2[mask], s2_[mask]) a2[mask] = self.estimate_obj_action(ag[mask], ag_2[mask]) loss_actor = -self.critics[i_agent](s[i_agent], K.cat([a1, a2],dim=1)).mean() if self.regularization: loss_actor += (self.actors[i_agent](s[i_agent])**2).mean()*1 self.actors_optim[i_agent].zero_grad() loss_actor.backward() self.actors_optim[i_agent].step() return loss_critic.item(), loss_actor.item() def update_target(self): soft_update(self.actors_target[0], self.actors[0], self.tau) soft_update(self.critics_target[0], self.critics[0], self.tau) soft_update(self.actors_target[1], self.actors[1], self.tau) soft_update(self.critics_target[1], self.critics[1], self.tau) def estimate_obj_action(self, state2, next_state2): self.backward.eval() with K.no_grad(): action2 = self.backward(state2.to(self.device), next_state2.to(self.device)) self.backward.train() return action2 def update_backward(self, batch, normalizer=None): observation_space = self.observation_space - K.tensor(batch['g'], dtype=self.dtype, device=self.device).shape[1] action_space = self.action_space[0].shape[0] mask = K.tensor(tuple(map(lambda ai_object: ai_object>0, K.tensor(batch['o'][:,-1]))), dtype=K.uint8, device=self.device) #s2 = K.cat([K.tensor(batch['o'], dtype=self.dtype, device=self.device)[:, observation_space:], # K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) a2 = K.tensor(batch['u'], dtype=self.dtype, device=self.device)[:, action_space:] #s2_ = K.cat([K.tensor(batch['o_2'], dtype=self.dtype, device=self.device)[:, observation_space:], # K.tensor(batch['g'], dtype=self.dtype, device=self.device)], dim=-1) #if normalizer[1] is not None: # s2 = normalizer[1].preprocess(s2) # s2_ = normalizer[1].preprocess(s2_) #a2_pred = self.backward(s2[mask], s2_[mask]) ag = K.tensor(batch['ag'], dtype=self.dtype, device=self.device) ag_2 = K.tensor(batch['ag_2'], dtype=self.dtype, device=self.device) a2_pred = self.backward(ag[mask], ag_2[mask]) loss_backward = self.loss_func(a2_pred, a2[mask]) self.backward_optim.zero_grad() loss_backward.backward() #K.nn.utils.clip_grad_norm_(self.forward.parameters(), 0.5) self.backward_optim.step() return loss_backward.item() <file_sep>import numpy as np import scipy as sc import time import imageio import torch as K import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import gym_wmgds as gym from olbr.algorithms.ppo_fine import PPO_BD from olbr.experience import Normalizer from olbr.exploration import Noise from olbr.utils import Saver, Summarizer, get_params, running_mean from olbr.agents.basic import ActorStoch as Actor from olbr.agents.basic import Critic import pdb import matplotlib import matplotlib.pyplot as plt device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 def init(config, agent='robot', her=False, object_Qfunc=None, backward_dyn=None, object_policy=None, reward_fun=None): #hyperparameters ENV_NAME = config['env_id'] SEED = config['random_seed'] N_ENVS = config['n_envs'] env = [] if 'Fetch' in ENV_NAME and 'Multi' in ENV_NAME: for i_env in range(N_ENVS): env.append(gym.make(ENV_NAME, n_objects=config['max_nb_objects'], obj_action_type=config['obj_action_type'], observe_obj_grp=config['observe_obj_grp'], obj_range=config['obj_range'])) n_rob_actions = 4 n_actions = config['max_nb_objects'] * len(config['obj_action_type']) + n_rob_actions elif 'HandManipulate' in ENV_NAME and 'Multi' in ENV_NAME: for i_env in range(N_ENVS): env.append(gym.make(ENV_NAME, obj_action_type=config['obj_action_type'])) n_rob_actions = 20 n_actions = 1 * len(config['obj_action_type']) + n_rob_actions else: for i_env in range(N_ENVS): env.append(gym.make(ENV_NAME)) def her_reward_fun(ag_2, g, info): # vectorized return env[0].compute_reward(achieved_goal=ag_2, desired_goal=g, info=info) for i_env in range(N_ENVS): env[i_env].seed(SEED+10*i_env) K.manual_seed(SEED) np.random.seed(SEED) observation_space = env[0].observation_space.spaces['observation'].shape[1] + env[0].observation_space.spaces['desired_goal'].shape[0] action_space = (gym.spaces.Box(-1., 1., shape=(n_rob_actions,), dtype='float32'), gym.spaces.Box(-1., 1., shape=(n_actions-n_rob_actions,), dtype='float32'), gym.spaces.Box(-1., 1., shape=(n_actions,), dtype='float32')) GAMMA = config['gamma'] TAU = config['tau'] ACTOR_LR = config['plcy_lr'] CRITIC_LR = config['crtc_lr'] MEM_SIZE = config['buffer_length'] REGULARIZATION = config['regularization'] NORMALIZED_REWARDS = config['reward_normalization'] if config['agent_alg'] == 'PPO_BD': MODEL = PPO_BD OUT_FUNC = 'linear' from olbr.replay_buffer import ReplayBuffer from olbr.her_sampler import make_sample_her_transitions from olbr.replay_buffer import RolloutStorage as RolloutStorage #exploration initialization env[0]._max_episode_steps *= config['max_nb_objects'] noise = (True, Noise(action_space[1].shape[0], sigma=0.2, eps=0.3) ) #model initialization optimizer = (optim.Adam, (ACTOR_LR, CRITIC_LR)) # optimiser func, (actor_lr, critic_lr) loss_func = F.mse_loss model = MODEL(observation_space, action_space, optimizer, Actor, Critic, config['clip_param'], config['ppo_epoch'], config['n_batches'], config['value_loss_coef'], config['entropy_coef'], eps=config['eps'], max_grad_norm=config['max_grad_norm'], use_clipped_value_loss=True, out_func=OUT_FUNC, discrete=False, agent_id=0, object_Qfunc=object_Qfunc, backward_dyn=backward_dyn, object_policy=object_policy, reward_fun=reward_fun, masked_with_r=config['masked_with_r']) normalizer = [Normalizer(), Normalizer()] #memory initilization if her: sample_her_transitions = make_sample_her_transitions('future', 4, her_reward_fun) else: sample_her_transitions = make_sample_her_transitions('none', 4, her_reward_fun) buffer_shapes = { 'o' : (env[0]._max_episode_steps, env[0].observation_space.spaces['observation'].shape[1]*2), 'ag' : (env[0]._max_episode_steps, env[0].observation_space.spaces['achieved_goal'].shape[0]), 'g' : (env[0]._max_episode_steps, env[0].observation_space.spaces['desired_goal'].shape[0]), 'u' : (env[0]._max_episode_steps-1, action_space[2].shape[0]) } memory = (RolloutStorage(env[0]._max_episode_steps-1, config['n_rollouts'], (observation_space,), action_space[0]), ReplayBuffer(buffer_shapes, MEM_SIZE, env[0]._max_episode_steps, sample_her_transitions) ) experiment_args = (env, memory, noise, config, normalizer, 0) return model, experiment_args def rollout(env, model, noise, i_env, normalizer=None, render=False, agent_id=0, ai_object=False, rob_policy=[0., 0.]): trajectories = [] for i_agent in range(2): trajectories.append([]) # monitoring variables episode_reward = 0 frames = [] env[i_env].env.ai_object = ai_object env[i_env].env.deactivate_ai_object() state_all = env[i_env].reset() if ai_object: for i_step in range(env[0]._max_episode_steps): model.to_cpu() obs = [K.tensor(obs, dtype=K.float32).unsqueeze(0) for obs in state_all['observation']] goal = K.tensor(state_all['desired_goal'], dtype=K.float32).unsqueeze(0) # Observation normalization obs_goal = [] obs_goal.append(K.cat([obs[0], goal], dim=-1)) if normalizer[0] is not None: obs_goal[0] = normalizer[0].preprocess(obs_goal[0]) value, action, log_probs = model.select_action(obs_goal[0], noise[0]) value = value.cpu().numpy().squeeze(0) action = action.cpu().numpy().squeeze(0) log_probs = log_probs.cpu().numpy().squeeze(0) action_to_env = np.zeros_like(env[0].action_space.sample()) action_to_env[0:action.shape[0]] = action next_state_all, reward, done, info = env[i_env].step(action_to_env) # Move to the next state state_all = next_state_all # Record frames if render: frames.append(env[i_env].render(mode='rgb_array')[0]) env[i_env].env.activate_ai_object() for i_step in range(env[0]._max_episode_steps): model.to_cpu() obs = [K.tensor(obs, dtype=K.float32).unsqueeze(0) for obs in state_all['observation']] goal = K.tensor(state_all['desired_goal'], dtype=K.float32).unsqueeze(0) # Observation normalization obs_goal = [] for i_agent in range(2): obs_goal.append(K.cat([obs[i_agent], goal], dim=-1)) if normalizer[i_agent] is not None: obs_goal[i_agent] = normalizer[i_agent].preprocess_with_update(obs_goal[i_agent]) value, action, log_probs = model.select_action(obs_goal[0], noise[0]) value = value.cpu().numpy().squeeze(0) action = action.cpu().numpy().squeeze(0) log_probs = log_probs.cpu().numpy().squeeze(0) if ai_object: action_to_env = env[0].action_space.sample() * rob_policy[0] + np.ones_like(env[0].action_space.sample()) * rob_policy[1] action_to_env[action.shape[0]::] = model.get_obj_action(obs_goal[1], noise[1]).cpu().numpy().squeeze(0) else: action_to_env = np.zeros_like(env[0].action_space.sample()) action_to_env[0:action.shape[0]] = action next_state_all, reward, done, info = env[i_env].step(action_to_env) if ai_object: for i_agent in range(2): state = { 'observation' : state_all['observation'][i_agent], 'achieved_goal' : state_all['achieved_goal'], 'desired_goal' : state_all['desired_goal'] } next_state = { 'observation' : next_state_all['observation'][i_agent], 'achieved_goal' : next_state_all['achieved_goal'], 'desired_goal' : next_state_all['desired_goal'] } trajectories[i_agent].append((state.copy(), action_to_env, reward, next_state.copy(), done)) else: next_obs = [K.tensor(next_obs, dtype=K.float32).unsqueeze(0) for next_obs in next_state_all['observation']] # Observation normalization next_obs_goal = [] for i_agent in range(2): next_obs_goal.append(K.cat([next_obs[i_agent], goal], dim=-1)) if normalizer[i_agent] is not None: next_obs_goal[i_agent] = normalizer[i_agent].preprocess(next_obs_goal[i_agent]) if model.masked_with_r: reward = model.get_obj_reward(obs_goal[1], next_obs_goal[1]).cpu().numpy().squeeze(0) * np.abs(reward) + (reward) else: reward = model.get_obj_reward(obs_goal[1], next_obs_goal[1]).cpu().numpy().squeeze(0) + (reward) # for monitoring episode_reward += reward for i_agent in range(2): trajectories[i_agent].append((obs_goal[i_agent].cpu().numpy().squeeze(0), action_to_env[0:action.shape[0]], reward, next_obs_goal[i_agent].cpu().numpy().squeeze(0), done, value, log_probs)) # Move to the next state state_all = next_state_all # Record frames if render: frames.append(env[i_env].render(mode='rgb_array')[0]) if ai_object: obs, ags, goals, acts = [], [], [], [] for trajectory in trajectories: obs.append([]) ags.append([]) goals.append([]) acts.append([]) for i_step in range(env[0]._max_episode_steps): obs[-1].append(trajectory[i_step][0]['observation']) ags[-1].append(trajectory[i_step][0]['achieved_goal']) goals[-1].append(trajectory[i_step][0]['desired_goal']) if (i_step < env[0]._max_episode_steps - 1): acts[-1].append(trajectory[i_step][1]) trajectories = { 'o' : np.concatenate(obs,axis=1)[np.newaxis,:], 'ag' : np.asarray(ags)[0:1,], 'g' : np.asarray(goals)[0:1,], 'u' : np.asarray(acts)[0:1,], } else: obs, acts, rews, vals, logs = [], [], [], [], [] for i_step in range(env[0]._max_episode_steps): obs.append(trajectories[0][i_step][0]) vals.append(trajectories[0][i_step][5]) if (i_step < env[0]._max_episode_steps - 1): acts.append(trajectories[0][i_step][1]) rews.append(trajectories[0][i_step][2]) logs.append(trajectories[0][i_step][6]) trajectories = { 'o' : np.asarray(obs)[np.newaxis,:], 'u' : np.asarray(acts)[np.newaxis,:], 'r' : np.asarray(rews)[np.newaxis,:], 'v' : np.asarray(vals)[np.newaxis,:], 'l' : np.asarray(logs)[np.newaxis,:] } return trajectories, episode_reward, info['is_success'], frames def run(model, experiment_args, train=True): total_time_start = time.time() env, memory, noise, config, normalizer, _ = experiment_args N_EPISODES = config['n_episodes'] if train else config['n_episodes_test'] N_CYCLES = config['n_cycles'] N_ROLLOUTS = config['n_rollouts'] N_BATCHES = config['n_batches'] N_BD_BATCHES = config['n_bd_batches'] N_TEST_ROLLOUTS = config['n_test_rollouts'] BATCH_SIZE = config['batch_size'] FT_RATE = config['ai_object_fine_tune_rate'] episode_reward_all = [] episode_success_all = [] episode_reward_mean = [] episode_success_mean = [] critic_losses = [] actor_losses = [] dist_entropies = [] backward_losses = [] for i_episode in range(N_EPISODES): lr = config['plcy_lr'] - (config['plcy_lr'] * (i_episode / float(N_EPISODES))) for param_group in model.optims[0].param_groups: param_group['lr'] = lr episode_time_start = time.time() if train: for i_cycle in range(N_CYCLES): trajectories = None for i_rollout in range(N_ROLLOUTS): # Initialize the environment and state ai_object = 1 if np.random.rand() < config['ai_object_rate'] else 0 i_env = i_rollout % config['n_envs'] render = config['render'] > 0 and i_rollout==0 trajectory, _, _, _ = rollout(env, model, noise, i_env, normalizer, render=render, agent_id=0, ai_object=ai_object, rob_policy=config['rob_policy']) if trajectories is None: trajectories = trajectory.copy() else: for key in trajectories.keys(): trajectories[key] = np.concatenate((trajectories[key], trajectory.copy()[key]), axis=0) memory[0].obs.copy_(K.tensor(np.swapaxes(trajectories['o'], 0, 1), dtype=model.dtype, device=model.device)) memory[0].actions.copy_(K.tensor(np.swapaxes(trajectories['u'], 0, 1), dtype=model.dtype, device=model.device)) memory[0].rewards.copy_(K.tensor(np.swapaxes(trajectories['r'], 0, 1), dtype=model.dtype, device=model.device)) memory[0].value_preds.copy_(K.tensor(np.swapaxes(trajectories['v'], 0, 1), dtype=model.dtype, device=model.device)) memory[0].action_log_probs.copy_(K.tensor(np.swapaxes(trajectories['l'], 0, 1), dtype=model.dtype, device=model.device)) memory[0].compute_returns(config['use_gae'], config['gamma'], config['gae_lambda']) model.to_cuda() memory[0].to(model.device) critic_loss, actor_loss, dist_entropy = model.update(memory[0]) critic_losses.append(critic_loss) actor_losses.append(actor_loss) dist_entropies.append(dist_entropy) if i_cycle%FT_RATE==FT_RATE-1: for i_rollout in range(N_ROLLOUTS): i_env = i_rollout % config['n_envs'] render = config['render'] > 0 and i_rollout==0 trajectories, _, _, _ = rollout(env, model, noise, i_env, normalizer, render=render, agent_id=0, ai_object=True, rob_policy=config['rob_policy']) memory[1].store_episode(trajectories.copy()) for i_batch in range(N_BATCHES): model.to_cuda() batch = memory[1].sample(BATCH_SIZE) _, _ = model.update_object_parameters(batch, normalizer) model.update_object_target() for i_batch in range(N_BD_BATCHES): batch = memory[1].sample(BATCH_SIZE) _ = model.update_backward(batch, normalizer) # <-- end loop: i_cycle plot_durations(np.asarray(critic_losses), np.asarray(critic_losses)) plot_durations(np.asarray(actor_losses), np.asarray(actor_losses)) plot_durations(np.asarray(dist_entropies), np.asarray(dist_entropies)) plot_durations(np.asarray(backward_losses), np.asarray(backward_losses)) episode_reward_cycle = [] episode_succeess_cycle = [] for i_rollout in range(N_TEST_ROLLOUTS): # Initialize the environment and state rollout_per_env = N_TEST_ROLLOUTS // config['n_envs'] i_env = i_rollout // rollout_per_env render = config['render'] > 0 and i_episode % config['render'] == 0 and i_env == 0 _, episode_reward, success, _ = rollout(env, model, (False,False), i_env, normalizer=normalizer, render=render, agent_id=0, ai_object=False, rob_policy=config['rob_policy']) episode_reward_cycle.append(episode_reward.item()) episode_succeess_cycle.append(success) # <-- end loop: i_rollout ### MONITORIRNG ### episode_reward_all.append(episode_reward_cycle) episode_success_all.append(episode_succeess_cycle) episode_reward_mean.append(np.mean(episode_reward_cycle)) episode_success_mean.append(np.mean(episode_succeess_cycle)) plot_durations(np.asarray(episode_reward_mean), np.asarray(episode_success_mean)) if config['verbose'] > 0: # Printing out if (i_episode+1)%1 == 0: print("==> Episode {} of {}".format(i_episode + 1, N_EPISODES)) print(' | Id exp: {}'.format(config['exp_id'])) print(' | Exp description: {}'.format(config['exp_descr'])) print(' | Env: {}'.format(config['env_id'])) print(' | Process pid: {}'.format(config['process_pid'])) print(' | Episode total reward: {}'.format(episode_reward)) print(' | Running mean of total reward: {}'.format(episode_reward_mean[-1])) print(' | Success rate: {}'.format(episode_success_mean[-1])) #print(' | Running mean of total reward: {}'.format(running_mean(episode_reward_all)[-1])) print(' | Time episode: {}'.format(time.time()-episode_time_start)) print(' | Time total: {}'.format(time.time()-total_time_start)) # <-- end loop: i_episode if train: print('Training completed') else: print('Test completed') return episode_reward_all, episode_success_all # set up matplotlib is_ipython = 'inline' in matplotlib.get_backend() if is_ipython: from IPython import display plt.ion() def plot_durations(p, r): plt.figure(2) plt.clf() plt.title('Training...') plt.xlabel('Episode') plt.ylabel('Duration') plt.plot(p) plt.plot(r) plt.pause(0.001) # pause a bit so that plots are updated if is_ipython: display.clear_output(wait=True) display.display(plt.gcf())<file_sep>import numpy as np import scipy as sc import time import imageio import torch as K import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import gym_wmgds as gym from olbr.algorithms import DDPG, HDDPG from olbr.experience import ReplayMemory, Transition from olbr.exploration import Noise from olbr.utils import Saver, Summarizer, get_noise_scale, get_params, running_mean from olbr.agents.basic import Actor from olbr.agents.basic import Critic import pdb device = K.device("cuda" if K.cuda.is_available() else "cpu") dtype = K.float32 def init(config): if config['resume'] != '': resume_path = config['resume'] saver = Saver(config) config, start_episode, save_dict = saver.resume_ckpt() config['resume'] = resume_path else: start_episode = 0 #hyperparameters ENV_NAME = config['env_id'] #'simple_spread' SEED = config['random_seed'] # 1 GAMMA = config['gamma'] # 0.95 TAU = config['tau'] # 0.01 ACTOR_LR = config['plcy_lr'] # 0.01 CRITIC_LR = config['crtc_lr'] # 0.01 MEM_SIZE = config['buffer_length'] # 1000000 REGULARIZATION = config['regularization'] # True NORMALIZED_REWARDS = config['reward_normalization'] # True env = gym.make(ENV_NAME) env.seed(SEED) observation_space = env.observation_space.spaces['observation'].shape[0] + env.observation_space.spaces['desired_goal'].shape[0] #goal_space = gym.spaces.box.Box(low=-1, high=1, shape=(8,), dtype='float32') #goal_space = gym.spaces.box.Box(low=-2, high=2, shape=env.observation_space.spaces['desired_goal'].shape, dtype='float32') goal_space = gym.spaces.box.Box(low=-1, high=1, shape=env.observation_space.spaces['desired_goal'].shape, dtype='float32') action_space = env.action_space if env.action_space.low[0] == -1 and env.action_space.high[0] == 1: OUT_FUNC = K.tanh elif env.action_space.low[0] == 0 and env.action_space.high[0] == 1: OUT_FUNC = K.sigmoid else: OUT_FUNC = K.sigmoid K.manual_seed(SEED) np.random.seed(SEED) MODEL = HDDPG if config['verbose'] > 1: # utils summaries = (Summarizer(config['dir_summary_train'], config['port'], config['resume']), Summarizer(config['dir_summary_test'], config['port'], config['resume'])) saver = Saver(config) else: summaries = None saver = None #exploration initialization noise = (Noise(action_space.shape[0], sigma=0.05, eps=0.2), Noise(goal_space.shape[0], sigma=0.05, eps=0.2)) #noise = OUNoise(action_space.shape[0]) #model initialization optimizer = (optim.Adam, (ACTOR_LR, CRITIC_LR)) # optimiser func, (actor_lr, critic_lr) loss_func = F.mse_loss model = MODEL(observation_space, action_space, goal_space, optimizer, Actor, Critic, loss_func, GAMMA, TAU, out_func=OUT_FUNC, discrete=False, regularization=REGULARIZATION, normalized_rewards=NORMALIZED_REWARDS) if config['resume'] != '': for i, param in enumerate(save_dict['model_params']): model.entities[i].load_state_dict(param) #memory initilization memory = [ReplayMemory(MEM_SIZE), ReplayMemory(MEM_SIZE)] experiment_args = (env, memory, noise, config, summaries, saver, start_episode) return model, experiment_args def rollout(env, model, noise, mask, ratio, mapping, C=25, render=False, sparse_rewards=True): trajectory = [[], []] # monitoring variables episode_reward = [0, 0] frames = [] state = env.reset() success = 0 for i_step in range(env._max_episode_steps): model.to_cpu() obs = K.tensor(state['observation'], dtype=K.float32).unsqueeze(0) goal = K.tensor(state['desired_goal'], dtype=K.float32).unsqueeze(0) obs = K.cat([obs, goal], dim=-1) obs_f = obs*mask obs_s = obs#*(1-mask) if i_step % C == 0: state_init = state.copy() #goal_f = model.select_goal(obs_s, noise[1]) #pdb.set_trace() goal_f = goal #goal_f = goal - obs[:,0:3] #goal_f *= (ratio[0:3]*C*2) #goal_f += obs_s[:,0:3] #pdb.set_trace() #goal_f *= (ratio[K.tensor(mask, dtype=K.uint8)]*C) #goal_f += obs_s[:,K.tensor(mask, dtype=K.uint8)] cumm_reward = K.zeros((1,1), dtype=K.float32) action = model.select_action(K.cat([obs_f, goal_f], dim=-1), noise[0]) next_state, reward, done, info = env.step(action.squeeze(0).numpy()) next_obs = K.tensor(next_state['observation'], dtype=K.float32).unsqueeze(0) #next_goal = K.tensor(next_state['desired_goal'], dtype=K.float32).unsqueeze(0) next_obs = K.cat([next_obs, goal], dim=-1) next_obs_f = next_obs*mask #next_obs_s = next_obs*(1-mask) reward = K.tensor(reward, dtype=K.float32).view(1,1) cumm_reward += reward #old_distance = F.mse_loss(goal_f, mapping(obs_f, mask)).view(1,1) #new_distance = F.mse_loss(goal_f, mapping(next_obs_f, mask)).view(1,1) #old_distance = goal_f - mapping(obs_f, mask) #new_distance = goal_f - mapping(next_obs_f, mask) #old_distance /= (ratio[K.tensor(mask, dtype=K.uint8)]*C) #new_distance /= (ratio[K.tensor(mask, dtype=K.uint8)]*C) #old_distance = K.tensor(np.linalg.norm(old_distance, axis=-1), dtype=K.float32).view(1,1) #new_distance = K.tensor(np.linalg.norm(new_distance, axis=-1), dtype=K.float32).view(1,1) distance = K.tensor(np.linalg.norm(mapping(goal_f) - mapping(next_obs_f), axis=-1), dtype=K.float32).view(1,1) #distance = K.tensor(np.linalg.norm(mapping(goal_f) - 0, axis=-1), dtype=K.float32).view(1,1) success = distance < 0.05 if sparse_rewards: intr_reward = - K.tensor(distance > 0.05, dtype=K.float32) else: intr_reward = old_distance - new_distance #K.sqrt(K.pow((goal_f - mapping(next_obs_f)), 2).sum(-1)) #print(K.sqrt(K.pow((goal_f - mapping(next_obs_f)), 2).sum(-1))) #print(F.mse_loss(goal_f, mapping(next_obs_f)).view(1,1)) # for monitoring episode_reward[0] = episode_reward[0] + intr_reward episode_reward[1] = episode_reward[1] + reward trajectory[0].append((state, action, intr_reward, next_state, goal_f, done)) if (i_step+1) % C == 0: trajectory[1].append((state_init, None, cumm_reward, next_state, goal_f, done)) # Move to the next state state = next_state # Record frames if render: frames.append(env.render(mode='rgb_array')[0]) return trajectory, episode_reward, (success, info['is_success']), frames, # def get_of_mask(env, nb_episodes=400, nb_steps=50, threshold=0.08): # states = [] # actions = [] # for _ in range(nb_episodes): # env.reset() # for _ in range(nb_steps): # action = env.action_space.sample() # state, _, _, _ = env.step(action) # observation = state['observation'] # desired_goal = state['desired_goal'] # state = np.concatenate([observation, desired_goal]) # states.append(state) # actions.append(action) # states = np.asarray(states) # actions = np.asarray(actions) # corr = np.zeros((states.shape[1], actions.shape[1])) # for i in range(states.shape[1]): # for j in range(actions.shape[1]): # corr[i,j] = np.corrcoef(states[:,i], actions[:,j])[0,1] # mask = (K.tensor(abs(corr))>threshold).any(dim=1) # return mask def get_of_mask(env, nb_episodes=400, nb_steps=50, threshold=0.08): states = [] actions = [] for _ in range(nb_episodes): old_state = env.reset() for _ in range(nb_steps): action = env.action_space.sample() new_state, _, _, _ = env.step(action) observation_diff = new_state['observation'] - old_state['observation'] desired_goal_diff = new_state['desired_goal'] - old_state['desired_goal'] state = np.concatenate([observation_diff, desired_goal_diff]) states.append(state) actions.append(action) old_state = new_state.copy() states = np.asarray(states) actions = np.asarray(actions) corr = np.zeros((states.shape[1], actions.shape[1])) for i in range(states.shape[1]): for j in range(actions.shape[1]): corr[i,j] = np.corrcoef(states[:,i], actions[:,j])[0,1] ratio = np.zeros((states.shape[1], actions.shape[1])) for i in range(states.shape[1]): for j in range(actions.shape[1]): ratio[i,j] = np.median(states[:,i]/actions[:,j]) mask = (K.tensor(abs(corr))>threshold).any(dim=1) return K.tensor(mask, dtype=K.float32), K.max(K.tensor(ratio, dtype=K.float32), dim=-1)[0] def mapping(x, mask=None): if mask is None: return x[:,0:3] else: return x[:, K.tensor(mask, dtype=K.uint8)] def run(model, experiment_args, train=True): total_time_start = time.time() env, memory, noise, config, summaries, saver, start_episode = experiment_args start_episode = start_episode if train else 0 NUM_EPISODES = config['n_episodes'] if train else config['n_episodes_test'] EPISODE_LENGTH = env._max_episode_steps #config['episode_length'] if train else config['episode_length_test'] episode_intr_reward_all = [] episode_reward_all = [] episode_intr_success_all = [] episode_success_all = [] mask, ratio = get_of_mask(env, nb_episodes=40) hier_C = 1 sparse_rewards = True for i_episode in range(start_episode, NUM_EPISODES*5): episode_time_start = time.time() #noise.scale = get_noise_scale(i_episode, config) if train: for i_cycle in range(10): trajectories = [] for i_rollout in range(16): # Initialize the environment and state trajectory, _, _, _ = rollout(env, model, noise, mask, ratio, mapping, hier_C, render=0, sparse_rewards=sparse_rewards) trajectories.append(trajectory) for trajectory in trajectories: for i_step in range(len(trajectory[0])): state, action, reward, next_state, goal_f, done = trajectory[0][i_step] obs = K.tensor(state['observation'], dtype=K.float32).unsqueeze(0) goal = K.tensor(state['desired_goal'], dtype=K.float32).unsqueeze(0) obs = K.cat([obs, goal], dim=-1) obs_f = obs*mask next_obs = K.tensor(next_state['observation'], dtype=K.float32).unsqueeze(0) next_obs = K.cat([next_obs, goal], dim=-1) next_obs_f = next_obs*mask next_achieved_f = mapping(next_obs_f) # regular sample obs_goal_f = K.cat([obs_f, goal_f], dim=-1) if done: next_obs_goal_f = None else: next_obs_goal_f = K.cat([next_obs_f, goal_f], dim=-1) memory[0].push(obs_goal_f, action, next_obs_goal_f, reward) # HER sample for _ in range(4): future = np.random.randint(i_step, len(trajectory[0])) _, _, _, next_state, _, _ = trajectory[0][future] aux_goal_f = mapping(K.cat([K.tensor(next_state['observation'], dtype=K.float32).unsqueeze(0), goal], dim=-1)*mask) obs_goal_f = K.cat([obs_f, aux_goal_f], dim=-1)#*(1-mask) if done: next_obs_goal_f = None else: next_obs_goal_f = K.cat([next_obs_f, aux_goal_f], dim=-1)#*(1-mask) reward = env.compute_reward(next_achieved_f, aux_goal_f, None) reward = K.tensor(reward, dtype=dtype).view(1,1) memory[0].push(obs_goal_f, action, next_obs_goal_f, reward) for i_step in range(len(trajectory[1])): state, _, reward, next_state, goal_f, done = trajectory[1][i_step] obs = K.tensor(state['observation'], dtype=K.float32).unsqueeze(0) goal = K.tensor(state['desired_goal'], dtype=K.float32).unsqueeze(0) next_obs = K.tensor(next_state['observation'], dtype=K.float32).unsqueeze(0) next_achieved = K.tensor(next_state['achieved_goal'], dtype=K.float32).unsqueeze(0) # regular sample obs_goal_s = K.cat([obs, goal], dim=-1)#*(1-mask) if done: next_obs_goal_s = None else: next_obs_goal_s = K.cat([next_obs, goal], dim=-1)#*(1-mask) memory[1].push(obs_goal_s, goal_f, next_obs_goal_s, reward) # HER sample for _ in range(4): future = np.random.randint(i_step, len(trajectory[1])) _, _, _, next_state, _, _ = trajectory[1][future] aux_goal = K.tensor(next_state['achieved_goal'], dtype=K.float32).unsqueeze(0) obs_goal_s = K.cat([obs, aux_goal], dim=-1)#*(1-mask) if done: next_obs_goal_s = None else: next_obs_goal_s = K.cat([next_obs, aux_goal], dim=-1)#*(1-mask) reward = env.compute_reward(next_achieved, aux_goal, None) #reward = K.tensor(reward, dtype=dtype).view(1,1)*(hier_C/2) - hier_C/2 reward = K.tensor(reward, dtype=dtype).view(1,1) memory[1].push(obs_goal_s, goal_f, next_obs_goal_s, reward) # <-- end loop: i_step # <-- end loop: i_rollout for _ in range(40): if len(memory[0]) > config['batch_size']-1 and len(memory[1]) > config['batch_size']-1: batch = [] model.to_cuda() batch.append(Transition(*zip(*memory[0].sample(config['batch_size'])))) batch.append(Transition(*zip(*memory[1].sample(config['batch_size'])))) critic_loss, actor_loss = model.update_parameters(batch) # <-- end loop: i_cycle episode_intr_reward_cycle = [] episode_reward_cycle = [] episode_intr_success_cycle = [] episode_succeess_cycle = [] for i_rollout in range(10): # Initialize the environment and state render = config['render'] > 0 and i_episode % config['render'] == 0 _, episode_reward, success, frames = rollout(env, model, noise=(False, False), mask=mask, ratio=ratio, mapping=mapping, C=hier_C, render=render, sparse_rewards=sparse_rewards) # Save gif dir_monitor = config['dir_monitor_train'] if train else config['dir_monitor_test'] if config['render'] > 0 and i_episode % config['render'] == 0: imageio.mimsave('{}/{}.gif'.format(dir_monitor, i_episode), frames) episode_intr_reward_cycle.append(episode_reward[0]) episode_reward_cycle.append(episode_reward[1]) episode_intr_success_cycle.append(success[0]) episode_succeess_cycle.append(success[1]) # <-- end loop: i_rollout ### MONITORIRNG ### episode_intr_reward_all.append(np.mean(episode_intr_reward_cycle)) episode_reward_all.append(np.mean(episode_reward_cycle)) episode_intr_success_all.append(np.mean(episode_intr_success_cycle)) episode_success_all.append(np.mean(episode_succeess_cycle)) if config['verbose'] > 0: # Printing out if (i_episode+1)%1 == 0: print("==> Episode {} of {}".format(i_episode + 1, NUM_EPISODES)) print(' | Id exp: {}'.format(config['exp_id'])) print(' | Exp description: {}'.format(config['exp_descr'])) print(' | Env: {}'.format(config['env_id'])) print(' | Process pid: {}'.format(config['process_pid'])) print(' | Tensorboard port: {}'.format(config['port'])) print(' | Episode total reward: {}'.format(episode_reward)) print(' | Running mean of total reward: {}'.format(episode_reward_all[-1])) print(' | Running mean of total intrinsic reward: {}'.format(episode_intr_reward_all[-1])) print(' | Success rate: {}'.format(episode_success_all[-1])) print(' | Intrinsic success rate: {}'.format(episode_intr_success_all[-1])) #print(' | Running mean of total reward: {}'.format(running_mean(episode_reward_all)[-1])) print(' | Time episode: {}'.format(time.time()-episode_time_start)) print(' | Time total: {}'.format(time.time()-total_time_start)) if config['verbose'] > 0: ep_save = i_episode+1 if (i_episode == NUM_EPISODES-1) else None is_best_save = None is_best_avg_save = None if (not train) or ((np.asarray([ep_save, is_best_save, is_best_avg_save]) == None).sum() == 3): to_save = False else: model.to_cpu() saver.save_checkpoint(save_dict = {'model_params': [entity.state_dict() for entity in model.entities]}, episode = ep_save, is_best = is_best_save, is_best_avg = is_best_avg_save ) to_save = True #if (i_episode+1)%100 == 0: # summary = summaries[0] if train else summaries[1] # summary.update_log(i_episode, # episode_reward, # list(episode_reward.reshape(-1,)), # critic_loss = critic_loss, # actor_loss = actor_loss, # to_save = to_save # ) # <-- end loop: i_episode if train: print('Training completed') else: print('Test completed') return episode_reward_all if __name__ == '__main__': monitor_macddpg_p2 = [] monitor_macddpg_p2_test = [] for i in range(0,5): config = get_params(args=['--exp_id','MACDDPG_P2_120K_'+ str(i+1), '--random_seed', str(i+1), '--agent_alg', 'MACDDPG', '--protocol_type', str(2), '--n_episodes', '120000', '--verbose', '2', ] ) model, experiment_args = init(config) env, memory, ounoise, config, summaries, saver, start_episode = experiment_args tic = time.time() monitor = run(model, experiment_args, train=True) monitor_test = run(model, experiment_args, train=False) toc = time.time() env.close() for summary in summaries: summary.close() monitor_macddpg_p2.append(monitor) monitor_macddpg_p2_test.append(monitor_test) np.save('./monitor_macddpg_p2.npy', monitor_macddpg_p2) np.save('./monitor_macddpg_p2_test.npy', monitor_macddpg_p2_test) print(toc-tic)
a486eb49df2680374aa13e04b653e3cca29faaf9
[ "Markdown", "Python" ]
14
Python
ozcell/olbr
74e45fd7d71493b8fc157f790f80733952f3fda0
ebdd25dc954fcdddf4142edb9c6fde566e1cc7ff
refs/heads/master
<file_sep>package com.obz.obzregistration; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class ActivityRegister extends AppCompatActivity { EditText name,mail,password1,password2; String Mail,Password1,Password2,Name; SQLiteDatabase database; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); mail = findViewById(R.id.mailId); password1 = findViewById(R.id.password1); password2 = findViewById(R.id.password2); name = findViewById(R.id.name); } public void BackPressed(View view) { super.onBackPressed(); } public void Register(View view) { Mail = String.valueOf(mail.getText()); Password1 = String.valueOf(password1.getText()); Password2 = String.valueOf(password2.getText()); Name = String.valueOf(name.getText()); if(!Password2.equals(Password1)){ Toast.makeText(this,"The passwords don't match",Toast.LENGTH_SHORT).show(); password2.setText(""); password1.setText(""); name.setText(Name); mail.setText(Mail); return; } database = this.openOrCreateDatabase("Users",MODE_PRIVATE,null); database.execSQL("CREATE TABLE IF NOT EXISTS Users(name VARCHAR, mail VARCHAR, password VARCHAR)"); database.execSQL("INSERT INTO Users(name, mail, password) VALUES('"+Name+"','"+Mail+"','"+Password1+"'"+")"); Intent intent = new Intent(ActivityRegister.this,ActivityWelcome.class); Mail = Mail.toLowerCase(); intent.putExtra("mail",Mail); startActivity(intent); finish(); } } <file_sep># OBZ_Dev An App for Register and Login
72e8b381e4c75c24ff41ab01ea4c7cb2b4b44cc5
[ "Markdown", "Java" ]
2
Java
ChandanNaik999/OBZ_Dev
34532718727fb1c0c52009258f31ed59e142db38
b632c4d51e609de21e74e6a6731f97dd39fcc4d1
refs/heads/master
<file_sep>package com.badoo.ribs.samples.comms_nodes_1.rib.menu import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams class MenuBuilder( private val dependency: Menu.Dependency ) : SimpleBuilder<Menu>() { override fun build(buildParams: BuildParams<Nothing?>): Menu { val presenter = MenuPresenterImpl() val viewDeps = object : MenuView.Dependency { override val presenter: MenuPresenter = presenter } return MenuNode( buildParams = buildParams, viewFactory = MenuViewImpl.Factory().invoke(deps = viewDeps), plugins = listOf(presenter) ) } } <file_sep>package com.badoo.ribs.example.network import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response /** * Authentication Interceptor * * Intercepts the [Request] and adds the auth headers to work with the [UnsplashApi] */ class AuthInterceptor(accessKey: String) : Interceptor { private val authHeaderValue = "Client-ID $accessKey" companion object { internal const val HEADER_NAME = "Authorization" } override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() .newBuilder() .addHeader(HEADER_NAME, authHeaderValue) .build() return chain.proceed(request) } } <file_sep>package com.badoo.ribs.samples.retained_instance_store.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.BuildContext import com.badoo.ribs.samples.retained_instance_store.R import com.badoo.ribs.samples.retained_instance_store.rib.retained_instance_example.RetainedInstanceExampleBuilder class RootActivity : RibActivity() { override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Rib { return RetainedInstanceExampleBuilder().build(BuildContext.root(savedInstanceState)) } } <file_sep># Tutorials (In progress, check back later for more) ## Before [Base concepts](baseconcepts.md) ## Tutorials 1. [Building and attaching a RIB to integration point](tutorial1/README.md) (~15m) 2. [Adding a child RIB to a parent](tutorial2/README.md) 3. [Satisfying dependencies of a child RIB](tutorial3/README.md) 4. [Communicating with child RIBs](tutorial4/README.md) 5. [Routing](tutorial5/README.md) 6. TODO 7. TODO ## After Best practices <file_sep>package com.badoo.ribs.tutorials.tutorial3.util /** * A very dumb interface for now. */ interface User { fun name(): String companion object { val DUMMY = object : User { override fun name(): String = "Tutorial User" } } } <file_sep>package com.badoo.ribs.portal import com.badoo.ribs.annotation.ExperimentalApi import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.AncestryInfo import io.reactivex.Single @ExperimentalApi interface RxPortal : Portal { fun showDefault(): Single<Rib> fun showInPortal(ancestryInfo: AncestryInfo): Single<Rib> } <file_sep>package com.badoo.ribs.tutorials.tutorial2.rib.hello_world import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.modality.BuildParams class HelloWorldInteractor( buildParams: BuildParams<Nothing?> ) : Interactor<HelloWorld, HelloWorldView>( buildParams = buildParams ) <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector.builder import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) internal annotation class OptionSelectorScope <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.parent import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.routing.transition.handler.TransitionHandler import com.badoo.ribs.samples.transitionanimations.rib.parent.routing.ParentChildBuilders import com.badoo.ribs.samples.transitionanimations.rib.parent.routing.ParentRouter import com.badoo.ribs.samples.transitionanimations.rib.parent.routing.ParentRouter.Configuration import com.badoo.ribs.samples.transitionanimations.rib.parent.routing.ParentTransitionHandler class ParentBuilder : SimpleBuilder<Parent>() { private val builders = ParentChildBuilders() override fun build(buildParams: BuildParams<Nothing?>): Parent { val backStack = backStack(buildParams) val transitionHandler = ParentTransitionHandler() val router = router(buildParams, backStack, transitionHandler) val presenter = presenter(backStack) val viewDependency = object : ParentView.Dependency { override val presenter: ParentPresenter = presenter } return node(buildParams, viewDependency, router) } private fun backStack(buildParams: BuildParams<Nothing?>): BackStack<Configuration> = BackStack( buildParams = buildParams, initialConfiguration = Configuration.Child1 ) private fun router( buildParams: BuildParams<Nothing?>, backStack: BackStack<Configuration>, transitionHandler: TransitionHandler<Configuration> ): ParentRouter = ParentRouter( buildParams = buildParams, routingSource = backStack, builders = builders, transitionHandler = transitionHandler ) private fun presenter(backStack: BackStack<Configuration>): ParentPresenterImpl = ParentPresenterImpl(backStack) private fun node( buildParams: BuildParams<Nothing?>, viewDependency: ParentView.Dependency, router: ParentRouter ) = ParentNode( buildParams = buildParams, viewFactory = ParentViewImpl.Factory().invoke(viewDependency), plugins = listOfNotNull( router ) ) } <file_sep>package com.badoo.ribs.samples.back_stack.rib.child_c import com.badoo.ribs.core.Rib interface ChildC : Rib { interface Dependency } <file_sep># Tutorial #4 ## The goal of this tutorial To cover how to implement proper `Input` / `Output` communication with child RIBs. ## Outline Every RIB can potentially expose a set of `Inputs` and `Outputs` on its main interface. This is the public API of the RIB, and every RIB guarantees that as long as the proper dependencies are supplied (i.e. a consumer of its `Output` that it can talk to / a source of its `Input` that it can observe), it will automatically wire the required setup internally. Which is an amazing thing when you think about it: 1. When using a RIB, it's not necessary to look inside and understand its internals to make it work, it's enough to have a look at its public API 2. It's also not necessary to create *any* additional wiring or setup to make it work: if you can build it, it works! ## Outputs There's one thing we left out so far: in **tutorial2** we removed the functionality of the **Say hello!** button, and we said we'd put it back later. Now's the time! The classes in this tutorial have all the removed pieces put back in: - `HelloWorld` interface (`Output` and dependency for it) - `HelloWorldModule` - uses `output` when constructing Interactor - `HelloWorldInteractor` - constructor parameter, and using `output` in `onViewCreated` - `ViewEventToOutput` in the `hello_world.mapper` package This means that as far as `HelloWorld` RIB is concerned, when its button is pressed, it will correctly trigger `Output.HelloThere` on its output channel. Now of course we need to provide the dependency for consuming this `Output` from `GreetingsContainer`. This will be similar to what we did in the previous tutorial - we will satisfy it in the parent, directly. More specifically, as `Outputs` and `Inputs` are forms of communication with a RIB, they should be handled as part of the business logic. Which means, we will want to implement it in the parent `Interactor`. Let's open `GreetingsContainerInteractor` and implement reacting to its child's `Output`. What to do with its `Output` actually? Well, `GreetingsContainer` has its own `Output` that it communicates to the outside world, so right now we will make it trigger just that. ```kotlin // mind the correct imports: import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld import android.os.Bundle class GreetingsContainerInteractor( savedInstanceState: Bundle?, router: Router<Configuration, Nothing, Configuration, Nothing, Nothing>, output: Consumer<GreetingsContainer.Output> ) : Interactor<Configuration, Configuration, Nothing, Nothing>( savedInstanceState = savedInstanceState, router = router ) { internal val helloWorldOutputConsumer: Consumer<HelloWorld.Output> = Consumer { when (it) { HelloThere -> output.accept(GreetingsSaid("Someone said hello!")) } } } ``` Now let's tell Dagger to use this! Scroll to the bottom of `GreetingsContainerModule` and replace the `TODO()` block you find there to the object we created: ```kotlin @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldOutputConsumer( interactor: GreetingsContainerInteractor ) : Consumer<HelloWorld.Output> = interactor.helloWorldOutputConsumer ``` "If you can give me `GreetingsContainerInteractor`, I know how to give you a `Consumer<HelloWorld.Output>`". And since `GreetingsContainerInteractor` was marked with `@GreetingsContainerScope` in the same DI configuration (check the method named `interactor`), it's treated as a singleton in the scope, making `Dagger` reuse the same exact instance of it when constructing this `Consumer`, instead of creating a new one. Now we've established a chain: `HelloWorldView` =(`Event`)⇒ `ViewEventToOutput` =(`HelloWorld.Output`)⇒ `GreetingsContainerInteractor` =(`GreetingsContainer.Output`)⇒ `RootActivity` The **tutorial4** app should build and run at this point, and display the Snackbar when the button is pressed. ## Inputs Let's say we want to update the text on the button from outside of the RIB. To expose this functionality, let's add an `Input` to `HelloWorld`: ```kotlin interface HelloWorld : Rib { interface Dependency { fun helloWorldInput(): ObservableSource<Input> // add this fun helloWorldOutput(): Consumer<Output> // remainder omitted } // add this sealed class Input { data class UpdateButtonText(val text: Text): Input() } sealed class Output { object HelloThere : Output() } // remainder omitted } ``` Note that we added a new dependency, too, on `ObservableSource<Input>`. > Reminder – as we've established in **tutorial1**: > - if a RIB has `Input`, then it also has a dependency of > `ObservableSource<Input>` > - if a RIB has `Output`, then it also has a dependency of `Consumer<Output>` > > This is so that we can implement the guaranteed auto-wiring functionality of the RIB, described in the **Outline** section at the beginning of this tutorial Let's use this input - add it to the constructor of our `Interactor` inside `HelloWorldModule`: ```kotlin @HelloWorldScope @Provides @JvmStatic internal fun interactor( savedInstanceState: Bundle?, user: User, config: HelloWorld.Config, input: ObservableSource<HelloWorld.Input>, // add this output: Consumer<HelloWorld.Output> ): HelloWorldInteractor = HelloWorldInteractor( savedInstanceState = savedInstanceState, user = user, config = config, input = input, // add this output = output ) ``` And: ```kotlin class HelloWorldInteractor( savedInstanceState: Bundle?, private val user: User, private val config: HelloWorld.Config, private val input: ObservableSource<HelloWorld.Input>, // add this private val output: Consumer<HelloWorld.Output> ) ``` Now let's implement the functionality on the other end, before connecting the dots. If we want to change the label of the button, we need to go to the view: ```kotlin interface HelloWorldView : RibView, ObservableSource<Event>, Consumer<ViewModel> { sealed class Event { object ButtonClicked : Event() } data class ViewModel( val titleText: Text, val welcomeText: Text, val buttonText: Text // add this ) } ``` And in `HelloWorldViewImpl`: ```kotlin override fun accept(vm: ViewModel) { title.text = vm.titleText.resolve(androidView.context) welcome.text = vm.welcomeText.resolve(androidView.context) button.text = vm.buttonText.resolve(androidView.context) // add this } ``` Now we need to update providing a `ViewModel` from the `Interactor`. We can easily modify the initial one by adding the last line: ```kotlin view.accept( HelloWorldView.ViewModel( titleText = Text.Resource(R.string.hello_world_title, user.name()), welcomeText = config.welcomeMessage, buttonText = Text.Resource(R.string.hello_world_button_text) ) ) ``` But this will only create one, and never update it - and we want to do just that, whenever an `Input.UpdateButtonText` arrives. We can use the `Binder` for that, similarly to how we already use it just a couple lines below the `ViewModel` creation: ```kotlin viewLifecycle.startStop { bind(view to output using ViewEventToOutput) } ``` To outline what we want to do, add a new line here: ```kotlin viewLifecycle.startStop { bind(view to output using ViewEventToOutput) bind(input to view using InputToViewModel) } ``` Create `InputToViewModel` in the `mapper` package: ```kotlin package com.badoo.ribs.tutorials.tutorial4.rib.hello_world.mapper import com.badoo.ribs.android.text.Text import com.badoo.ribs.tutorials.tutorial4.R import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.HelloWorld.Input.UpdateButtonText import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.HelloWorldView.ViewModel import com.badoo.ribs.tutorials.tutorial4.util.User class InputToViewModel( private val user: User, private val config: HelloWorld.Config ) : (HelloWorld.Input) -> ViewModel? { override fun invoke(input: HelloWorld.Input): ViewModel? = when (input) { is UpdateButtonText -> ViewModel( titleText = Text.Resource(R.string.hello_world_title, user.name()), welcomeText = config.welcomeMessage, buttonText = input.text // using the incoming data ) } } ``` Two things worth mentioning here: 1. Notice how the return type is nullable: `ViewModel?` – meaning we don't have to create one if we don't want to. A legitimate use-case is if in the future we decide to add more types of `Input`, and not all of them actually do something with the view – in those branches in the `when` expression we can just return `null`, and `Binder` will not propagate it to the view. 2. Notice that we actually needed to pass `user` and `config` here, so it can no longer be just a Kotlin object. Modify our `Interactor` to create it: ```kotlin // create the transformer private val inputToViewModel = InputToViewModel(user, config) override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) setInitialViewModel(view) viewLifecycle.startStop { bind(view to output using ViewEventToOutput) bind(input to view using inputToViewModel) // use it here } } // extracted this to a method too private fun setInitialViewModel(view: HelloWorldView) { view.accept( HelloWorldView.ViewModel( titleText = Text.Resource(R.string.hello_world_title, user.name()), welcomeText = config.welcomeMessage, buttonText = Text.Resource(R.string.hello_world_button_text) ) ) } ``` > Alternatively, we could create the transformer in our DI module and pass it in the constructor (then we could spare passing in `user` and `config`). Since we don't need it outside of the `Interactor`, and since it's just a simple mapper (it's not like we'd want to mock it), it's also ok to keep it here. Up to you I guess. ## Test run Right now, we only implemented the functionality to react to exposed `Input` type on the `HelloWorld` side of things. Now we also need to satisfy the dependency of `ObservableSource<Input>` in the parent, which we will do similarly to how we did with `Output` before: ```kotlin class GreetingsContainerInteractor( savedInstanceState: Bundle?, router: Router<Configuration, Nothing, Configuration, Nothing, Nothing>, output: Consumer<GreetingsContainer.Output> ) : Interactor<Configuration, Configuration, Nothing, Nothing>( savedInstanceState = savedInstanceState, router = router ) { // Add this: internal val helloWorldInputSource: Relay<HelloWorld.Input> = BehaviorRelay.create() internal val helloWorldOutputConsumer: Consumer<HelloWorld.Output> = Consumer { when (it) { HelloThere -> output.accept(GreetingsSaid("Someone said hello")) } } // Add this to send an Input immediately when this RIB attaches override fun onAttach(ribLifecycle: Lifecycle, savedInstanceState: Bundle?) { super.onAttach(ribLifecycle, savedInstanceState) helloWorldInputSource.accept( HelloWorld.Input.UpdateButtonText( Text.Plain("Woo hoo!") ) ) } } ``` > Right now we will only provide an `Input` statically and once. We will make it more useful in the next tutorial. And add it to the bottom of `GreetingsContainerModule` so that Dagger understands to grab this when providing `HelloWorld.Dependency`: ```kotlin @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldInputSource( interactor: GreetingsContainerInteractor ) : ObservableSource<HelloWorld.Input> = interactor.helloWorldInputSource ``` Now we've established a chain: `GreetingsContainerInteractor` =(`HelloWorld.Input`)⇒`Relay`⇒`InputToViewModel` =(`ViewModel`)⇒ `HelloWorldView` The app should now compile. Test it! ![](https://i.imgur.com/ISU6yZU.png) ## Tutorial complete Congratulations! You can advance to the next one. ## Summary **`Inputs` and `Outputs`** - `Inputs` and `Outputs` are forms of communication with a RIB: - `Inputs` expose functionality that can be triggered from the outside - `Outputs` signal some events where deciding what to do lies beyond the responsibility of the RIB in question - Paired dependencies: - `Inputs` always come with a dependency of `ObservableSource<Input>`. - `Outputs` always come with a dependency of `Consumer<Output>`. - This is to ensure auto-wiring of the RIB, so that as long as you can build it, it works automatically. - When satisfying `Output` and `Input` dependencies, we **always** want to do that directly in the parent: - By satisfying these dependencies, we create a connection between the place where we satisfy them and the RIB in question. - Having a certain RIB as a child is an implementation detail of the parent, that should be kept hidden to maintain flexibility. - If we were to bubble up the dependency to a higher level, we would expose this implementation detail. We would create a connection between the outside world and the implementation detail, making the immediate parent lose its ability to easily change it. This should be avoided at all costs. - If the parent cannot handle an `Output` message directly, it can transform it to its own `Output` type, keeping the implementation detail hidden. <file_sep>package com.badoo.ribs.samples.buildtime.rib.build_time_deps import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.samples.buildtime.rib.build_time_deps.BuildTimeDepsRouter.Configuration import com.badoo.ribs.samples.buildtime.rib.profile.ProfileBuilder class BuildTimeDepsBuilder : SimpleBuilder<BuildTimeDeps>() { override fun build(buildParams: BuildParams<Nothing?>): BuildTimeDeps { val backStack: BackStack<Configuration> = BackStack( initialConfiguration = Configuration.Default, buildParams = buildParams ) val presenter = BuildTimeDepsPresenterImpl( backStack = backStack ) val router = BuildTimeDepsRouter( buildParams = buildParams, routingSource = backStack, profileBuilder = ProfileBuilder() ) val viewDependencies = object : BuildTimeDepsView.Dependency { override val presenter: BuildTimeDepsPresenter = presenter } return BuildTimeDepsNode( buildParams = buildParams, viewFactory = BuildTimeDepsViewImpl.Factory().invoke(deps = viewDependencies), plugins = listOf(presenter, router) ) } } <file_sep>// Use the .github folder as a way to find the root directory. // Without this, the plugins module will not be able to use this script without hacks. File rootDirectory = rootDir while (!rootDirectory.listFiles().any { it.isDirectory() && it.name == ".github" }) { rootDirectory = rootDirectory.parentFile } def props = new Properties() def propsFile = file("$rootDirectory/local.properties") boolean useCompose = false if (propsFile.exists()) { propsFile.withInputStream { props.load(it) } useCompose = Boolean.parseBoolean(props.getProperty("useCompose").toString()) } if (hasProperty("useCompose")) { useCompose = Boolean.parseBoolean(getProperty("useCompose").toString()) } ext.useCompose = useCompose <file_sep>package com.badoo.ribs.samples.transitionanimations.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.BuildContext.Companion.root import com.badoo.ribs.samples.transitionanimations.R import com.badoo.ribs.samples.transitionanimations.rib.parent.ParentBuilder class RootActivity : RibActivity() { override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Rib = ParentBuilder().build(buildContext = root(savedInstanceState)) } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2 import androidx.lifecycle.Lifecycle import com.badoo.ribs.core.plugin.ViewAware internal class SimpleRoutingChild2Presenter : ViewAware<SimpleRoutingChild2View> { override fun onViewCreated(view: SimpleRoutingChild2View, viewLifecycle: Lifecycle) { view.showInitialMessage() } } <file_sep>package com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.GreetingsContainer import dagger.BindsInstance @GreetingsContainerScope @dagger.Component( modules = [GreetingsContainerModule::class], dependencies = [GreetingsContainer.Dependency::class] ) internal interface GreetingsContainerComponent { @dagger.Component.Factory interface Factory { fun create( dependency: GreetingsContainer.Dependency, @BindsInstance buildParams: BuildParams<Nothing?> ): GreetingsContainerComponent } fun node(): Node<Nothing> } <file_sep>package com.badoo.ribs.tutorials.tutorial1.rib.hello_world.builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorld.Output import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorldInteractor import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorldView import dagger.Provides import io.reactivex.functions.Consumer @dagger.Module internal object HelloWorldModule { @HelloWorldScope @Provides @JvmStatic internal fun interactor( buildParams: BuildParams<Nothing?>, output: Consumer<Output> ): HelloWorldInteractor = HelloWorldInteractor( buildParams = buildParams, output = output ) @HelloWorldScope @Provides @JvmStatic internal fun node( buildParams: BuildParams<Nothing?>, customisation: HelloWorld.Customisation, interactor: HelloWorldInteractor ) : Node<HelloWorldView> = Node( buildParams = buildParams, viewFactory = customisation.viewFactory(null), plugins = listOf(interactor) ) } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2 import com.badoo.ribs.core.Rib import com.badoo.ribs.core.customisation.RibCustomisation interface SimpleRoutingChild1Child2 : Rib { interface Dependency class Customisation( val viewFactory: SimpleRoutingChild1Child2View.Factory = SimpleRoutingChild1Child2ViewImpl.Factory() ) : RibCustomisation } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1 import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.core.plugin.Plugin import com.badoo.ribs.core.view.ViewFactory internal class SimpleRoutingChild1Node( buildParams: BuildParams<*>, viewFactory: ViewFactory<SimpleRoutingChild1View>?, plugins: List<Plugin> ) : Node<SimpleRoutingChild1View>( buildParams = buildParams, viewFactory = viewFactory, plugins = plugins ), SimpleRoutingChild1 <file_sep># Tutorial #2 ## The goal of this tutorial To add a child RIB to another RIB ## Outline Building on top of what we achieved in **tutorial1**, we have our `HelloWorld` RIB with its single button. So far, we directly attached it to our integration point, `RootActivity`, but now we want to see an example how to add it as a child RIB of another. ## Viewless RIBs In the framework, individual RIBs are not forced to implement a view, they can also be purely business logic driven. In this case, they only add a `Node` to the `Node` tree, but no `View` to the View tree. Of course, they can do everything else, and can have child RIBs all the same. If these children have their own `Views`, those will be attached directly to the `View` of the closest parent up in the tree that has one. ## Starting out Check the `com.badoo.ribs.tutorials.tutorial2.rib` package in the `tutorial2` module, you now see two RIBs: `HelloWorld`, and `GreetingsContainer`, the new one. If you check `RootActivity`, it builds and attaches `GreetingsContainer` directly, and `HelloWorld` is not used anywhere (yet). The project should compile without any changes, and if you launch the app, this is what you should see: ![Empty greetings container](https://i.imgur.com/4XmUpqF.png) Not too much to see here yet. `GreetingsContainer` is a viewless container RIB, so it does not add anything to the screen. We will add functionality to it in later tutorials, right now the only thing we want to do is to attach `HelloWorld` to it as its child. To do that, first we need to familiarise ourselves with the concept of routing. ## Routing Parent - child relationships and their dynamic changes are described under the concept of routing. In case of Badoo RIBs, routing is done via these steps: 1. define the set of possible configurations a certain RIB can be in 2. define what a certain configuration means, by resolving it to a routing action 3. set the initial configuration for the Router 4. *(dynamically manipulate the Router to set it into any of the pre-defined configurations, based on business logic - in later tutorials)* ## What is a configuration? A configuration is just a label used to describe the routing state. For example, imagine a `Root` RIB, which, on a very basic level, can have two possible subtrees attached: one if the user is logged out, and another if the user is logged in. But not both at the same time! In this case, `LoggedOut` and `LoggedIn` would be the two possible configurations, which we could define as a Kotlin sealed class: ```kotlin sealed class Configuration : Parcelable { @Parcelize object LoggedOut : Configuration() @Parcelize object LoggedIn : Configuration() } ``` > ⚠️ Note how it implements `Parcelable`, so that the framework can save/restore our configurations later. ## What is a routing action? Once we defined our possible configurations, we need to say *what* should happen when any of them is activated. This is done by implementing the `resolveConfiguration` method in the `Router`: ```kotlin abstract fun resolveConfiguration(configuration: C): RoutingAction ``` The library offers implementations of the `RoutingAction` interface, which should cover all cases you encounter. For simplicity, we will now only look at one of them: the `AttachRibRoutingAction`, which, as the name implies, tells the `Router` to attach a certain child RIB. ## Getting our hands dirty Let's have a look at routing for the `GreetingsContainer`: ```kotlin class GreetingsContainerRouter( savedInstanceState: Bundle? ): Router</* ... */>( savedInstanceState = savedInstanceState, initialConfiguration = Configuration.Default ) { sealed class Configuration : Parcelable { @Parcelize object Default : Configuration() } override fun resolve(routing: RoutingElement<Configuration>): RoutingAction = RoutingAction.noop() } ``` This looks pretty basic: 1. The possible set of configurations contain only one: `Default` 2. `GreetingsContainerRouter` passes in `Configuration.Default` as `initialConfiguration` in the parent constructor. All `Routers` need to state their initial configurations. 3. When resolving configurations, we always return `noop()` as a `RoutingAction`, doing nothing Let's spice it up a bit! First, rename `Default` to describe what we actually want to do: ```kotlin sealed class Configuration : Parcelable { @Parcelize object HelloWorld : Configuration() } ``` Next, change the resolution so that it attaches something: ```kotlin import com.badoo.ribs.routing.action.AttachRibRoutingAction.Companion.attach /* ... */ override fun resolve(routing: RoutingElement<Configuration>): RoutingAction = when (routing.configuration) { is Configuration.HelloWorld -> child { TODO() } } ``` > ⚠️ Notice how `AttachRibRoutingAction` also offers a convenience method `attach` to construct it, for which you can use static imports. The same goes for other `RoutingActions`, too. > ⚠️ Also notice that even though `Configuration.HelloWorld` is a Kotlin object, there's still an `is` for it in the `when` expression. This is actually important, since after save/restore cycle, the instance restored from `Bundle` will be a different instance! Without using `is`, the `when` expression will not match in that case. Alright, but what to put in place of the `TODO()` statement? Looking at the signature of the `attach` method it needs a lambda that can build another `Node` given a nullable `Bundle` (representing `savedInstanceState`): ```kotlin fun attach(builder: (Bundle?) -> Node<*>): RoutingAction ``` ## We need a Builder To build the `HelloWorld` RIB, we need an instance its Builder: `HelloWorldBuilder`, just as we did in **tutorial1**. So first just add it as a constructor dependency to our Router: ```kotlin class GreetingsContainerRouter( private val helloWorldBuilder: HelloWorldBuilder ) /* rest is the same */ ``` We'll care about how to pass it here just in a moment, but first let's finish our job here, and replace the `TODO()` block in our `attach` block: ```kotlin override fun resolve(routing: RoutingElement<Configuration>): RoutingAction = when (routing.configuration) { is Configuration.HelloWorld -> child { helloWorldBuilder.build(it) } } ``` Our job is done here in the `GreetingsContainerRouter`, let's see how we can provide the Builder we need. ## The dependency chain Badoo RIBs relies on Dagger2 to provide dependencies. In the `builder` subpackage, let's open `GreetingsContainerModule`, and notice how the first method constructs the Router: ```kotlin @GreetingsContainerScope @Provides @JvmStatic internal fun router( // pass component to child rib builders, or remove if there are none component: GreetingsContainerComponent ): GreetingsContainerRouter = GreetingsContainerRouter() ``` Notice how the constructor invocation has a compilation error now, since we don't yet pass in the required dependency. Let's do that, and change the constructor invocation to: ```kotlin GreetingsContainerRouter( helloWorldBuilder = HelloWorldBuilder() ) ``` Now it's the `HelloWorldBuilder()` part that's missing something. If we open it up, we get a reminder that in order to construct it, we need to satisfy the `HelloWorld` RIB's dependencies. Notice how the function has an unused parameter we can use: ```kotlin internal fun router( // pass component to child rib builders, or remove if there are none component: GreetingsContainerComponent ) ``` Let's do that! ```kotlin GreetingsContainerRouter( helloWorldBuilder = HelloWorldBuilder(component) ) ``` Notice the compilation error again: ![](https://imgur.com/0Kk27dp.png) That's fine and expected! We need to make the connection and say that `HelloWorldComponent` should actually provide those dependencies: ![](https://i.imgur.com/yyJklDY.png) > For simplicity, we removed all actual dependencies from `HelloWorld.Dependency` interface, so that we can attach it as easily as possible. > > Don't worry, we will add it back in the next tutorial! ## Test run! The application should now compile, and launching it, this is what we should see: ![](https://i.imgur.com/iuarP6N.png) It's not very different from what we've seen in **tutorial1**, but now it's added as a child RIB of `GreetingsContainer`. > Note that because we removed the `Consumer<Output>` dependency from `HelloWorld`, the button now doesn't do anything when pressed. We'll fix that soon! ## 🎉 🎉 🎉 Congratulations 🎉 🎉 🎉 You can advance to the next tutorial! ## Summary Steps to add a child RIB: 1. Go to Router 1. Define configuration 2. Resolve configuration to `child { childBuilder.build(it) }` routing action 3. Define `childBuilder` as a constructor dependency 2. Go to Dagger module 1. When constructing the `Router`, create and pass in an instance of the required child `Builder` 2. Add `component` as a parameter to `Builder` constructor 3. Let our component extend the required `Dependency` interface 4. *(Actually satisfy those dependencies - coming up in next tutorial)* <file_sep>package com.badoo.ribs.tutorials.tutorial1.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Node import com.badoo.ribs.tutorials.tutorial1.R /** The tutorial app's single activity */ class RootActivity : RibActivity() { override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Node<*> = TODO("Create HelloWorldBuilder, supply dependencies in constructor, return built Node") } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.hello_world import androidx.lifecycle.Lifecycle import com.badoo.mvicore.android.lifecycle.startStop import com.badoo.mvicore.binder.using import com.badoo.ribs.android.text.Text import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.R import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld.Config import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld.Input import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld.Output import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorldView.Event import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorldView.ViewModel import com.badoo.ribs.tutorials.tutorial5.util.User import io.reactivex.ObservableSource import io.reactivex.functions.Consumer class HelloWorldInteractor( private val user: User, private val config: Config, private val input: ObservableSource<Input>, private val output: Consumer<Output>, buildParams: BuildParams<Nothing?> ) : Interactor<HelloWorld, HelloWorldView>( buildParams = buildParams ) { private var currentButtonText = config.buttonText private val initialViewModel = viewModel(currentButtonText) private val inputToViewModel = { input: Input -> when (input) { is Input.UpdateButtonText -> { viewModel(input.text.also { currentButtonText = it }) } } } private fun viewModel(buttonText: Text): ViewModel { return ViewModel( titleText = Text.Resource(R.string.hello_world_title, user.name()), welcomeText = config.welcomeMessage, buttonText = buttonText ) } private val viewEventToOutput = { event: Event -> when (event) { Event.HelloButtonClicked -> Output.HelloThere(currentButtonText) } } override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) view.accept(initialViewModel) viewLifecycle.startStop { bind(view to output using viewEventToOutput) bind(input to view using inputToViewModel) } } } <file_sep>package com.badoo.ribs.minimal.state import io.reactivex.observers.TestObserver import org.junit.Test class StoreTest { @Test fun `store emits initial state on observe`() { val store = object : Store<Int>(0) { } val testObserver = TestObserver<Int>() store.observe { testObserver.onNext(it) } testObserver.assertValue(0) } @Test fun `store emits latest state on observe`() { val store = object : Store<Int>(0) { fun next() { emit(state + 1) } } val testObserver = TestObserver<Int>() store.next() store.observe { testObserver.onNext(it) } testObserver.assertValue(1) } @Test fun `observer receives state updates`() { val store = object : Store<Int>(0) { fun next() { emit(state + 1) } } val testObserver = TestObserver<Int>() store.observe { testObserver.onNext(it) } store.next() testObserver.assertValues(0, 1) } @Test fun `observer does not receive values after cancel`() { val store = object : Store<Int>(0) { fun next() { emit(state + 1) } } val testObserver = TestObserver<Int>() val cancellable = store.observe { testObserver.onNext(it) } cancellable.cancel() store.next() testObserver.assertValues(0) } @Test fun `async store can emit multiple values through events`() { val store = object : AsyncStore<Int, String>("") { override fun reduceEvent(event: Int, state: String): String = state + event fun trigger() { emitEvent(1) emitEvent(2) } } val testObserver = TestObserver<String>() store.observe { testObserver.onNext(it) } store.trigger() testObserver.assertValues("", "1", "12") } } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_parent.routing import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.builder.SimpleRoutingChild1Builder import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.builder.SimpleRoutingChild2Builder import com.badoo.ribs.samples.simplerouting.rib.simple_routing_parent.SimpleRoutingParent internal open class SimpleRoutingParentChildBuilders( dependency: SimpleRoutingParent.Dependency ) { private val subtreeDeps = SubtreeDependency(dependency) val child1: SimpleRoutingChild1Builder = SimpleRoutingChild1Builder(subtreeDeps) val child2: SimpleRoutingChild2Builder = SimpleRoutingChild2Builder(subtreeDeps) class SubtreeDependency( dependency: SimpleRoutingParent.Dependency ) : SimpleRoutingParent.Dependency by dependency, SimpleRoutingChild1.Dependency, SimpleRoutingChild2.Dependency { override val title: String = "Child 1 title" } } <file_sep>package com.badoo.ribs import android.os.Bundle import android.view.ViewGroup import com.badoo.common.rib.test.activity.R import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Rib class RibTestActivity : RibActivity() { override val rootViewGroup: ViewGroup get() = findViewById(android.R.id.content) override fun createRib(savedInstanceState: Bundle?): Rib = ribFactory!!(this, savedInstanceState) override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } companion object { var ribFactory: ((RibTestActivity, Bundle?) -> Rib)? = null } } <file_sep>package com.badoo.ribs.tutorials.tutorial4.rib.greetings_container.builder import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) internal annotation class GreetingsContainerScope <file_sep>package com.badoo.ribs.tutorials.tutorial2.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildContext.Companion.root import com.badoo.ribs.tutorials.tutorial2.R import com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.GreetingsContainer import com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.builder.GreetingsContainerBuilder import com.google.android.material.snackbar.Snackbar import io.reactivex.functions.Consumer /** The tutorial app's single activity */ class RootActivity : RibActivity() { override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Node<*> = GreetingsContainerBuilder( object : GreetingsContainer.Dependency { override fun greetingsContainerOutput(): Consumer<GreetingsContainer.Output> = Consumer { output -> when (output) { is GreetingsContainer.Output.GreetingsSaid -> { Snackbar.make(rootViewGroup, output.greeting, Snackbar.LENGTH_SHORT).show() } } } } ).build( buildContext = root( savedInstanceState = savedInstanceState ) ) } <file_sep>package com.badoo.ribs.sandbox.rib.compose_parent import android.view.ViewGroup import com.badoo.ribs.core.customisation.inflate import com.badoo.ribs.core.view.AndroidRibView import com.badoo.ribs.core.view.RibView import com.badoo.ribs.core.view.ViewFactory import com.badoo.ribs.core.view.ViewFactoryBuilder import com.badoo.ribs.sandbox.compose.R interface ComposeParentView : RibView { interface Factory : ViewFactoryBuilder<Nothing?, ComposeParentView> } class ComposeParentViewImpl private constructor( override val androidView: ViewGroup ) : AndroidRibView(), ComposeParentView { class Factory : ComposeParentView.Factory { override fun invoke(deps: Nothing?): ViewFactory<ComposeParentView> = ViewFactory { ComposeParentViewImpl( it.inflate(R.layout.rib_compose_parent) ) } } } <file_sep>package com.badoo.ribs.core.lifecycle import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.State import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import org.junit.Assert.assertEquals import org.junit.Test class MinimumCombinedLifecycleTest { @Test fun `completely duplicates state of single lifecycle`() { val test = TestLifecycle() val combined = MinimumCombinedLifecycle(test.lifecycle) STATES.forEach { if (it != State.INITIALIZED) { test.state = it } assertEquals(it, combined.lifecycle.currentState) } } @Test fun `completely duplicates state of lifecycles with same state`() { val test1 = TestLifecycle() val test2 = TestLifecycle() val combined = MinimumCombinedLifecycle(test1.lifecycle, test2.lifecycle) STATES.forEach { if (it != State.INITIALIZED) { test1.state = it test2.state = it } assertEquals(it, combined.lifecycle.currentState) } } @Test fun `destroyed when one of lifecycles is destroyed`() { val test1 = TestLifecycle() test1.state = State.DESTROYED val test2 = TestLifecycle() val combined = MinimumCombinedLifecycle(test1.lifecycle, test2.lifecycle) assertEquals(State.DESTROYED, combined.lifecycle.currentState) } private class TestLifecycle : LifecycleOwner { private val registry = LifecycleRegistry(this) var state: State get() = registry.currentState set(value) { registry.currentState = value } override fun getLifecycle(): Lifecycle = registry } companion object { val STATES = listOf(State.INITIALIZED, State.CREATED, State.STARTED, State.RESUMED, State.DESTROYED) } } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2Node import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2Presenter class SimpleRoutingChild2Builder( private val dependency: SimpleRoutingChild2.Dependency ) : SimpleBuilder<SimpleRoutingChild2>() { override fun build(buildParams: BuildParams<Nothing?>): SimpleRoutingChild2 { val customisation = buildParams.getOrDefault(SimpleRoutingChild2.Customisation()) val presenter = SimpleRoutingChild2Presenter() return SimpleRoutingChild2Node( buildParams = buildParams, viewFactory = customisation.viewFactory(null), plugins = listOf(presenter) ) } } <file_sep>package com.badoo.ribs.tutorials.tutorial5.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildContext import com.badoo.ribs.tutorials.tutorial5.R import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainer import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.builder.GreetingsContainerBuilder import com.badoo.ribs.tutorials.tutorial5.util.User import com.google.android.material.snackbar.Snackbar import io.reactivex.functions.Consumer /** The tutorial app's single activity */ class RootActivity : RibActivity() { override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Node<*> = GreetingsContainerBuilder( object : GreetingsContainer.Dependency { override fun user(): User = User.DUMMY override fun greetingsContainerOutput(): Consumer<GreetingsContainer.Output> = Consumer { output -> when (output) { is GreetingsContainer.Output.GreetingsSaid -> { Snackbar.make( rootViewGroup, "${output.greeting.resolve(this@RootActivity)} to you as well!", Snackbar.LENGTH_SHORT ).show() } } } } ).build(BuildContext.root(savedInstanceState = savedInstanceState)) } <file_sep>package com.badoo.ribs.tutorials.tutorial1.rib.hello_world import androidx.annotation.LayoutRes import android.view.ViewGroup import android.widget.Button import com.badoo.ribs.core.view.RibView import com.badoo.ribs.core.view.ViewFactoryBuilder import com.badoo.ribs.core.customisation.inflate import com.badoo.ribs.core.view.AndroidRibView import com.badoo.ribs.core.view.ViewFactory import com.badoo.ribs.tutorials.tutorial1.R import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorldView.Event import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorldView.ViewModel import com.jakewharton.rxrelay2.PublishRelay import io.reactivex.ObservableSource import io.reactivex.functions.Consumer interface HelloWorldView : RibView, ObservableSource<Event>, Consumer<ViewModel> { sealed class Event { object ButtonClicked : Event() } data class ViewModel( val i: Int = 0 ) interface Factory : ViewFactoryBuilder<Nothing?, HelloWorldView> } class HelloWorldViewImpl private constructor( override val androidView: ViewGroup, private val events: PublishRelay<Event> = PublishRelay.create() ) : AndroidRibView(), HelloWorldView, ObservableSource<Event> by events, Consumer<ViewModel> { class Factory( @LayoutRes private val layoutRes: Int = R.layout.rib_hello_world ) : HelloWorldView.Factory { override fun invoke(deps: Nothing?): ViewFactory<HelloWorldView> = ViewFactory { HelloWorldViewImpl( it.inflate(layoutRes) ) } } private val button: Button = androidView.findViewById(R.id.hello_world_button) init { button.setOnClickListener { events.accept(Event.ButtonClicked) } } override fun accept(vm: ViewModel) { } } <file_sep>package com.badoo.ribs.samples.buildtime.rib.build_time_deps import com.badoo.ribs.core.plugin.ViewAware import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.routing.source.backstack.operation.replace import com.badoo.ribs.samples.buildtime.rib.build_time_deps.BuildTimeDepsRouter.Configuration.ShowProfile interface BuildTimeDepsPresenter { fun onBuildChildClicked(profileId: Int) } internal class BuildTimeDepsPresenterImpl( private val backStack: BackStack<BuildTimeDepsRouter.Configuration> ) : ViewAware<BuildTimeDepsView>, BuildTimeDepsPresenter { override fun onBuildChildClicked(profileId: Int) { backStack.replace(ShowProfile(profileId)) } } <file_sep>package com.badoo.ribs.example.logged_out_container.routing import com.badoo.ribs.example.logged_out_container.LoggedOutContainer import com.badoo.ribs.example.welcome.Welcome import com.badoo.ribs.example.welcome.WelcomeBuilder internal class LoggedOutContainerChildBuilders( val dependency: LoggedOutContainer.Dependency ) { private val subtreeDeps = SubtreeDeps(dependency) val welcomeBuilder = WelcomeBuilder(subtreeDeps) private class SubtreeDeps( dependency: LoggedOutContainer.Dependency ) : LoggedOutContainer.Dependency by dependency, Welcome.Dependency } <file_sep>package com.badoo.ribs.routing.transition.progress class MultiProgressEvaluator : ProgressEvaluator { private val evaluators = mutableListOf<ProgressEvaluator>() fun add(evaluator: ProgressEvaluator) { evaluators.add(evaluator) } override var progress: Float = evaluators.map { it.progress }.min() ?: 0f override fun isPending(): Boolean = evaluators.any { it.isPending() } } <file_sep>@file:SuppressWarnings("LongParameterList") package com.badoo.ribs.samples.comms_nodes_1.rib.container import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.samples.comms_nodes_1.rib.container.routing.ContainerChildBuilders import com.badoo.ribs.samples.comms_nodes_1.rib.container.routing.ContainerRouter import com.badoo.ribs.samples.comms_nodes_1.rib.container.routing.ContainerRouter.Configuration import com.badoo.ribs.samples.comms_nodes_1.rib.container.routing.ContainerRouter.Configuration.Content class ContainerBuilder( private val dependency: Container.Dependency ) : SimpleBuilder<Container>() { private val builders by lazy { ContainerChildBuilders(dependency) } override fun build(buildParams: BuildParams<Nothing?>): Container { val backStack = backStack(buildParams) val router = router(buildParams, backStack, builders) val presenter = ContainerPresenterImpl(backStack) return ContainerNode( buildParams = buildParams, viewFactory = ContainerViewImpl.Factory().invoke(deps = null), plugins = listOfNotNull(router, presenter) ) } private fun backStack(buildParams: BuildParams<Nothing?>): BackStack<Configuration> = BackStack( buildParams = buildParams, initialConfiguration = Content.Child1 ) private fun router( buildParams: BuildParams<Nothing?>, backStack: BackStack<Configuration>, builders: ContainerChildBuilders ) = ContainerRouter( buildParams = buildParams, builders = builders, routingSource = backStack ) } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1 import com.badoo.ribs.core.Rib import com.badoo.ribs.core.customisation.RibCustomisation interface SimpleRoutingChild1Child1 : Rib { interface Dependency class Customisation( val viewFactory: SimpleRoutingChild1Child1View.Factory = SimpleRoutingChild1Child1ViewImpl.Factory() ) : RibCustomisation } <file_sep>package com.badoo.ribs.routing.transition.progress import com.badoo.ribs.util.RIBs class SingleProgressEvaluator : ProgressEvaluator { private sealed class Progress { object Initialised : Progress() object Reset : Progress() class InProgress : Progress() { var progress: Float = 0f } object Finished : Progress() } private var state: Progress = Progress.Initialised override val progress: Float = when (val state = state) { is Progress.Initialised -> 0f is Progress.Reset -> 0f is Progress.InProgress -> state.progress is Progress.Finished -> 1f } fun start() { state = Progress.InProgress() } fun updateProgress(progress: Float) { when (val state = state) { is Progress.InProgress -> state.progress = progress else -> if (progress != 1f && progress != 0f) { RIBs.errorHandler.handleNonFatalError( "Progress $progress is not applicable to $state" ) } } } fun reset() { state = Progress.Reset } fun markFinished() { state = Progress.Finished } override fun isPending(): Boolean = isInProgress() || isInitialised() private fun isInProgress(): Boolean = state is Progress.InProgress private fun isInitialised(): Boolean = state is Progress.Initialised } <file_sep>package com.badoo.ribs.samples.dialogs.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.android.dialog.AlertDialogLauncher import com.badoo.ribs.android.dialog.DialogLauncher import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.BuildContext import com.badoo.ribs.samples.dialogs.R import com.badoo.ribs.samples.dialogs.rib.dialogs_example.DialogsExample import com.badoo.ribs.samples.dialogs.rib.dialogs_example.DialogsBuilder class DialogsActivity : RibActivity() { private val deps = object : DialogsExample.Dependency { override val dialogLauncher: DialogLauncher = AlertDialogLauncher( this@DialogsActivity, [email protected] ) } override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_dialogs) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.dialogs_activity_root) override fun createRib(savedInstanceState: Bundle?): Rib = DialogsBuilder(deps).build(BuildContext.root(savedInstanceState)) } <file_sep>package com.badoo.ribs.tutorials.tutorial3.rib.hello_world.builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial3.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial3.rib.hello_world.HelloWorldInteractor import com.badoo.ribs.tutorials.tutorial3.rib.hello_world.HelloWorldView import dagger.Provides @dagger.Module internal object HelloWorldModule { @HelloWorldScope @Provides @JvmStatic internal fun interactor( buildParams: BuildParams<Nothing?> ): HelloWorldInteractor = HelloWorldInteractor( buildParams = buildParams ) @HelloWorldScope @Provides @JvmStatic internal fun node( buildParams: BuildParams<Nothing?>, customisation: HelloWorld.Customisation, interactor: HelloWorldInteractor ) : Node<HelloWorldView> = Node( buildParams = buildParams, viewFactory = customisation.viewFactory(null), plugins = listOf(interactor) ) } <file_sep>package com.badoo.ribs.routing.state.feature import com.badoo.ribs.routing.state.RoutingContext import com.badoo.ribs.routing.state.changeset.TransitionDescriptor import com.badoo.ribs.routing.state.feature.state.WorkingState import com.badoo.ribs.routing.transition.handler.TransitionHandler import com.badoo.ribs.test.TestConfiguration import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import org.junit.Test class ActorTest { private val pendingTransition: PendingTransition<TestConfiguration> = mock() private val pendingTransitionFactory: PendingTransitionFactory<TestConfiguration> = mock { on { create(any(), any(), any(), any()) } doReturn pendingTransition } /** * [Case-1] * 1. there is no ongoingTransitions * 2. there is no pendingTransitions * 3. globalActivationState is NOT SLEEPING * 4. transitionHandler is NOT null */ @Test fun `GIVEN Case-1 conditions WHEN a RoutingChange is accepted THEN a pendingTransition is scheduled`() { val state = WorkingState<TestConfiguration>(activationLevel = RoutingContext.ActivationState.ACTIVE) val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = mock() ) getActor().invoke(state, transaction) verify(pendingTransition).schedule() } /** * [Case-2] * 1. there is no ongoingTransitions * 2. there is no pendingTransitions * 2. globalActivationState is SLEEPING * 3. transitionHandler is NOT null */ @Test fun `GIVEN Case-2 conditions WHEN a RoutingChange is accepted THEN a pendingTransition is NOT scheduled`() { val state = WorkingState<TestConfiguration>(activationLevel = RoutingContext.ActivationState.SLEEPING) val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = mock() ) getActor().invoke(state, transaction) verify(pendingTransition, never()).schedule() } /** * [Case-3] * 1. there is no ongoingTransitions * 2. there is no pendingTransitions * 3. globalActivationState is NOT SLEEPING * 4. transitionHandler is null */ @Test fun `GIVEN Case-3 conditions WHEN a RoutingChange is accepted THEN a pendingTransition is NOT scheduled`() { val state = WorkingState<TestConfiguration>(activationLevel = RoutingContext.ActivationState.ACTIVE) val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = mock() ) getActor(null).invoke(state, transaction) verify(pendingTransition, never()).schedule() } /** * [Case-4] * 1. there is no ongoingTransitions * 2. there is 1 pendingTransitions * 3. globalActivationState is NOT SLEEPING * 4. transitionHandler is NOT null * 5. The existing pending transition is the reversed of the new RoutingChange */ @Test fun `GIVEN Case-4 conditions WHEN a RoutingChange is accepted THEN a the old pending transition is discarded, and new one is scheduled`() { val oldPendingTransition: PendingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf(oldPendingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isReverseOf(oldPendingTransition.descriptor) } doReturn true } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(oldPendingTransition).discard() verify(pendingTransition).schedule() } /** * [Case-5] * 1. there is no ongoingTransitions * 2. there is 1 pendingTransitions * 3. globalActivationState is NOT SLEEPING * 4. transitionHandler is NOT null * 5. The existing pending transition is the continuation of the new RoutingChange */ @Test fun `GIVEN Case-5 conditions WHEN a RoutingChange is accepted THEN the old pending transition is completeWithoutTransition, and new one is scheduled`() { val oldPendingTransition: PendingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf(oldPendingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isReverseOf(oldPendingTransition.descriptor) } doReturn false on { isContinuationOf(oldPendingTransition.descriptor) } doReturn true } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(oldPendingTransition).completeWithoutTransition() verify(pendingTransition).schedule() } /** * [Case-6] * 1. there is no ongoingTransitions * 2. there is no pendingTransitions * 3. globalActivationState is NOT SLEEPING * 4. transitionHandler is NOT null * 5. The existing pending transition is the continuation of the new RoutingChange */ @Test fun `GIVEN Case-6 conditions WHEN a RoutingChange is accepted THEN the old pending transition is completeWithoutTransition, and new one is scheduled`() { val oldPendingTransition: PendingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf(oldPendingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isReverseOf(oldPendingTransition.descriptor) } doReturn false on { isContinuationOf(oldPendingTransition.descriptor) } doReturn true } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(oldPendingTransition).completeWithoutTransition() verify(pendingTransition).schedule() } /** * [Case-7] * 1. there is no ongoingTransitions * 2. there is no pendingTransitions * 3. globalActivationState is NOT SLEEPING * 4. transitionHandler is NOT null * 5. The existing pending transition has no interactions with the new one */ @Test fun `GIVEN Case-7 conditions WHEN a RoutingChange is accepted THEN then new one is scheduled and no actions are applied to old one`() { val oldPendingTransition: PendingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf(oldPendingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isReverseOf(oldPendingTransition.descriptor) } doReturn false on { isContinuationOf(oldPendingTransition.descriptor) } doReturn false } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(oldPendingTransition, never()).completeWithoutTransition() verify(oldPendingTransition, never()).discard() verify(pendingTransition).schedule() } /** * [Case-8] * 1. globalActivationState is NOT SLEEPING * 2. there is 1 pendingTransitions * 3. transitionHandler is NOT null * 4. Accepted transition is the pending one. */ @Test fun `GIVEN Case-8 conditions WHEN a ExecutePendingTransition is accepted THEN then the pendingTransition is executed and ongoingTransition started`() { val ongoingTransition: OngoingTransition<TestConfiguration> = mock() val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf(pendingTransition) ) whenever(pendingTransition.execute(any())).thenReturn(ongoingTransition) getActor().invoke(state, Transaction.InternalTransaction.ExecutePendingTransition(pendingTransition)) verify(pendingTransition).execute(any()) verify(ongoingTransition).start() } /** * [Case-9] * 1. globalActivationState is NOT SLEEPING * 2. there is 1 pendingTransitions * 3. transitionHandler is NOT null * 4. Accepted transition is NOT the pending one. */ @Test fun `GIVEN Case-9 conditions WHEN a ExecutePendingTransition is accepted THEN then the pendingTransition is discarded`() { val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf<PendingTransition<TestConfiguration>>(mock()) ) getActor().invoke(state, Transaction.InternalTransaction.ExecutePendingTransition(pendingTransition)) verify(pendingTransition).discard() } /** * [Case-10] * 1. globalActivationState is SLEEPING * 2. there is 1 pendingTransitions * 3. transitionHandler is NOT null * 4. Accepted transition is the pending one. */ @Test fun `GIVEN Case-10 conditions WHEN a ExecutePendingTransition is accepted THEN then the pendingTransition is completedWithoutTransition`() { val state = WorkingState( activationLevel = RoutingContext.ActivationState.SLEEPING, pendingTransitions = listOf(pendingTransition) ) getActor().invoke(state, Transaction.InternalTransaction.ExecutePendingTransition(pendingTransition)) verify(pendingTransition).completeWithoutTransition() } /** * [Case-11] * 1. globalActivationState is NOT SLEEPING * 2. there is 1 pendingTransitions * 3. transitionHandler is null * 4. Accepted transition is the pending one. */ @Test fun `GIVEN Case-11 conditions WHEN a ExecutePendingTransition is accepted THEN then the pendingTransition is completedWithoutTransition`() { val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, pendingTransitions = listOf(pendingTransition) ) getActor(null).invoke(state, Transaction.InternalTransaction.ExecutePendingTransition(pendingTransition)) verify(pendingTransition).completeWithoutTransition() } /** * [Case-12] * 1. globalActivationState is NOT SLEEPING * 2. transitionHandler is NOT null * 3. there is no pendingTransitions * 4. there is 1 ongoingTransition * 4. The existing ongoingTransition is the reverse of the new one. */ @Test fun `GIVEN Case-12 conditions WHEN a RoutingChange is accepted THEN then the old one is reversed, and new one is NOT scheduled`() { val ongoingTransition: OngoingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, ongoingTransitions = listOf(ongoingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isReverseOf(ongoingTransition.descriptor) } doReturn true } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(ongoingTransition).reverse() verify(pendingTransition, never()).schedule() } /** * [Case-13] * 1. globalActivationState is NOT SLEEPING * 2. transitionHandler is NOT null * 3. there is no pendingTransitions * 4. there is 1 ongoingTransition * 4. The new transition is the continuation of the ongoing one. */ @Test fun `GIVEN Case-13 conditions WHEN a RoutingChange is accepted THEN then the old one is jumpToEnd, and new one is scheduled`() { val ongoingTransition: OngoingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, ongoingTransitions = listOf(ongoingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isContinuationOf(ongoingTransition.descriptor) } doReturn true } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(ongoingTransition).jumpToEnd() verify(pendingTransition).schedule() } /** * [Case-14] * 1. globalActivationState is NOT SLEEPING * 2. transitionHandler is NOT null * 3. there is no pendingTransitions * 4. there is 1 ongoingTransition * 4. The new transition has no interaction with ongoing one */ @Test fun `GIVEN Case-14 conditions WHEN a RoutingChange is accepted THEN then new one is scheduled and no actions are applied to old one`() { val ongoingTransition: OngoingTransition<TestConfiguration> = mock { on { descriptor } doReturn mock() } val state = WorkingState( activationLevel = RoutingContext.ActivationState.ACTIVE, ongoingTransitions = listOf(ongoingTransition) ) val newDescriptor: TransitionDescriptor = mock { on { isReverseOf(ongoingTransition.descriptor) } doReturn false on { isContinuationOf(ongoingTransition.descriptor) } doReturn false } val transaction = Transaction.RoutingChange<TestConfiguration>( changeset = emptyList(), descriptor = newDescriptor ) getActor().invoke(state, transaction) verify(ongoingTransition, never()).reverse() verify(ongoingTransition, never()).jumpToEnd() verify(pendingTransition).schedule() } private fun getActor(transitionHandler: TransitionHandler<TestConfiguration>? = mock()) = Actor( resolver = mock(), activator = mock(), parentNode = mock(), transitionHandler = transitionHandler, effectEmitter = mock(), pendingTransitionFactory = pendingTransitionFactory ) } <file_sep>package com.badoo.ribs.samples.back_stack.rib.parent.routing import com.badoo.ribs.samples.back_stack.rib.child_a.ChildA import com.badoo.ribs.samples.back_stack.rib.child_a.ChildABuilder import com.badoo.ribs.samples.back_stack.rib.child_b.ChildB import com.badoo.ribs.samples.back_stack.rib.child_b.ChildBBuilder import com.badoo.ribs.samples.back_stack.rib.child_c.ChildC import com.badoo.ribs.samples.back_stack.rib.child_c.ChildCBuilder import com.badoo.ribs.samples.back_stack.rib.child_d.ChildD import com.badoo.ribs.samples.back_stack.rib.child_d.ChildDBuilder import com.badoo.ribs.samples.back_stack.rib.child_e.ChildE import com.badoo.ribs.samples.back_stack.rib.child_e.ChildEBuilder import com.badoo.ribs.samples.back_stack.rib.child_f.ChildF import com.badoo.ribs.samples.back_stack.rib.child_f.ChildFBuilder import com.badoo.ribs.samples.back_stack.rib.parent.Parent internal open class ParentChildBuilders( dependency: Parent.Dependency ) { private val subtreeDeps = SubtreeDependency(dependency) val childA: ChildABuilder = ChildABuilder(subtreeDeps) val childB: ChildBBuilder = ChildBBuilder(subtreeDeps) val childC: ChildCBuilder = ChildCBuilder(subtreeDeps) val childD: ChildDBuilder = ChildDBuilder(subtreeDeps) val childE: ChildEBuilder = ChildEBuilder(subtreeDeps) val childF: ChildFBuilder = ChildFBuilder(subtreeDeps) class SubtreeDependency( dependency: Parent.Dependency ) : Parent.Dependency by dependency, ChildA.Dependency, ChildD.Dependency, ChildB.Dependency, ChildC.Dependency, ChildE.Dependency, ChildF.Dependency } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.SimpleRoutingChild1Child1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.SimpleRoutingChild1Child1Node class SimpleRoutingChild1Child1Builder( private val dependency: SimpleRoutingChild1Child1.Dependency ) : SimpleBuilder<SimpleRoutingChild1Child1>() { override fun build(buildParams: BuildParams<Nothing?>): SimpleRoutingChild1Child1 { val customisation = buildParams.getOrDefault(SimpleRoutingChild1Child1.Customisation()) return SimpleRoutingChild1Child1Node( buildParams = buildParams, viewFactory = customisation.viewFactory(null) ) } } <file_sep>package com.badoo.ribs.portal import com.badoo.ribs.annotation.ExperimentalApi import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.portal.PortalRouter.Configuration import com.badoo.ribs.routing.source.backstack.BackStack @ExperimentalApi class RxPortalBuilder( dependency: Portal.Dependency ) : BasePortalBuilder<RxPortal>(dependency) { override fun createNode( buildParams: BuildParams<Nothing?>, interactor: PortalInteractor, router: PortalRouter, backStack: BackStack<Configuration> ): RxPortal = RxPortalNode( buildParams = buildParams, backStack = backStack, plugins = listOf( interactor, router ) ) } <file_sep>package com.badoo.ribs.template.node.foo_bar import androidx.lifecycle.Lifecycle import com.badoo.mvicore.android.lifecycle.createDestroy import com.badoo.mvicore.android.lifecycle.startStop import com.badoo.mvicore.binder.using import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.template.node.foo_bar.analytics.FooBarAnalytics import com.badoo.ribs.template.node.foo_bar.feature.FooBarFeature import com.badoo.ribs.template.node.foo_bar.mapper.InputToWish import com.badoo.ribs.template.node.foo_bar.mapper.NewsToOutput import com.badoo.ribs.template.node.foo_bar.mapper.StateToViewModel import com.badoo.ribs.template.node.foo_bar.mapper.ViewEventToAnalyticsEvent import com.badoo.ribs.template.node.foo_bar.mapper.ViewEventToWish import com.badoo.ribs.template.node.foo_bar.routing.FooBarRouter.Configuration internal class FooBarInteractor( buildParams: BuildParams<*>, private val backStack: BackStack<Configuration>, private val feature: FooBarFeature ) : Interactor<FooBar, FooBarView>( buildParams = buildParams ) { override fun onCreate(nodeLifecycle: Lifecycle) { nodeLifecycle.createDestroy { bind(feature.news to rib.output using NewsToOutput) bind(rib.input to feature using InputToWish) } } override fun onViewCreated(view: FooBarView, viewLifecycle: Lifecycle) { viewLifecycle.startStop { bind(feature to view using StateToViewModel) bind(view to feature using ViewEventToWish) bind(view to FooBarAnalytics using ViewEventToAnalyticsEvent) } } override fun onChildBuilt(child: Node<*>) { /** * TODO bind children here and delete this comment block. * * At this point children haven't set their own bindings yet, * so it's safe to setup listening to their output before they start emitting. * * On the other hand, they're not ready to receive inputs yet. Usually this is alright. * If it's a requirement though, create those bindings in [onChildAttached] */ // child.lifecycle.createDestroy { // when (child) { // is Child1 -> bind(child.output to someConsumer) // } // } } } <file_sep># Tutorial #3 - solutions ### HelloWorldView ```kotlin interface HelloWorldView : RibView, ObservableSource<Event>, Consumer<ViewModel> { sealed class Event { object ButtonClicked : Event() } data class ViewModel( val titleText: Text, val welcomeText: Text ) } ``` ### HelloWorldViewImpl ```kotlin class HelloWorldViewImpl private constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0, private val events: PublishRelay<Event> ) : ConstraintLayout(context, attrs, defStyle), HelloWorldView, ObservableSource<Event> by events, Consumer<ViewModel> { @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : this(context, attrs, defStyle, PublishRelay.create<Event>()) override val androidView = this private val title: TextView by lazy { findViewById<TextView>(R.id.hello_world_title) } private val welcome: TextView by lazy { findViewById<TextView>(R.id.hello_world_welcome) } private val button: Button by lazy { findViewById<Button>(R.id.hello_world_button) } override fun onFinishInflate() { super.onFinishInflate() button.setOnClickListener { events.accept(Event.ButtonClicked) } } override fun accept(vm: ViewModel) { title.text = vm.titleText.resolve(context) welcome.text = vm.welcomeText.resolve(context) } } ``` ### HelloWorldInteractor ```kotlin class HelloWorldInteractor( user: User, config: HelloWorld.Configuration, savedInstanceState: Bundle?, router: Router<Configuration, Nothing, Content, Nothing, HelloWorldView> ) : Interactor<Configuration, Content, Nothing, HelloWorldView>( savedInstanceState = savedInstanceState, router = router ) { override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) view.accept(initialViewModel) } private val initialViewModel = HelloWorldView.ViewModel( titleText = Text.Resource(R.string.hello_world_title, user.name()), welcomeText = config.welcomeMessage ) } ``` ### HelloWorld ```kotlin interface HelloWorld : Rib { interface Dependency { fun user(): User fun config(): Config } data class Config { val welcomeMessage: Text } // remainder the same } ``` ### HelloWorldModule ```kotlin @dagger.Module internal object HelloWorldModule { @HelloWorldScope @Provides @JvmStatic internal fun interactor( user: User, config: HelloWorld.Configuration, router: HelloWorldRouter ): HelloWorldInteractor = HelloWorldInteractor( user = user, config = config, router = router ) // remainder the same } ``` ### GreetingsContainer ```kotlin interface GreetingsContainer : Rib { interface Dependency { fun user(): User fun greetingsContainerOutput(): Consumer<Output> } sealed class Output { data class GreetingsSaid(val greeting: String) : Output() } } ``` ### RootActivity ```kotlin /** The tutorial app's single activity */ class RootActivity : RibActivity() { // remainder the same override fun createRib(savedInstanceState: Bundle?): Node<*> = GreetingsContainerBuilder( object : GreetingsContainer.Dependency { override fun user(): User = User.DUMMY override fun greetingsContainerOutput(): Consumer<GreetingsContainer.Output> = Consumer { output -> when (output) { is GreetingsContainer.Output.GreetingsSaid -> { Snackbar.make(rootViewGroup, output.greeting, Snackbar.LENGTH_SHORT).show() } } } } ).build() } ``` <file_sep>package com.badoo.ribs.example import android.os.Bundle import android.preference.PreferenceManager import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.BuildContext import com.badoo.ribs.core.modality.BuildContext.Companion.root import com.badoo.ribs.core.plugin.Plugin import com.badoo.ribs.core.plugin.utils.debug.DebugControlsHost import com.badoo.ribs.core.plugin.utils.debug.GrowthDirection import com.badoo.ribs.debug.TreePrinter import com.badoo.ribs.example.auth.AuthStateStorage import com.badoo.ribs.example.auth.PreferencesAuthStateStorage import com.badoo.ribs.example.network.ApiFactory import com.badoo.ribs.example.network.NetworkError import com.badoo.ribs.example.network.UnsplashApi import com.badoo.ribs.example.root.Root import com.badoo.ribs.example.root.RootBuilder import com.jakewharton.rxrelay2.PublishRelay import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers class RootActivity : RibActivity() { private val networkErrorsRelay = PublishRelay.create<NetworkError>() override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.example_activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Rib = buildRootNode(root( savedInstanceState = savedInstanceState, defaultPlugins = { node -> if (BuildConfig.DEBUG) { listOfNotNull( if (node.isRoot) createDebugControlHost() else null ) } else emptyList() } )) private fun buildRootNode( buildContext: BuildContext ): Root = RootBuilder( object : Root.Dependency { override val api: UnsplashApi = api() override val authStateStorage: AuthStateStorage = PreferencesAuthStateStorage(PreferenceManager.getDefaultSharedPreferences(this@RootActivity)) override val networkErrors: Observable<NetworkError> = networkErrorsRelay .observeOn(AndroidSchedulers.mainThread()) } ).build(buildContext) private fun api(): UnsplashApi = ApiFactory.api( isDebug = BuildConfig.DEBUG, accessKey = BuildConfig.ACCESS_KEY, networkErrorConsumer = networkErrorsRelay ) private fun createDebugControlHost(): Plugin = DebugControlsHost( viewGroupForChildren = { findViewById(R.id.debug_controls_host) }, growthDirection = GrowthDirection.BOTTOM, defaultTreePrinterFormat = TreePrinter.FORMAT_SIMPLE ) } <file_sep>package com.badoo.ribs.tutorials.tutorial4.rib.greetings_container.builder import com.badoo.ribs.android.text.Text import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial4.R import com.badoo.ribs.tutorials.tutorial4.rib.greetings_container.GreetingsContainerInteractor import com.badoo.ribs.tutorials.tutorial4.rib.greetings_container.GreetingsContainerRouter import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.builder.HelloWorldBuilder import dagger.Provides import io.reactivex.functions.Consumer @dagger.Module internal object GreetingsContainerModule { @GreetingsContainerScope @Provides @JvmStatic internal fun router( // pass component to child rib builders, or remove if there are none component: GreetingsContainerComponent, interactor: GreetingsContainerInteractor, buildParams: BuildParams<Nothing?> ): GreetingsContainerRouter = GreetingsContainerRouter( buildParams = buildParams, routingSource = interactor, helloWorldBuilder = HelloWorldBuilder(component) ) @GreetingsContainerScope @Provides @JvmStatic internal fun interactor( buildParams: BuildParams<Nothing?> ): GreetingsContainerInteractor = GreetingsContainerInteractor( buildParams = buildParams ) @GreetingsContainerScope @Provides @JvmStatic internal fun node( buildParams: BuildParams<Nothing?>, router: GreetingsContainerRouter, interactor: GreetingsContainerInteractor ) : Node<Nothing> = Node<Nothing>( buildParams = buildParams, viewFactory = null, plugins = listOf(interactor, router) ) @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldConfig(): HelloWorld.Config = HelloWorld.Config( welcomeMessage = Text.Resource( R.string.hello_world_welcome_text ) ) @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldOutputConsumer( interactor: GreetingsContainerInteractor ) : Consumer<HelloWorld.Output> = TODO("Pass instance from interactor") } <file_sep>package com.badoo.ribs.tutorials.tutorial1.rib.hello_world.mapper import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorld.Output import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.HelloWorldView object ViewEventToOutput : (HelloWorldView.Event) -> HelloWorld.Output { override fun invoke(event: HelloWorldView.Event): HelloWorld.Output = when (event) { HelloWorldView.Event.ButtonClicked -> Output.HelloThere } } <file_sep>package com.badoo.ribs.tutorials.tutorial3.rib.greetings_container import com.badoo.ribs.core.Rib import io.reactivex.functions.Consumer interface GreetingsContainer : Rib { interface Dependency { fun greetingsContainerOutput(): Consumer<Output> } sealed class Output { data class GreetingsSaid(val greeting: String) : Output() } } <file_sep>package com.badoo.ribs.tutorials.tutorial3.rib.hello_world import com.badoo.ribs.core.Rib interface HelloWorld : Rib { interface Dependency class Customisation( val viewFactory: HelloWorldView.Factory = HelloWorldViewImpl.Factory() ) } <file_sep>package com.badoo.ribs.samples.plugins.plugins_demo import com.badoo.ribs.core.Rib interface PluginsDemo : Rib { interface Dependency } <file_sep>package com.badoo.ribs.samples.simplerouting import android.os.Bundle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import com.badoo.ribs.test.RibsRule import com.badoo.ribs.core.modality.BuildContext.Companion.root import com.badoo.ribs.samples.simplerouting.rib.R import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.SimpleRoutingChild1Child1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.builder.SimpleRoutingChild1Child1Builder import org.junit.Rule import org.junit.Test class SimpleRoutingChild1Child1Test { @get:Rule val ribsRule = RibsRule { _, savedInstanceState -> buildRib(savedInstanceState) } private fun buildRib(savedInstanceState: Bundle?) = SimpleRoutingChild1Child1Builder( object : SimpleRoutingChild1Child1.Dependency {} ).build(root(savedInstanceState)) @Test fun showsTitleText() { onView(withId(R.id.child1_child1_title)) .check(matches(withText(R.string.child1_child1_text))) } } <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.parent import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.routing.source.backstack.operation.push import com.badoo.ribs.samples.transitionanimations.rib.parent.routing.ParentRouter.Configuration interface ParentPresenter { fun goToNext() } internal class ParentPresenterImpl( private val backStack: BackStack<Configuration> ) : ParentPresenter { override fun goToNext() { backStack.push(backStack.activeConfiguration.toNextConfiguration()) } private fun Configuration.toNextConfiguration() = when (this) { is Configuration.Child1 -> Configuration.Child2 is Configuration.Child2 -> Configuration.Child3 is Configuration.Child3 -> Configuration.Child1 } } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.hello_world import com.badoo.ribs.core.Rib import com.badoo.ribs.android.text.Text import com.badoo.ribs.tutorials.tutorial5.util.User import io.reactivex.ObservableSource import io.reactivex.functions.Consumer interface HelloWorld : Rib { interface Dependency { fun helloWorldInput(): ObservableSource<Input> fun helloWorldOutput(): Consumer<Output> fun user(): User fun config(): Config } sealed class Input { data class UpdateButtonText(val text: Text): Input() } sealed class Output { data class HelloThere(val greeting: Text) : Output() } data class Config( val welcomeMessage: Text, val buttonText: Text ) class Customisation( val viewFactory: HelloWorldView.Factory = HelloWorldViewImpl.Factory() ) } <file_sep>package com.badoo.ribs.core.helper import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize object AnyConfiguration : Parcelable { override fun toString(): String = "AnyConfiguration" } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector.builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView import dagger.BindsInstance @OptionSelectorScope @dagger.Component( modules = [OptionSelectorModule::class], dependencies = [OptionSelector.Dependency::class] ) internal interface OptionSelectorComponent { @dagger.Component.Factory interface Factory { fun create( dependency: OptionSelector.Dependency, @BindsInstance buildParams: BuildParams<Nothing?>, @BindsInstance customisation: OptionSelector.Customisation ): OptionSelectorComponent } fun node(): Node<OptionSelectorView> } <file_sep>package com.badoo.ribs.routing.state.feature import com.badoo.ribs.routing.state.feature.RoutingStatePool.Effect.Transition.TransitionFinished import com.badoo.ribs.routing.state.feature.RoutingStatePool.Effect.Transition.TransitionStarted import com.badoo.ribs.routing.transition.TransitionElement import com.badoo.ribs.test.TestConfiguration import com.nhaarman.mockitokotlin2.* import org.junit.Test class OngoingTransitionTest { private val effectEmitter: EffectEmitter<TestConfiguration> = mock() private val transitionElement: TransitionElement<TestConfiguration> = mock() private val ongoingTransition = OngoingTransition( descriptor = mock(), actions = emptyList(), direction = mock(), transitionPair = mock(), transitionElements = listOf(transitionElement), emitter = effectEmitter, handler = mock() ) @Test fun `GIVEN that there are pending transition elements WHEN transition is started THEN TransitionStarted is emitted but not TransitionFinished`() { whenever(transitionElement.isPending()).thenReturn(true) ongoingTransition.start() verify(effectEmitter).invoke(any<TransitionStarted<TestConfiguration>>()) verify(effectEmitter, never()).invoke(any<TransitionFinished<TestConfiguration>>()) } @Test fun `GIVEN that there are NOT pending transition elements WHEN transition has started THEN TransitionFinished is emitted`() { whenever(transitionElement.isPending()).thenReturn(false) ongoingTransition.start() verify(effectEmitter).invoke(any<TransitionFinished<TestConfiguration>>()) } @Test fun `WHEN transition is jumpToEnd THEN TransitionFinished is emitted`() { ongoingTransition.jumpToEnd() verify(effectEmitter).invoke(any<TransitionFinished<TestConfiguration>>()) } } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector import com.badoo.ribs.core.Rib import com.badoo.ribs.core.customisation.RibCustomisation import com.badoo.ribs.android.text.Text import io.reactivex.functions.Consumer interface OptionSelector : Rib { interface Dependency { fun moreOptionsOutput(): Consumer<Output> fun moreOptionsConfig(): Config } data class Config( val options: List<Text> ) sealed class Output class Customisation( val viewFactory: OptionSelectorView.Factory = OptionSelectorViewImpl.Factory() ) : RibCustomisation } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.SimpleRoutingChild1Child2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.SimpleRoutingChild1Child2Node class SimpleRoutingChild1Child2Builder( private val dependency: SimpleRoutingChild1Child2.Dependency ) : SimpleBuilder<SimpleRoutingChild1Child2>() { override fun build(buildParams: BuildParams<Nothing?>): SimpleRoutingChild1Child2 { val customisation = buildParams.getOrDefault(SimpleRoutingChild1Child2.Customisation()) return SimpleRoutingChild1Child2Node( buildParams = buildParams, viewFactory = customisation.viewFactory(null) ) } } <file_sep>package com.badoo.ribs.samples.dialogs.dialogs import com.badoo.ribs.android.dialog.Dialog class LazyDialog : Dialog<Dialog.Event>({}) <file_sep>package com.badoo.ribs.samples.comms_nodes_1.rib.container import com.badoo.ribs.core.Rib interface Container : Rib { interface Dependency } <file_sep>package com.badoo.ribs.tutorials.tutorial3.rib.hello_world import androidx.lifecycle.Lifecycle import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.modality.BuildParams class HelloWorldInteractor( buildParams: BuildParams<Nothing?> ) : Interactor<HelloWorld, HelloWorldView>( buildParams = buildParams ) { override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) } } <file_sep>package com.badoo.ribs.example.auth import android.util.Log import com.badoo.ribs.example.BuildConfig import com.badoo.ribs.example.network.UnsplashApi import com.badoo.ribs.example.network.model.AccessToken import com.jakewharton.rxrelay2.BehaviorRelay import io.reactivex.ObservableSource import io.reactivex.Single interface AuthDataSource { val authUpdates: ObservableSource<AuthState> fun login(authCode: String): Single<AccessToken> fun loginAnonymous() fun logout() fun getState(): AuthState } class AuthDataSourceImpl( private val api: UnsplashApi, private val storage: AuthStateStorage, private val accessKey: String = BuildConfig.ACCESS_KEY, private val clientSecret: String = BuildConfig.CLIENT_SECRET ) : AuthDataSource { private val stateRelay = BehaviorRelay.createDefault<AuthState>(storage.restore()) override val authUpdates: ObservableSource<AuthState> = stateRelay override fun login(authCode: String) = api.requestAccessToken( clientId = accessKey, clientSecret = clientSecret, redirectUri = AuthConfig.redirectUri, code = authCode ) .doOnSuccess(::onAuthSuccess) private fun onAuthSuccess(token: AccessToken) { val authState = AuthState.Authenticated(token.accessToken) updateState(authState) } override fun loginAnonymous() { val state = AuthState.Anonymous updateState(state) } override fun logout() { val state = AuthState.Unauthenticated updateState(state) } override fun getState(): AuthState { val authState = stateRelay.value return if (authState != null) { authState } else { Log.e("AuthDataSource", "Cannot retrieve auth state") AuthState.Unauthenticated } } private fun updateState(authState: AuthState) { storage.save(authState) stateRelay.accept(authState) } } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.greetings_container import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainer.Output.GreetingsSaid import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainerRouter.Configuration import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld.Output.HelloThere import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector import com.badoo.ribs.tutorials.tutorial5.util.BackStackInteractor import com.jakewharton.rxrelay2.PublishRelay import com.jakewharton.rxrelay2.Relay import io.reactivex.functions.Consumer class GreetingsContainerInteractor( buildParams: BuildParams<Nothing?>, output: Consumer<GreetingsContainer.Output> ) : BackStackInteractor<GreetingsContainer, Nothing, Configuration>( buildParams = buildParams, initialConfiguration = Configuration.HelloWorld ) { internal val helloWorldInputSource: Relay<HelloWorld.Input> = PublishRelay.create() internal val helloWorldOutputConsumer: Consumer<HelloWorld.Output> = Consumer { when (it) { is HelloThere -> output.accept(GreetingsSaid(it.greeting)) } } internal val optionsSelectorOutputConsumer: Consumer<OptionSelector.Output> = Consumer { // TODO } } <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.child3 import com.badoo.ribs.core.Rib interface Child3 : Rib <file_sep>package com.badoo.ribs.samples.plugins.plugins_demo import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams class PluginsDemoBuilder( private val dependency: PluginsDemo.Dependency ) : SimpleBuilder<PluginsDemo>() { override fun build(buildParams: BuildParams<Nothing?>): PluginsDemo { val node = PluginsDemoNode( buildParams = buildParams, viewFactory = PluginsDemoViewImpl.Factory().invoke(null), plugins = emptyList() ) return node } } <file_sep>package com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.GreetingsContainerInteractor import com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.GreetingsContainerRouter import dagger.Provides @dagger.Module internal object GreetingsContainerModule { @GreetingsContainerScope @Provides @JvmStatic internal fun interactor( buildParams: BuildParams<Nothing?> ): GreetingsContainerInteractor = GreetingsContainerInteractor( buildParams = buildParams ) @GreetingsContainerScope @Provides @JvmStatic internal fun router( // pass component to child rib builders, or remove if there are none component: GreetingsContainerComponent, interactor: GreetingsContainerInteractor, buildParams: BuildParams<Nothing?> ): GreetingsContainerRouter = GreetingsContainerRouter( buildParams = buildParams, routingSource = interactor ) @GreetingsContainerScope @Provides @JvmStatic internal fun node( buildParams: BuildParams<Nothing?>, router: GreetingsContainerRouter, interactor: GreetingsContainerInteractor ) : Node<Nothing> = Node<Nothing>( buildParams = buildParams, viewFactory = null, plugins = listOf(interactor, router) ) } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.hello_world.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorldView class HelloWorldBuilder( private val dependency: HelloWorld.Dependency ) : SimpleBuilder<Node<HelloWorldView>>() { override fun build(buildParams: BuildParams<Nothing?>): Node<HelloWorldView> = DaggerHelloWorldComponent .factory() .create( dependency = dependency, customisation = HelloWorld.Customisation(), buildParams = buildParams ) .node() } <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.parent import com.badoo.ribs.core.Rib interface Parent : Rib { interface Dependency } <file_sep>package com.badoo.ribs.core.customisation interface RibCustomisation <file_sep>package com.badoo.ribs.routing.source.impl import android.os.Parcelable import com.badoo.ribs.minimal.reactive.Cancellable import com.badoo.ribs.minimal.reactive.Relay import com.badoo.ribs.routing.Routing import com.badoo.ribs.routing.history.RoutingHistory import com.badoo.ribs.routing.history.RoutingHistoryElement import com.badoo.ribs.routing.source.RoutingSource import java.util.UUID class Pool<C : Parcelable>( private val allowRepeatingConfigurations: Boolean ) : RoutingSource<C> { private var elements: Map<Routing.Identifier, RoutingHistoryElement<C>> = emptyMap() private val current: RoutingHistory<C> get() = RoutingHistory.from( elements.values ) private val states: Relay<RoutingHistory<C>> = Relay() // FIXME save/restore to bundle to support correct baseLineState override fun baseLineState(fromRestored: Boolean): RoutingHistory<C> = RoutingHistory.from( emptySet() ) fun add( configuration: C, identifier: Routing.Identifier = Routing.Identifier( "Set ${System.identityHashCode(this)} #$configuration.${if (allowRepeatingConfigurations) UUID.randomUUID() else "#"}" ) ): Routing.Identifier { if (!allowRepeatingConfigurations) { elements .filter { it.value.routing.configuration == configuration } .map { it.key } .firstOrNull()?.let { return it } } elements = elements.plus( identifier to RoutingHistoryElement( activation = RoutingHistoryElement.Activation.INACTIVE, routing = Routing( configuration = configuration, identifier = identifier ), // TODO consider overlay support -- not needed now, can be added later overlays = emptyList() ) ) updateState() return identifier } fun activate(identifier: Routing.Identifier) { updateActivation(identifier, RoutingHistoryElement.Activation.ACTIVE ) } fun deactivate(identifier: Routing.Identifier) { updateActivation(identifier, RoutingHistoryElement.Activation.INACTIVE ) } private fun updateActivation(identifier: Routing.Identifier, activation: RoutingHistoryElement.Activation) { elements[identifier]?.let { elements = elements .minus(it.routing.identifier) .plus(it.routing.identifier to it.copy( activation = activation ) ) updateState() } } override fun remove(identifier: Routing.Identifier) { elements[identifier]?.let { elements = elements .minus(it.routing.identifier) updateState() } } private fun updateState() { states.emit(current) } override fun observe(callback: (RoutingHistory<C>) -> Unit): Cancellable { callback(current) return states.observe(callback) } } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector.builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector.Output import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorInteractor import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView import dagger.Provides import io.reactivex.functions.Consumer @dagger.Module internal object OptionSelectorModule { @OptionSelectorScope @Provides @JvmStatic internal fun interactor( buildParams: BuildParams<Nothing?>, output: Consumer<Output>, config: OptionSelector.Config ): OptionSelectorInteractor = OptionSelectorInteractor( buildParams = buildParams, output = output, options = config.options ) @OptionSelectorScope @Provides @JvmStatic internal fun node( buildParams: BuildParams<Nothing?>, customisation: OptionSelector.Customisation, interactor: OptionSelectorInteractor ) : Node<OptionSelectorView> = Node( buildParams = buildParams, viewFactory = customisation.viewFactory.invoke(null), plugins = listOf(interactor) ) } <file_sep>package com.badoo.ribs.tutorials.tutorial3.rib.greetings_container import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial3.rib.greetings_container.GreetingsContainerRouter.Configuration import com.badoo.ribs.tutorials.tutorial3.util.BackStackInteractor class GreetingsContainerInteractor( buildParams: BuildParams<Nothing?> ) : BackStackInteractor<GreetingsContainer, Nothing, Configuration>( buildParams = buildParams, initialConfiguration = Configuration.Default ) { } <file_sep>package com.badoo.ribs.core.customisation import com.badoo.ribs.core.Rib import kotlin.reflect.KClass interface MutableRibCustomisationDirectory : RibCustomisationDirectory { fun <T : Rib> putSubDirectory(key: KClass<T>, value: RibCustomisationDirectory) fun <T : RibCustomisation> put(key: KClass<T>, value: T) } <file_sep># Tutorial #3 ## The goal of this tutorial To see how to provide dependencies to a RIB ## Starting out Compiling and launching **tutorial3**, this is what we see: ![](https://i.imgur.com/Ja45nRm.png) We will provide text to the placeholders first manually, then as a dependency. Have a brief look at the `Text` interface found in the library, as we will use it in the example: ```kotlin package com.badoo.ribs.android import android.content.Context /** * An abstraction over text, so that you can provide it from different sources. * * In case the default implementations are not good enough, feel free to implement your own. */ interface Text { fun resolve(context: Context): String class Plain(private val string: String): Text { override fun resolve(context: Context): String = string } class Resource(private val resId: Int, private vararg val formatArgs: Any) : Text { override fun resolve(context: Context): String = context.resources.getString(resId, formatArgs) } } ``` It provides us with an abstraction over textual information, and two simple implementations – one for actual Strings, the other for String resources. This is a useful approach for cases when you want to set a text from resource, but at the place of definition you don't have access to a `Context` that Android can provide, only later. Hence the `resolve(context: Context)` method. ## A welcoming message Let's start with the second placeholder first! Check the `HelloWorldView` interface. Its `ViewModel` contains a dummy integer field only: ```kotlin data class ViewModel( val i: Int = 0 ) ``` Let's change that so that we will give a `Text` to the view to render instead: ```kotlin data class ViewModel( val welcomeText: Text ) ``` Let's scroll down to the Android view implementation. Notice how it already finds a reference to the welcome text view: ```kotlin private val welcome: TextView = androidView.findViewById(R.id.hello_world_welcome) ``` So let's implement the `ViewModel` rendering: ```kotlin override fun accept(vm: ViewModel) { welcome.text = vm.welcomeText.resolve(androidView.context) } ``` Notice how we added `welcomeText` as a `Text`, which we could now resolve using the `Context` our view has access to. ## Feeding the view with data Let's head to our Interactor in this RIB, `HelloWorldInteractor`, where we should put business logic. We'll find an empty block, where we can put all view-related business logic, tied to the lifecycle of the view: ```kotlin override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) } ``` Just to try out what we did, we could do something like this to test out the parts we just implemented in `HelloWorldView`: ```kotlin override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) view.accept(initialViewModel) } private val initialViewModel = HelloWorldView.ViewModel( welcomeText = Text.Plain("Does this work at all?") ) ``` Launch the app to verify that it indeed works. ![](https://i.imgur.com/maHH0pn.png) Alright, now instead of manually fixing this, let's try and make this a dependency! Let's head to `HelloWorld`, the main interface of the RIB, which doesn't have any dependencies now: ```kotlin interface HelloWorld : Rib { interface Dependency // ... } ``` Change it so that it looks like: ```kotlin interface HelloWorld : Rib { interface Dependency { fun config(): Config } // It's a good idea to group all "simple data" dependencies into a Config // object, instead of directly adding them to Dependency interface: data class Config( val welcomeMessage: Text ) // ... } ``` Now if we try to build the project, Dagger will fail us, as we do not yet actually provide this dependency: ``` [Dagger/MissingBinding] com.badoo.ribs.tutorials.tutorial3.rib.hello_world.HelloWorld.Config cannot be provided without an @Inject constructor or an @Provides-annotated method. public abstract interface GreetingsContainerComponent extends com.badoo.ribs.tutorials.tutorial3.rib.hello_world.HelloWorld.Dependency ``` ## Provide dependency directly in the parent In this case, our dependency is simple configuration data, so we could just satisfy it directly in the parent. Let's head to `GreetingsContainerModule`, the place where we add all the `@Provides` DI definitions on the container level, and add this block to the bottom: ```kotlin @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldConfig(): HelloWorld.Config = HelloWorld.Config( welcomeMessage = Text.Resource( R.string.hello_world_welcome_text ) ) ``` Now the app should build, as we provide the dependency - other than that, nothing changed, since we are not using this config yet. Let's correct that, and make use of it in the child `Interactor`. Add the config to the constructor, and use it to construct the initial `ViewModel`: ```kotlin class HelloWorldInteractor( config: HelloWorld.Config, // add this router: // ... remainder omitted ) { override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) view.accept(initialViewModel) } private val initialViewModel = HelloWorldView.ViewModel( welcomeText = config.welcomeMessage // use it ) } ``` And change the actual construction of the Interactor in `HelloWorldModule`: ```kotlin @HelloWorldScope @Provides @JvmStatic internal fun interactor( config: HelloWorld.Config, // add this, Dagger will provide it automatically router: HelloWorldRouter ): HelloWorldInteractor = HelloWorldInteractor( config = config, // pass it to the Interactor router = router ) ``` Try it out, it should now display the text we passed in as a resource: ![](https://i.imgur.com/HTSayPD.png) ## Section summary #### Adding new data to display in the view 1. Add new widget to xml 2. Find view by id and store reference in `ViewImpl` 3. Define new field in `ViewModel` 4. Modify `accept(vm: ViewModel)` method in `ViewImpl` to actually display data 5. In case of initial `ViewModel`: pass it from `Interactor`'s `onViewCreated` method (we'll cover dynamically changing data later) #### Adding dependency to child from parent 1. Add it to child's `Dependency` interface 2. In parent's `Module` class, add new `@Provides` annotated block 3. Use dependency in child where it's needed 1. e.g. add it to constructor of `Interactor` 2. go to child's `Module` / provides function 3. add it as a parameter to `@Provides` function - this will be provided by Dagger 4. use it in constructing the object, e.g. the `Interactor` ## Next task: greet the user We are still left with a placeholder text to be filled with text. Let's imagine this application has some kind of `User` object representing the current logged in user, and we want this placeholder to greet the user like: **"<NAME>!"**, with their actual name. (There's a `User` interface included in this module, check it out) Obviously, the `HelloWorld` RIB cannot fill in the name of the user, and will need an instance of `User` as a dependency. In the case of the welcome text, we could provide the dependency directly. Problem is, finding an instance of `User` is not the responsibility of `HelloWorld`, but it's also not the responsibility of the parent RIB, the `GreetingsContainer`. So in this case, we will need to bubble up this dependency until at some level we can grab an instance of the current `User`, and pass it down. (As we do not have proper logged out / logged in handling yet, we wil just pass in a dummy User object from the Activity level) ## Test your knowledge! Based on the previous sections, you should be able to: 1. Add a new field to `HelloWorldViewImpl` that holds a reference to the `TextView` for the other placeholder, found in `rib_hello_world.xml` with the id `@+id/hello_world_title` 2. Add a new field to `HelloWorldView.ViewModel`, named `titleText`, type `Text` 3. Set the text of the `TextView` by resolving the `Text` from `titleText` whenever the `ViewModel` is rendered in `HelloWorldViewImpl` 4. Set a fixed value for this field from `HelloWorldInteractor` just to test it out. Now let's make it more dynamic. You should also be able to: 1. Add an instance of `user: User` as a constructor dependency to `HelloWorldInteractor` 2. Use `user.name()` to construct: `Text.Resource(R.string.hello_world_title, user.name())`, and pass it as the value for `titleText` when creating the `ViewModel` 3. Add the instance of `User` as a dependency for the creation of `HelloWorldInteractor` in the respective `@Provides` function in `HelloWorldModule` 4. Add `User` to `HelloWorld.Dependency` interface to say that `HelloWorld` RIB needs this from the outside If you feel stuck, you can refer to the previous sections for help, or have a peek at [solutions](solutions.md). Building the project at this point, Dagger should give you: `Dagger/MissingBinding] com.badoo.ribs.tutorials.tutorial3.util.User cannot be provided without an @Provides-annotated method.` ## Bubbling up dependencies This will be super easy, if you got this far. The only difference is that if we cannot provide a dependency directly, we also add it to the `Dependency` interface of parent. We can keep doing this further until on some level we can actually provide it. Really, just a one-liner. Try it: ```kotlin interface GreetingsContainer : Rib { interface Dependency { // Add this, and you are done on this level - Dagger will provide // it further down to children automatically: fun user(): User fun greetingsContainerOutput(): Consumer<Output> } // ... remainder omitted } ``` At this point we reached the root level. `RootActivity` creates an anonymous object actually providing dependencies to `GreetingsContainer`, so we have a compilation error there until we actually implement the newly added `user()` method: ```kotlin /** The tutorial app's single activity */ class RootActivity : RibActivity() { // ... remainder omitted override fun createRib(savedInstanceState: Bundle?): Node<*> = GreetingsContainerBuilder( object : GreetingsContainer.Dependency { // add this block: override fun user(): User = User.DUMMY override fun greetingsContainerOutput(): Consumer<GreetingsContainer.Output> = // ... remainder omitted } ).build(savedInstanceState) } ``` The application should now build, and this is what you should see when launching: ![](https://i.imgur.com/4i2lQ1o.png) ## Tutorial complete Congratulations! You can advance to the next one. <file_sep>package com.badoo.ribs.samples.simplerouting import android.os.Bundle import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import com.badoo.ribs.test.RibsRule import com.badoo.ribs.core.modality.BuildContext.Companion.root import com.badoo.ribs.samples.simplerouting.rib.R import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.builder.SimpleRoutingChild2Builder import org.junit.Rule import org.junit.Test class SimpleRoutingChild2Test { @get:Rule val ribsRule = RibsRule { _, savedInstanceState -> buildRib(savedInstanceState) } private fun buildRib(savedInstanceState: Bundle?) = SimpleRoutingChild2Builder( object : SimpleRoutingChild2.Dependency {} ).build(root(savedInstanceState)) @Test fun showsStaticText() { onView(withId(R.id.content_text)) .check(matches(withText(R.string.child2_text))) } } <file_sep>package com.badoo.ribs.clienthelper.connector import com.badoo.ribs.minimal.reactive.Relay class NodeConnector<Input, Output>( override val input: Relay<Input> = Relay(), override val output: Relay<Output> = Relay() ): Connectable<Input, Output> <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.parent.routing import com.badoo.ribs.samples.transitionanimations.rib.child1.Child1Builder import com.badoo.ribs.samples.transitionanimations.rib.child2.Child2Builder import com.badoo.ribs.samples.transitionanimations.rib.child3.Child3Builder internal open class ParentChildBuilders { val child1Builder: Child1Builder = Child1Builder() val child2Builder: Child2Builder = Child2Builder() val child3Builder: Child3Builder = Child3Builder() } <file_sep>package com.badoo.ribs.tutorials.tutorial1.rib.hello_world import androidx.lifecycle.Lifecycle import com.badoo.mvicore.android.lifecycle.startStop import com.badoo.mvicore.binder.using import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial1.rib.hello_world.mapper.ViewEventToOutput import io.reactivex.functions.Consumer class HelloWorldInteractor( buildParams: BuildParams<Nothing?>, private val output: Consumer<HelloWorld.Output> ) : Interactor<HelloWorld, HelloWorldView>( buildParams = buildParams ) { override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { viewLifecycle.startStop { bind(view to output using ViewEventToOutput) } } } <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.child2 import com.badoo.ribs.core.Rib interface Child2 : Rib <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1 import androidx.lifecycle.Lifecycle import com.badoo.ribs.core.plugin.ViewAware internal class SimpleRoutingChild1Presenter( private val title: String ) : ViewAware<SimpleRoutingChild1View> { override fun onViewCreated(view: SimpleRoutingChild1View, viewLifecycle: Lifecycle) { view.setTitle(title) } } <file_sep>package com.badoo.ribs.samples.buildtime.rib.build_time_deps import com.badoo.ribs.core.Rib interface BuildTimeDeps : Rib <file_sep>package com.badoo.ribs.samples.back_stack.rib.parent import com.badoo.ribs.core.Rib interface Parent : Rib { interface Dependency } <file_sep>package com.badoo.ribs.samples.comms_nodes_1.rib.container.routing import com.badoo.ribs.samples.comms_nodes_1.rib.child1.Child1 import com.badoo.ribs.samples.comms_nodes_1.rib.child1.Child1Builder import com.badoo.ribs.samples.comms_nodes_1.rib.child2.Child2 import com.badoo.ribs.samples.comms_nodes_1.rib.child2.Child2Builder import com.badoo.ribs.samples.comms_nodes_1.rib.child3.Child3 import com.badoo.ribs.samples.comms_nodes_1.rib.child3.Child3Builder import com.badoo.ribs.samples.comms_nodes_1.rib.container.Container import com.badoo.ribs.samples.comms_nodes_1.rib.menu.Menu import com.badoo.ribs.samples.comms_nodes_1.rib.menu.MenuBuilder internal class ContainerChildBuilders( dependency: Container.Dependency ) { private val subtreeDeps = SubtreeDependency(dependency) val menu: MenuBuilder = MenuBuilder(subtreeDeps) val child1: Child1Builder = Child1Builder(subtreeDeps) val child2: Child2Builder = Child2Builder(subtreeDeps) val child3: Child3Builder = Child3Builder(subtreeDeps) class SubtreeDependency( dependency: Container.Dependency ) : Container.Dependency by dependency, Menu.Dependency, Child1.Dependency, Child2.Dependency, Child3.Dependency } <file_sep>package com.badoo.ribs.rx2.clienthelper.connector import com.jakewharton.rxrelay2.PublishRelay import com.jakewharton.rxrelay2.Relay class NodeConnector<Input, Output>( override val input: Relay<Input> = PublishRelay.create(), override val output: Relay<Output> = PublishRelay.create() ): Connectable<Input, Output> <file_sep>package com.badoo.ribs.tutorials.tutorial2.rib.hello_world.builder import javax.inject.Scope @Scope @Retention(AnnotationRetention.RUNTIME) internal annotation class HelloWorldScope <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1 import com.badoo.ribs.core.Rib import com.badoo.ribs.core.customisation.RibCustomisation interface SimpleRoutingChild1 : Rib { interface Dependency { val title: String } class Customisation( val viewFactory: SimpleRoutingChild1View.Factory = SimpleRoutingChild1ViewImpl.Factory() ) : RibCustomisation } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.routing import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.SimpleRoutingChild1Child1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.builder.SimpleRoutingChild1Child1Builder import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.SimpleRoutingChild1Child2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.builder.SimpleRoutingChild1Child2Builder internal open class SimpleRoutingChild1ChildBuilders( dependency: SimpleRoutingChild1.Dependency ) { private val subtreeDeps = SubtreeDependency(dependency) val child1: SimpleRoutingChild1Child1Builder = SimpleRoutingChild1Child1Builder(subtreeDeps) val child2: SimpleRoutingChild1Child2Builder = SimpleRoutingChild1Child2Builder(subtreeDeps) class SubtreeDependency( dependency: SimpleRoutingChild1.Dependency ) : SimpleRoutingChild1.Dependency by dependency, SimpleRoutingChild1Child1.Dependency, SimpleRoutingChild1Child2.Dependency } <file_sep>package com.badoo.ribs.tutorials.tutorial4.rib.greetings_container import android.os.Parcelable import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.Routing import com.badoo.ribs.routing.resolution.ChildResolution.Companion.child import com.badoo.ribs.routing.resolution.Resolution import com.badoo.ribs.routing.router.Router import com.badoo.ribs.routing.source.RoutingSource import com.badoo.ribs.tutorials.tutorial4.rib.greetings_container.GreetingsContainerRouter.Configuration import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.builder.HelloWorldBuilder import kotlinx.android.parcel.Parcelize class GreetingsContainerRouter( buildParams: BuildParams<Nothing?>, routingSource: RoutingSource<Configuration>, private val helloWorldBuilder: HelloWorldBuilder ): Router<Configuration>( buildParams = buildParams, routingSource = routingSource ) { sealed class Configuration : Parcelable { @Parcelize object HelloWorld : Configuration() } override fun resolve(routing: Routing<Configuration>): Resolution = when (routing.configuration) { is Configuration.HelloWorld -> child { helloWorldBuilder.build(it) } } } <file_sep>package com.badoo.ribs.tutorials.tutorial2.util import android.os.Parcelable import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.core.view.RibView import com.badoo.ribs.routing.source.RoutingSource import com.badoo.ribs.routing.source.backstack.BackStack /** * Helper class for easier migration. * * Suggested to rather extend Interactor, create and inject back stack / other RoutingSource manually. */ abstract class BackStackInteractor<R : Rib, V : RibView, C : Parcelable>( buildParams: BuildParams<*>, val backStack: BackStack<C> ) : Interactor<R, V>( buildParams = buildParams ), RoutingSource<C> by backStack { constructor( buildParams: BuildParams<*>, initialConfiguration: C ) : this( buildParams = buildParams, backStack = BackStack( initialConfiguration = initialConfiguration, buildParams = buildParams ) ) } <file_sep>package com.badoo.ribs.tutorials.tutorial4.rib.hello_world import com.badoo.ribs.android.text.Text import com.badoo.ribs.core.Rib import com.badoo.ribs.tutorials.tutorial4.util.User import io.reactivex.functions.Consumer interface HelloWorld : Rib { interface Dependency { fun user(): User fun config(): Config fun helloWorldOutput(): Consumer<Output> } sealed class Output { object HelloThere : Output() } data class Config( val welcomeMessage: Text ) class Customisation( val viewFactory: HelloWorldView.Factory = HelloWorldViewImpl.Factory() ) } <file_sep>package com.badoo.ribs.tutorials.tutorial1.rib.hello_world import com.badoo.ribs.core.Rib import io.reactivex.functions.Consumer interface HelloWorld : Rib { interface Dependency { fun helloWorldOutput(): Consumer<Output> } sealed class Output { object HelloThere : Output() } class Customisation( val viewFactory: HelloWorldView.Factory = HelloWorldViewImpl.Factory() ) } <file_sep># Routing ## Suggested read ⚠️ Before you proceed, make sure you've read: - [Happy little trees](happy-little-trees.md) ## What's routing? [screenshot – card swiping game]() In this example, we have a bottom menu on this screen with three options: ```My profile```, ```Card swiping game```, ```Messages```. Pressing any of them would show the corresponding screen in the content area. Since we're building our application by building a tree of single-responsibility ```Nodes```, we can represent this with the following structure: [diagram – container]() At any given moment, only one of them can be active though: [diagram – container / anim]() We can go deeper too! The ```Messages``` screen displays either a ```Conversation list```, or – after selecting one of them – a single ```Chat```: [screenshot – connections / list]() [screenshot – connections / chat]() We can represent this with the following ```Node``` structure: [diagram – messages / container]() Using containers in both the above examples allow us to follow a true single responsibility approach: while implementing actual "screens" is delegated to other ```Nodes```, containers keep a single one: deciding when to switch between them. This switching mechanism is what we refer to as routing. ## Combining individual routings The two examples above don't exist in their own vacuum though: they are directly connected. We can only see any of the ```Conversation list``` / ```Chat``` when one level higher, the main screen container switches its routing to show: ```Messages``` [diagram - combined]() In fact, this pattern can be repeated in both directions indefinitely: we can always break up any level to more standalone pieces, and we can put any of the levels as a child under another one serving as a parent: [diagram - app]() Routing a pattern really starts to shine when we start to describe the whole application state with it. ## Routing: a piece of navigation as a local concern Routing is an alternative to a global navigation pattern: instead, navigation is broken up to "local pieces", without wanting to know too much about the rest of the application. This, among other things, also solves an age old problem of navigation in a shared module world, where shared modules shouldn't have to know about the hosting application. If navigation is a local concern, then only the direct next "piece" of it needs to present itself as a dependency! ## Navigation represented as state Routing describes the state of local navigation in your tree of Nodes. The combination of these local, stateful navigation concerns uniquely describes the state of your whole application. In RIBs, routing is both stateful and persistent, automatically handled by the framework. <file_sep>package com.badoo.ribs.sandbox.rib.compose_parent.routing import android.os.Parcelable import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.Routing import com.badoo.ribs.routing.resolution.ChildResolution.Companion.child import com.badoo.ribs.routing.resolution.Resolution import com.badoo.ribs.routing.router.Router import com.badoo.ribs.routing.source.RoutingSource import com.badoo.ribs.routing.transition.handler.TransitionHandler import com.badoo.ribs.sandbox.rib.compose_parent.routing.ComposeParentRouter.Configuration import com.badoo.ribs.sandbox.rib.compose_parent.routing.ComposeParentRouter.Configuration.Permanent.ComposeLeaf import kotlinx.android.parcel.Parcelize class ComposeParentRouter internal constructor( buildParams: BuildParams<*>, private val builders: ComposeParentChildBuilders, transitionHandler: TransitionHandler<Configuration>? = null ): Router<Configuration>( buildParams = buildParams, routingSource = RoutingSource.permanent(ComposeLeaf), transitionHandler = transitionHandler ) { sealed class Configuration : Parcelable { sealed class Permanent : Configuration() { @Parcelize object ComposeLeaf : Permanent() } } override fun resolve(routing: Routing<Configuration>): Resolution = with(builders) { when (routing.configuration) { is ComposeLeaf -> child { composeLeaf.build(it) } } } } <file_sep>package com.badoo.ribs.samples.dialogs.rib.dialogs_example import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.samples.dialogs.dialogs.Dialogs import com.badoo.ribs.samples.dialogs.rib.dialogs_example.DialogsRouter.Configuration.Content class DialogsBuilder( private val deps: DialogsExample.Dependency ) : SimpleBuilder<DialogsExample>() { private val dialogs = Dialogs() override fun build(buildParams: BuildParams<Nothing?>): DialogsExample { val backStack: BackStack<DialogsRouter.Configuration> = BackStack( initialConfiguration = Content.Default, buildParams = buildParams ) val presenter = DialogsPresenterImpl(dialogs, backStack) val router = DialogsRouter( buildParams = buildParams, routingSource = backStack, dialogLauncher = deps.dialogLauncher, dialogs = dialogs ) val viewDependencies = object : DialogsView.Dependency { override val presenter: DialogsPresenter = presenter } return DialogsNode( buildParams = buildParams, viewFactory = DialogsViewImpl.Factory().invoke(viewDependencies), plugins = listOf(router, presenter) ) } } <file_sep>version = VERSION_NAME group = GROUP def getReleaseRepositoryUrl() { return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" } def getSnapshotRepositoryUrl() { return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL : "https://oss.sonatype.org/content/repositories/snapshots/" } apply plugin: "com.vanniktech.maven.publish" mavenPublish { targets { uploadArchives { releaseRepositoryUrl = getReleaseRepositoryUrl() snapshotRepositoryUrl = getSnapshotRepositoryUrl() } } } project.afterEvaluate { project.tasks.named("androidSourcesJar").configure { from project.android.sourceSets.main.java.srcDirs } project.tasks.register("install").configure { task -> task.dependsOn("installArchives") } } <file_sep>package com.badoo.ribs.samples.back_stack.rib.parent import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.routing.source.backstack.BackStack import com.badoo.ribs.samples.back_stack.rib.parent.routing.ParentChildBuilders import com.badoo.ribs.samples.back_stack.rib.parent.routing.ParentRouter import com.badoo.ribs.samples.back_stack.rib.parent.routing.ParentRouter.Configuration import com.badoo.ribs.samples.back_stack.rib.parent.routing.ParentRouter.Configuration.Content class ParentBuilder( private val dependency: Parent.Dependency ) : SimpleBuilder<Parent>() { private val builders by lazy { ParentChildBuilders(dependency) } override fun build(buildParams: BuildParams<Nothing?>): Parent { val backStack = backStack(buildParams) val router = router(buildParams, backStack) val presenter = presenter(backStack) val viewDependency = object : ParentView.Dependency { override val presenter: ParentPresenter = presenter } return ParentNode( buildParams = buildParams, viewFactory = ParentViewImpl.Factory().invoke(viewDependency), plugins = listOfNotNull( router, presenter ) ) } private fun backStack(buildParams: BuildParams<Nothing?>): BackStack<Configuration> = BackStack( buildParams = buildParams, initialConfiguration = Content.A ) private fun router( buildParams: BuildParams<Nothing?>, backStack: BackStack<Configuration> ): ParentRouter = ParentRouter( buildParams = buildParams, routingSource = backStack, builders = builders ) private fun presenter(backStack: BackStack<Configuration>): ParentPresenterImpl = ParentPresenterImpl(backStack) } <file_sep>package com.badoo.ribs.test import android.os.Parcelable sealed class TestConfiguration : Parcelable <file_sep>package com.badoo.ribs.tutorials.tutorial4.rib.greetings_container import com.badoo.ribs.core.Rib import com.badoo.ribs.tutorials.tutorial4.util.User import io.reactivex.functions.Consumer interface GreetingsContainer : Rib { interface Dependency { fun user(): User fun greetingsContainerOutput(): Consumer<Output> } sealed class Output { data class GreetingsSaid(val greeting: String) : Output() } } <file_sep>package com.badoo.ribs.samples.dialogs.rib.dialogs_example import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.core.plugin.Plugin import com.badoo.ribs.core.view.ViewFactory internal class DialogsNode( buildParams: BuildParams<*>, viewFactory: ViewFactory<DialogsView>, plugins: List<Plugin> ) : Node<DialogsView>( buildParams = buildParams, viewFactory = viewFactory, plugins = plugins ), DialogsExample <file_sep>package com.badoo.ribs.test import android.os.Bundle import androidx.test.rule.ActivityTestRule import com.badoo.ribs.RibTestActivity import com.badoo.ribs.core.Rib import org.junit.runner.Description import org.junit.runners.model.Statement open class RibsRule( builder: ((RibTestActivity, Bundle?) -> Rib)? = null ): ActivityTestRule<RibTestActivity>( RibTestActivity::class.java, true, builder != null ) { init { RibTestActivity.ribFactory = builder } fun start(ribFactory: ((RibTestActivity, Bundle?) -> Rib)) { RibTestActivity.ribFactory = ribFactory launchActivity(null) } override fun apply(base: Statement, description: Description?): Statement = super.apply(object : Statement() { override fun evaluate() { try { base.evaluate() } finally { RibTestActivity.ribFactory = null } } }, description) } <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.parent import android.view.ViewGroup import android.widget.Button import androidx.annotation.LayoutRes import com.badoo.ribs.core.Node import com.badoo.ribs.core.customisation.inflate import com.badoo.ribs.core.view.AndroidRibView import com.badoo.ribs.core.view.RibView import com.badoo.ribs.core.view.ViewFactory import com.badoo.ribs.core.view.ViewFactoryBuilder import com.badoo.ribs.samples.transitionanimations.R interface ParentView : RibView { interface Factory : ViewFactoryBuilder<Dependency, ParentView> interface Dependency { val presenter: ParentPresenter } } class ParentViewImpl private constructor( override val androidView: ViewGroup, private val presenter: ParentPresenter ) : AndroidRibView(), ParentView { class Factory( @LayoutRes private val layoutRes: Int = R.layout.rib_parent ) : ParentView.Factory { override fun invoke(deps: ParentView.Dependency): ViewFactory<ParentView> = ViewFactory { ParentViewImpl( androidView = it.inflate(layoutRes), presenter = deps.presenter ) } } private val nextButton: Button = androidView.findViewById(R.id.next_button) private val container: ViewGroup = androidView.findViewById(R.id.container) init { nextButton.setOnClickListener { presenter.goToNext() } } override fun getParentViewForSubtree(subtreeOf: Node<*>): ViewGroup = container } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.builder import com.badoo.ribs.android.text.Text import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.R import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainer import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainerInteractor import com.badoo.ribs.tutorials.tutorial5.rib.greetings_container.GreetingsContainerRouter import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.HelloWorld import com.badoo.ribs.tutorials.tutorial5.rib.hello_world.builder.HelloWorldBuilder import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector import dagger.Provides import io.reactivex.ObservableSource import io.reactivex.functions.Consumer @dagger.Module internal object GreetingsContainerModule { @GreetingsContainerScope @Provides @JvmStatic internal fun router( // pass component to child rib builders, or remove if there are none component: GreetingsContainerComponent, buildParams: BuildParams<Nothing?>, interactor: GreetingsContainerInteractor ): GreetingsContainerRouter = GreetingsContainerRouter( buildParams = buildParams, helloWorldBuilder = HelloWorldBuilder(component), routingSource = interactor ) @GreetingsContainerScope @Provides @JvmStatic internal fun interactor( buildParams: BuildParams<Nothing?>, output: Consumer<GreetingsContainer.Output> ): GreetingsContainerInteractor = GreetingsContainerInteractor( buildParams = buildParams, output = output ) @GreetingsContainerScope @Provides @JvmStatic internal fun lexemes(): List<@JvmSuppressWildcards Text> = listOf( Text.Plain("Hello"), Text.Plain("Grüss gott"), Text.Plain("Bonjour"), Text.Plain("Hola"), Text.Plain("Szép jó napot"), Text.Plain("Góðan dag") ) @GreetingsContainerScope @Provides @JvmStatic internal fun node( buildParams: BuildParams<Nothing?>, router: GreetingsContainerRouter, interactor: GreetingsContainerInteractor ) : Node<Nothing> = Node<Nothing>( buildParams = buildParams, viewFactory = null, plugins = listOf(interactor, router) ) @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldConfig( options: @JvmSuppressWildcards List<Text> ): HelloWorld.Config = HelloWorld.Config( welcomeMessage = Text.Resource(R.string.hello_world_welcome_text), buttonText = options.first() ) @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldOutputConsumer( interactor: GreetingsContainerInteractor ) : Consumer<HelloWorld.Output> = interactor.helloWorldOutputConsumer @GreetingsContainerScope @Provides @JvmStatic internal fun helloWorldInputSource( interactor: GreetingsContainerInteractor ) : ObservableSource<HelloWorld.Input> = interactor.helloWorldInputSource @GreetingsContainerScope @Provides @JvmStatic internal fun moreOptionsConfig( options: @JvmSuppressWildcards List<Text> ): OptionSelector.Config = OptionSelector.Config( options = options ) @GreetingsContainerScope @Provides @JvmStatic internal fun moreOptionsOutput( interactor: GreetingsContainerInteractor ): Consumer<OptionSelector.Output> = interactor.optionsSelectorOutputConsumer } <file_sep># Tutorial #1 ## Before you start 1. Clone the repo: ``` git clone https://github.com/badoo/RIBs ``` 2. Open the project in Android Studio ## The goal of this tutorial Building and attaching an existing RIB to an integration point. Hello world! ## How an app using RIBs is structured 1. There's one or more integration points in the form of `Activities` / `Fragments` / etc. Ideally the app should be single-Activity, but the library makes no difference about it. 2. Integration points build a `Node` (can be any `Node`), and attach it to themselves, propagating all lifecycle methods to it. This `Node` will be the root. 3. A tree structure of `Node`s represent the application's business logic state. 4. A tree structure of `View`s represent the application on the view level. This tree is not necessarily the same as the `Node` tree, as `Node`s do not necessarily have their own views, or might be attached to a different place in the view tree (dialogs). We'll see examples about these later. ## How a RIB is structured Open up the `tutorial1` module, which has a single RIB in the `com.badoo.ribs.tutorials.tutorial1.rib.hello_world` package. It contains a bunch of classes and packages, where to start? The immediate go-to when checking out any RIB you are not familiar with, is the **main interface** of the RIB, which serves as the documentation of its public API. In Badoo RIBs, this main interface always has the name of the RIB itself without any suffix, and you can find it in the root of the package. An example of such a public interface typically looks like: ```kotlin interface ExampleRib : Rib { interface Dependency : Rib.Dependency { fun exampleRibInput(): ObservableSource<Input> fun exampleRibOutput(): Consumer<Output> // + other dependencies } sealed class Input { // possible Inputs } sealed class Output { // possible Outputs } class Customisation( val viewFactory: ViewFactory<HelloWorldView> = inflateOnDemand( R.layout.rib_hello_world ) ) } ``` ### Dependencies Here, the `Dependency` interface describes all external dependencies this RIB needs to be built. RIBs act as a black box that can be plugged in anywhere. This means, that as long as you can provide their dependencies, you can build them, and they are supposed to be auto-wired and ready to go immediately without any further actions. ### Inputs and Outputs RIBs can also have `Inputs` / `Outputs`. These represent the way we can communicate with them, and they are always defined as part of the public API. We'll see this in practical examples, but for now, the only things that matter, is that: - if a RIB has `Input`, then it also has a dependency of `ObservableSource<Input>` - if a RIB has `Output`, then it also has a dependency of `Consumer<Output>` This is important to satisfy the plug-and-play functionality of the RIB. Every RIB implementation guarantees that as long as you can give it a source of its `Inputs` that it can observe, and a consumer of its possible `Outputs` that will handle them, it will do all the required wiring internally, and will "just work" out of the box. ## Getting our hands dirty Enough theory, let's get down to the practical details, and check out `HelloWorld` interface: ```kotlin package com.badoo.ribs.tutorials.tutorial1.rib.hello_world interface HelloWorld : Rib { interface Dependency { fun helloWorldOutput(): Consumer<Output> } sealed class Output { object HelloThere : Output() } class Customisation( val viewFactory: ViewFactory<HelloWorldView> = inflateOnDemand( R.layout.rib_hello_world ) ) } ``` The new thing here is the `Customisation` part, but we'll talk about that in other tutorials. For now, it's enough to understand that this RIB will have a default view inflated from `R.layout.rib_hello_world`. This RIB does not have any `Inputs`, and it has only one possible `Output`: `HelloThere`. Following from what we said above, this also means that it has a dependency of someone to consume this `Output`. It has no other dependencies, so as long as we can give it a `Consumer`, we can build it! Let's take it for a test run! Open up `RootActivity` in the `tutorial1` module: ```kotlin /** The tutorial app's single activity */ class RootActivity : RibActivity() { /* remainder omitted */ override fun createRib(savedInstanceState: Bundle?): Node<*> = TODO("Create HelloWorldBuilder, supply dependencies in constructor, return built Node") } ``` This `Activity` extends the `RibActivity` class from the library, which is just a convenience class to forward all lifecycle methods to a single root RIB. It has an abstract method `createRib(): Node<*>` which we need to implement here. To do this, we first need to create an instance of `HelloWorldBuilder`. Opening this class we can see that it indeed needs an instance of the `Dependency` interface defined in the public API of the RIB: ```kotlin class HelloWorldBuilder(dependency: HelloWorld.Dependency) { /* remainder omitted */ fun build(buildContext: BuildContext.Params): Node<HelloWorldView> { /* remainder omitted */ } } ``` And also that it has a `build` method which will give us the `Node` object we need to return from the `createRib()` method. So let's do that! ```kotlin /** The tutorial app's single activity */ class RootActivity : RibActivity() { /* remainder omitted */ override fun createRib(savedInstanceState: Bundle?): Node<*> = HelloWorldBuilder( object : HelloWorld.Dependency { override fun helloWorldOutput(): Consumer<HelloWorld.Output> = Consumer { // not sure what to do here yet } } ).build(BuildContext.root(savedInstanceState)) } ``` Now the project should compile. Build it, and we should see this screen: ![](https://i.imgur.com/c2fUEHO.png) And checking the view hierarchy, this is what we should see: [![View hierarchy of HelloWorld RIB](https://i.imgur.com/cf2gi9N.png)](https://i.imgur.com/Xkh2XmP.png) So indeed, that button we see is coming from the RIB we built! Yay! Now this doesn't do to much. So let's change the `Consumer` dependency that we pass to the `Builder` so that it displays a Snackbar: ```kotlin override fun createRib(savedInstanceState: Bundle?): Node<*> = HelloWorldBuilder( object : HelloWorld.Dependency { override fun helloWorldOutput(): Consumer<HelloWorld.Output> = Consumer { Snackbar.make(rootViewGroup, "Hello world!", Snackbar.LENGTH_SHORT).show() } } ).build( // You only ever need to supply this info manually at your root RIB // All other children get it from the framework BuildContext.Params( ancestryInfo = AncestryInfo.Root, savedInstanceState = savedInstanceState ) ) ``` Build and deploy the app, and pressing the button this is what we should see: ![](https://i.imgur.com/F5GEBpw.png) As promised, beyond providing the required dependencies, we did not need to make any additional wiring - the HelloWorld RIB takes care of the setup that makes the button click invoke the lambda that we passed in. ## 🎉 🎉 🎉 Congratulations 🎉 🎉 🎉 You just built your first RIB! You can advance to the next tutorial, or continue reading for some additional understanding of the internals. ## Further reading - internals of the HelloWorld RIB If we want to understand *why* pressing the button on the UI actually invokes showing the Snackbar, we'll have to check some other classes in the `hello_world` package, too. ### The View Let's start from the view side, and open up `HelloWorldView`. We see an interface and an implementation of it. Let's start with the interface: ```kotlin interface HelloWorldView : RibView, ObservableSource<Event>, Consumer<ViewModel> { sealed class Event { object ButtonClicked : Event() } /* remainder omitted */ } ``` Views (as well as other components in RIBs) are reactive. This `HelloWorldView` interface states that any implementation of the view is a source of `Events` (here a single one for `ButtonClicked`) and a consumer of `ViewModels` (which we are not using now). ### The View implementation You can check in the Android view implementation right below the interface how this is done: ```kotlin class HelloWorldViewImpl( /* remainder omitted */ ) { /* remainder omitted */ private val button: Button by lazy { findViewById<Button>(R.id.hello_world_button) } override fun onFinishInflate() { super.onFinishInflate() button.setOnClickListener { events.accept(Event.ButtonClicked) } } /* remainder omitted */ } ``` Any click on the button with the id `R.id.hello_world_button` will result in the associated `ButtonClicked` event being published. The `View` itself never cares for how a certain UI interaction affects anything related to business logic. It only renders `ViewModels`, and triggers `Events` based on the user interaction. So where is this event being used? ### Connecting the dots Open up `HelloWorldInteractor`, which is responsible for connecting different parts of business logic: ```kotlin class HelloWorldInteractor( /* remainder omitted */ private val output: Consumer<HelloWorld.Output> /* remainder omitted */ ) { override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { viewLifecycle.startStop { bind(view to output using ViewEventToOutput) } } } ``` The only important parts are that: 1. This class receives `output` in its constructor. This is the object that we required when we declared the RIB's dependencies - the consumer which knows how to react to our `Output` event -, and is passed here via dependency injection. If you are familiar with Dagger, you can check `HelloWorldComponent` and `HelloWorldModule` classes in the `builder` package to see how. 2. The maybe strange looking syntax in onViewCreated is a lifecycle-scoped binding between two reactive endpoints. Here, these two endpoints are the `view` (reactive source of `HelloWorldView.Event`) and the `output` (reactive consumer of HelloWorld.Output), and the scope of the binding is a START-STOP cycle. As the two endpoints have different types, the binding uses a simple mapper `ViewEventToOutput` found in the `mapper` package. In this implementation it provides a simple 1:1 mapping between the two types: ```kotlin object ViewEventToOutput : (HelloWorldView.Event) -> HelloWorld.Output { override fun invoke(event: HelloWorldView.Event): HelloWorld.Output = when (event) { HelloWorldView.Event.ButtonClicked -> Output.HelloThere } } ``` ### Sidenote ### Badoo RIBs uses [MVICore](https://github.com/badoo/MVICore) both under the hood and in RIB implementations for state machines as well as providing the tools to connect reactive components. Both the `viewLifecycle.startStop` and the `bind(view to output using ViewEventToOutput)` parts come from the library. You can check out its [documentation](https://github.com/badoo/MVICore) for more information about these topics. ### To sum it up ### 1. The default view is inflated from `R.layout.rib_hello_world` (defined in main interface), which gives us an instance of `HelloWorldViewImpl` 2. `HelloWorldViewImpl` finds a button in the view hierarchy by id 3. An onClickListener is set on it that will trigger publishing an `Event` defined in `HelloWorldView` interface 4. Interactor will: 1. take `HelloWorldView` as a reactive output 2. transforms elements coming from it using a mapper 3. connect this transformed stream of `Output` events to the output consumer (which we got from our dependencies) The result is a clear separation of concerns. View implementation doesn't care what the event will trigger, and even the whole RIB doesn't care what should happen once a certain `Output` is triggered. You can integrate this same RIB in different places, and provide a `Consumer` dependency that shows a Snackbar in one place, and one that shows a Toast in another. <file_sep>package com.badoo.ribs.tutorials.tutorial4.rib.hello_world import androidx.lifecycle.Lifecycle import com.badoo.mvicore.android.lifecycle.startStop import com.badoo.mvicore.binder.using import com.badoo.ribs.android.text.Text import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial4.R import com.badoo.ribs.tutorials.tutorial4.rib.hello_world.mapper.ViewEventToOutput import com.badoo.ribs.tutorials.tutorial4.util.User import io.reactivex.functions.Consumer class HelloWorldInteractor( user: User, config: HelloWorld.Config, private val output: Consumer<HelloWorld.Output>, buildParams: BuildParams<Nothing?> ) : Interactor<HelloWorld, HelloWorldView>( buildParams = buildParams ) { override fun onViewCreated(view: HelloWorldView, viewLifecycle: Lifecycle) { super.onViewCreated(view, viewLifecycle) view.accept(initialViewModel) viewLifecycle.startStop { bind(view to output using ViewEventToOutput) } } private val initialViewModel = HelloWorldView.ViewModel( titleText = Text.Resource(R.string.hello_world_title, user.name()), welcomeText = config.welcomeMessage ) } <file_sep>package com.badoo.ribs.samples.retained_instance_store.rib.retained_instance_example import com.badoo.ribs.core.Rib interface RetainedInstanceExample : Rib<file_sep># Base concepts ## Terminology This section contains the suggested knowledge before starting with the tutorials. Don't worry if not everything is clear, you will get the "Aha!" moment along the way. ### RIB A self-contained black box of business logic along with its view. RIB as a word refers to this conceptual unit as a whole, not a class. On the practical level, RIBs have the following main components: `Builder`, `Node`, `Router`, `Interactor`, `View` (optional). ### Builder A class responsible for the building operation: `(Dependencies) -> Node`. ### Node The physical embodiment of a RIB, the actual result of the `Builder`'s build operation. A `Node` is responsible for: - implementing the lifecycle of the RIB as a whole - keeping reference to its immediate child `Node`s + propagating lifecycle methods to them - implementing all tree operations (attach/detach child and child view) automatically ### Router Implements high-level routing logic by: - defining a set of possible configurations the RIB can be in - resolving those configurations to `RoutingActions`, such as (but not limited to) attaching another `Node` as a child - maintains an automatically persisted back stack of configurations, and offers and API to manipulate it (operations like push, pop, etc.) ### Interactor Implements business logic: - connects reactive pieces (e.g state machines, view, inputs and outputs of children) - can set the RIB in any pre-defined configuration via calling on operations offered by `Router` ### View Reponsible for rendering a ViewModel and triggering events, nothing more. Since it's just an interface, can also be customised or mocked when testing. <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView class OptionSelectorBuilder( private val dependency: OptionSelector.Dependency ) : SimpleBuilder<Node<OptionSelectorView>>() { override fun build(buildParams: BuildParams<Nothing?>): Node<OptionSelectorView> = DaggerOptionSelectorComponent .factory() .create( buildParams = buildParams, dependency = dependency, customisation = OptionSelector.Customisation() ) .node() } <file_sep># Jetpack Compose support RIBs support Jetpack Compose! ## Dependencies All artifacts should be available from jitpack with a `-compose` suffix too. See [Module dependencies](../setup/deps.md) ## Building the project locally If you'd like to play around in this repo, add this flag in your `local.properties`, then hit gradle sync: ``` useCompose=true ``` What you get: - Some new modules enabled (you can check `settings.gradle` to see which) - Compose-based implementation of `RibView`: `ComposeRibView` - Demo in `sandbox` app <file_sep>package com.badoo.ribs.samples.transitionanimations.rib.child1 import com.badoo.ribs.core.Rib interface Child1 : Rib <file_sep>package com.badoo.ribs.samples.simplerouting.app import android.os.Bundle import android.view.ViewGroup import com.badoo.ribs.android.RibActivity import com.badoo.ribs.core.Rib import com.badoo.ribs.core.modality.BuildContext import com.badoo.ribs.samples.simplerouting.rib.simple_routing_parent.SimpleRoutingParent import com.badoo.ribs.samples.simplerouting.rib.simple_routing_parent.builder.SimpleRoutingParentBuilder class RootActivity : RibActivity() { override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_root) super.onCreate(savedInstanceState) } override val rootViewGroup: ViewGroup get() = findViewById(R.id.root) override fun createRib(savedInstanceState: Bundle?): Rib = SimpleRoutingParentBuilder( object : SimpleRoutingParent.Dependency {} ).build( BuildContext.root(savedInstanceState) ) } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.RadioButton import android.widget.RadioGroup import androidx.annotation.LayoutRes import com.badoo.ribs.core.view.RibView import com.badoo.ribs.core.view.ViewFactoryBuilder import com.badoo.ribs.core.customisation.inflate import com.badoo.ribs.tutorials.tutorial5.R import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView.Event import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView.ViewModel import com.badoo.ribs.android.text.Text import com.badoo.ribs.core.view.AndroidRibView import com.badoo.ribs.core.view.ViewFactory import com.jakewharton.rxrelay2.PublishRelay import io.reactivex.ObservableSource import io.reactivex.functions.Consumer interface OptionSelectorView : RibView, ObservableSource<Event>, Consumer<ViewModel> { sealed class Event data class ViewModel( val options: List<Text> ) interface Factory : ViewFactoryBuilder<Nothing?, OptionSelectorView> } class OptionSelectorViewImpl private constructor( override val androidView: ViewGroup, private val events: PublishRelay<Event> = PublishRelay.create() ) : AndroidRibView(), OptionSelectorView, ObservableSource<Event> by events, Consumer<ViewModel> { class Factory( @LayoutRes private val layoutRes: Int = R.layout.rib_option_selector ) : OptionSelectorView.Factory { override fun invoke(deps: Nothing?): ViewFactory<OptionSelectorView> = ViewFactory { OptionSelectorViewImpl( it.inflate(layoutRes) ) } } private val radioGroup: RadioGroup = androidView.findViewById(R.id.more_options_radio_group) private val confirmButton: Button = androidView.findViewById(R.id.more_options_confirm_selection) init { // TODO set click listener on confirmButton that will emit ConfirmButtonClicked // hint: use radioGroup.checkedIndex to set the value of ConfirmButtonClicked.selectionIndex } private val RadioGroup.checkedIndex: Int get() { val checkedRadio = findViewById<RadioButton>(checkedRadioButtonId) return indexOfChild(checkedRadio) } override fun accept(vm: ViewModel) { createRadios(vm.options) } private fun createRadios(options: List<Text>) { radioGroup.removeAllViews() options.forEachIndexed { idx, lexem -> RadioButton(androidView.context).apply { text = lexem.resolve(context) id = View.generateViewId() radioGroup.addView(this) isChecked = idx == 0 } } } } <file_sep># Tutorial #5 ## The goal of this tutorial Understanding how to dynamically switch between child RIBs ## Starting out ![](https://i.imgur.com/TIfGFtw.png) Launch the **tutorial5** app, and you can see that there's a new button in the layout: **MORE OPTIONS**. If you look at the project structure, you can also find a new RIB in this module: `OptionSelector`. All it does is it renders a screen with text options and a confirm button. We will use that to update the button text in our `HelloWorld` rib, and also use it for the actual greeting shown in the Snackbar. ![](https://i.imgur.com/hz7ZXlQ.png) ## Hiererachy of multi-child RIBs We had this hiearachy so far: ``` GreetingsContainer └── HelloWorld ``` And now we'll add `OptionsSelector` as the second child of `GreetingsContainer`: ``` GreetingsContainer ├── HelloWorld └── OptionsSelector ``` The idea how they will work together: 1. On `HelloWorld` screen, User presses **MORE OPTIONS**. Since it is beyond the responsibility of `HelloWorld` RIB, it reports it as `Output` 2. `GreetingsContainer` catches the output, and switches its routing from `HelloWorld` to `OptionsSelector`. Since we display the container on the whole screen, this results in a "new screen" effect. 3. `OptionsSelector` offers UI interaction to select something from a radio group. What should happen when a certain options is selected is beyond its responsibilities, so similarly as with `HelloWorld`, it reports it as `Output`. 4. `GreetingsContainer` catches the output, switches back its routing to `HelloWorld` again. 5. The text of the main button in `HelloWorld` should be updated to reflect the newly selected option. This can be done by via an `Input` command to `HelloWorld` which allows setting of the text from outside of the RIB. ## Test your knowledge By now you should be able to: 1. Trigger a new event from the UI that reaches the parent as `Output` 1. Add a new element to `Output` in `HelloWorld` called `ShowMoreOptions` 2. Add a new element to `Event` in `HelloWorldView` called `MoreOptionsButtonClicked` 3. In `HelloWorldView`, set a click listener on `moreOptionsButton` that will publish `MoreOptionsButtonClicked` 4. Add the transformation between `Event` and `Output` in the `viewEventToOutput` transformer 5. React to this new output in `GreetingsContainerInteractor`. Leave the actual implementation a `TODO()` 2. Add `OptionSelector` RIB as a child of `GreetingsContainer`. This involves: 1. making `GreetingsContainerComponent` extend child dependency interface 1. satisfying child dependencies (prepared for you in `GreetingsContainerModule`) 2. providing `optionsSelectorBuilder` to the `GreetingsContainerRouter` 3. adding a new Configuration to `GreetingsContainerRouter`: "OptionsSelector" 4. resolving it to an `child { optionsSelectorBuilder.build() }` action For help with the above tasks, you can refer to: - **tutorial1** / **Further reading** section on how to make a Button trigger an `Output` - **tutorial2** / **Summary** section on how to add a child RIB to a parent - **tutorial4** on commnunication with child RIBs, i.e. `Inputs` / `Outputs` ## Implement routing Right now: 1. our new Button can signal the correct `Output` 2. the container's `Router` can build the other RIB we need The only thing we need is to connect the dots, so that `1.` actually triggers doing `2.` Business logic triggers routing: 1. in `GreetingsContainerInteractor` we consume the `Output` of `HelloWorld` 2. in the `when` branch for the new `Output` (where we added a `TODO()`) we want to tell `GreetingsContainerRouter` to switch to the Configuration representing `OptionSelector` RIB. All we need to do is: ```kotlin class GreetingsContainerInteractor // ... internal val helloWorldOutputConsumer: Consumer<HelloWorld.Output> = Consumer { when (it) { HelloThere -> output.accept(GreetingsSaid("Someone said hello")) ShowMoreOptions -> router.push(Configuration.OptionsSelector) } } } ``` Pressing the **MORE OPTIONS** button the app should display the new screen: ![](https://i.imgur.com/s0Udusa.png) Try it! Right now the only way of getting back to `HelloWorld` is to press back on the device. We'll address that soon. ## Explanation: the back stack Why did the above work? All `Routers` have a routing back stack. By default, this back stack has a single element: ``` back stack = [(initial configuration)] ``` This is the one you set in your `Router`. In `GreetingsContainerRouter` this reads: ```kotlin class GreetingsContainerRouter( // ... initialConfiguration = Configuration.HelloWorld ) ``` So our default back stack was in fact: ``` back stack = [*Configuration.HelloWorld] ``` A configuration can be either **active**/**inactive**. In simple terms, it's **active** if it's on screen. A simplified rule of the back stack is that only the last configuration is **active**. We'll mark this with an asterisk (*) from now on. `Router` offers you operations to manipulate this back stack. ```kotlin fun push(configuration: Content) fun popBackStack(): Boolean ``` There are other operations too, but we'll discuss them later in other tutorials. What's important is that `push` adds a new element to the end of the back stack, while `popBackStack` removes the last one from the end. So when we did ```router.push(Configuration.OptionsSelector)```, this happened: ``` back stack 0 = [*Configuration.HelloWorld] // push back stack 1 = [Configuration.HelloWorld, *Configuration.OptionsSelector] ``` And because we just said that the last element in the back stack is **active** (on screen), this means that the view of `HelloWorld` gets detached, and `OptionsSelector` gets created and attached. ## Back pressing and the back stack The reverse is happening when we pressed back. By default, back pressing is propagated to the deepest **active** levels of the RIB tree by default, where each RIB has a chance to react to it: 1. `Interactor` has a chance to override `handleBackPress()` to do something based on business logic 2. `Router` will be asked if it has back stack to pop. If yes, pop is triggered and nothing else is done. 3. If `Router` had only one more configuration left in its back stack, there's nothing more to remove. The whole thing starts bubbling up the RIB tree to higher levels until one of the levels can handle it (points 1 and 2). If it is handled, the propagation stops. 4. If the whole RIB tree didn't handle the back press, then the last fallback is the Android environment (in practice this probably means that the hosting `Activity` finishes). In our case, when we were on the `OptionsSelector` screen, `GreetingsContainerRouter` had 2 elements in its back stack, so it could automatically handle the back press event by popping the latest: ``` back stack 0 = [*Configuration.HelloWorld] // push back stack 1 = [Configuration.HelloWorld, *Configuration.OptionsSelector] // back press back stack 2 = [*Configuration.HelloWorld] ``` And again, because last element in the back stack is on screen, this means that `OptionsSelector` gets detached, and `HelloWorld` gets attached back to the screen again. ## Almost there: use the result from options screen Of course there's no point of opening the second screen if we cannot interact with it and our only option is to press back. So let's make it a bit more useful: 1. Add a new element to `Output` in `OptionsSelector`: ```data class OptionSelected(val text: Text) : Output()``` 2. Add a new element to `Event` in `OptionsSelectorView`: ```data class ConfirmButtonClicked(val selectionIndex: Int) : Event()``` 3. In `OptionsSelectorViewImpl`, add a click listener on `confirmButton` that will trigger this event. 4. Go to `OptionSelectorInteractor`. Add the transformation between `Event` and `Output` in the `viewEventToOutput` transformer. 5. Go to `GreetingsContainerInteractor`, and add a branch to the `when` expression in `moreOptionsOutputConsumer` What we want to do is: - Take the `Text` that's coming in the `Output` - Feed it to `HelloWorld` using an Input of `UpdateButtonText` - Actually go back one screen = manually popping the back stack This is how it might look: ```kotlin internal val optionsSelectorOutputConsumer: Consumer<OptionSelector.Output> = Consumer { when (it) { is Output.OptionSelected -> { router.popBackStack() helloWorldInputSource.accept( UpdateButtonText(it.text) ) } } } ``` ## Test run! At this point we should be able to go to options selection screen, chose an item from the radio group, and pressing the confirm button we should land back at the Hello world! screen with the label of the hello button reflecting our choice. ![](https://i.imgur.com/j9ZDpDN.png) Press the button! ![](https://i.imgur.com/8HXzhog.png) ## Reflecting on what we just did: composing We just created more complex functionality by a composition of individually simple pieces! When we created our hierarchy like this, we kept the two children decoupled from each other: ``` GreetingsContainer ├── HelloWorld └── OptionsSelector ``` Even though they work together as a system, `HelloWorld` and `OptionsSelector` has no dependency on each other at all. This is actually beneficial, because: - `OptionsSelector` is a generic screen (it renders *whatever* text options we build it with) - From the perspective of `HelloWorld` it really shouldn't care where it gets its other greetings Keeping them decoupled means: - `OptionsSelector` can be reused freely elsewhere to render the same screen with other options - `HelloWorld` can be reused with different implementation details how to provide more options to it The combined functionality we just implemented emerges out of the composition of these pieces inside `GreetingsContainer`. Each level handles only its immediate concerns: - `HelloWorld` implements hello functionality and can ask for more options - `OptionsSelector` renders options and signals selection - `GreetingsContainer` connects the dots and contains only coordination logic. All other things are delegated to child screens as implementation details. ## Tutorial complete Congratulations! You can advance to the next one. ## Summary **Dynamic routing** 1. Make the parent RIB be able to build a child RIB (as seen in **tutorial2**): 1. Add configuration & routing action in Router 2. Provide child `Builder` via DI 2. React to some event (usually to child `Output` as seen in **tutorial4**, but can be anything else) in `Interactor` of parent RIB by pushing new configuration to its `Router` 3. Use back press or `popBackStack()` programmatically to go back **Composing functionality** 1. Instead of one messy RIB, map complex functionality to a composition of simple, single responsibility RIBs 2. When composing, keep parent levels simple. They should only coordinate between child RIBs by `Inputs`/`Outputs`, and delegate actual functionality to children as implementation details. 3. Sibling RIBs on the same level should not depend on each other, so that they can be easily reused elsewhere. <file_sep>package com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.Node import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial2.rib.greetings_container.GreetingsContainer class GreetingsContainerBuilder( private val dependency: GreetingsContainer.Dependency ) : SimpleBuilder<Node<Nothing>>() { override fun build(buildParams: BuildParams<Nothing?>): Node<Nothing> { val component = DaggerGreetingsContainerComponent.factory() .create( dependency = dependency, buildParams = buildParams ) return component.node() } } <file_sep>package com.badoo.ribs.core.customisation import com.badoo.ribs.core.Rib import kotlin.reflect.KClass interface RibCustomisationDirectory { val parent: RibCustomisationDirectory? fun <T : Rib> getSubDirectory(key: KClass<T>) : RibCustomisationDirectory? fun <T : Rib> getSubDirectoryOrSelf(key: KClass<T>) : RibCustomisationDirectory fun <T : RibCustomisation> get(key: KClass<T>) : T? fun <T : RibCustomisation> getRecursively(key: KClass<T>) : T? fun <T : RibCustomisation> getRecursivelyOrDefault(default: T) : T = get(default::class) ?: parent?.get(default::class) ?: default } <file_sep>package com.badoo.ribs.minimal.reactive import com.badoo.ribs.minimal.reactive.Cancellable.Companion.cancellableOf class Relay<T> : Source<T>, Emitter<T> { private val listeners: MutableList<(T) -> Unit> = mutableListOf() fun accept(value: T) { emit(value) } override fun emit(value: T) { listeners.forEach { it.invoke(value) } } override fun observe(callback: (T) -> Unit): Cancellable { listeners += callback return cancellableOf { listeners -= callback } } } <file_sep>package com.badoo.ribs.core.customisation import com.badoo.ribs.core.Rib import kotlin.reflect.KClass open class RibCustomisationDirectoryImpl( override val parent: RibCustomisationDirectory? = null ) : MutableRibCustomisationDirectory { private val map: MutableMap<Any, Any> = hashMapOf() override fun <T : RibCustomisation> put(key: KClass<T>, value: T) { map[key] = value } fun <T : Any> put(vararg values: T) { values.forEach { map[it::class] = it } } inline operator fun <reified T : Any> T.unaryPlus() { put(this) } override fun <T : RibCustomisation> get(key: KClass<T>): T? = map[key] as? T override fun <T : RibCustomisation> getRecursively(key: KClass<T>): T? = get(key) ?: parent?.get(key) override fun <T : Rib> putSubDirectory(key: KClass<T>, value: RibCustomisationDirectory) { map[key] = value } override fun <T : Rib> getSubDirectory(key: KClass<T>): RibCustomisationDirectory?= map[key] as? RibCustomisationDirectory override fun <T : Rib> getSubDirectoryOrSelf(key: KClass<T>): RibCustomisationDirectory { val subDir = map.keys.firstOrNull { it is KClass<*> && it.java.isAssignableFrom(key.java) } return map[subDir] as? RibCustomisationDirectory ?: this } operator fun KClass<out Rib>.invoke(block: RibCustomisationDirectoryImpl.() -> Unit) { if (map.containsKey(this)) { // TODO warning for accidental override? } map[this] = RibCustomisationDirectoryImpl(this@RibCustomisationDirectoryImpl).apply(block) } } <file_sep>package com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.builder import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1Node import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1Presenter import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.routing.SimpleRoutingChild1ChildBuilders import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.routing.SimpleRoutingChild1Router class SimpleRoutingChild1Builder( private val dependency: SimpleRoutingChild1.Dependency ) : SimpleBuilder<SimpleRoutingChild1>() { override fun build(buildParams: BuildParams<Nothing?>): SimpleRoutingChild1 { val customisation = buildParams.getOrDefault(SimpleRoutingChild1.Customisation()) val presenter = SimpleRoutingChild1Presenter(title = dependency.title) val router = SimpleRoutingChild1Router( buildParams = buildParams, builders = SimpleRoutingChild1ChildBuilders(dependency) ) return SimpleRoutingChild1Node( buildParams = buildParams, viewFactory = customisation.viewFactory(null), plugins = listOf(presenter, router) ) } } <file_sep>@file:SuppressWarnings("LongParameterList") package com.badoo.ribs.sandbox.rib.compose_parent import com.badoo.ribs.builder.SimpleBuilder import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.core.plugin.Plugin class ComposeParentBuilder( private val dependency: ComposeParent.Dependency ) : SimpleBuilder<ComposeParent>() { override fun build(buildParams: BuildParams<Nothing?>): ComposeParent { val customisation = buildParams.getOrDefault(ComposeParent.Customisation()) return node(buildParams, customisation) } private fun node( buildParams: BuildParams<*>, customisation: ComposeParent.Customisation ) = ComposeParentNode( buildParams = buildParams, viewFactory = customisation.viewFactory(null), plugins = emptyList() ) } <file_sep>package com.badoo.ribs.example import android.content.Context import androidx.test.platform.app.InstrumentationRegistry import coil.DefaultRequestOptions import coil.ImageLoader import coil.decode.DataSource import coil.request.GetRequest import coil.request.LoadRequest import coil.request.RequestDisposable import coil.request.RequestResult import coil.request.SuccessResult import com.badoo.ribs.example.test.R class TestImageLoader : ImageLoader { private val instrumentationContext: Context = InstrumentationRegistry.getInstrumentation().context private val drawable = instrumentationContext.getDrawable(R.drawable.ic_sample)!! private val disposable = object : RequestDisposable { override val isDisposed = true override fun dispose() {} override suspend fun await() {} } override val defaults = DefaultRequestOptions() override fun execute(request: LoadRequest): RequestDisposable { request.target?.onStart(drawable) request.target?.onSuccess(drawable) return disposable } override suspend fun execute(request: GetRequest): RequestResult = SuccessResult(drawable, DataSource.MEMORY) override fun invalidate(key: String) {} override fun clearMemory() {} override fun shutdown() {} } <file_sep>package com.badoo.ribs.samples.customisations.app import com.badoo.ribs.core.customisation.RibCustomisationDirectoryImpl import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1.SimpleRoutingChild1ViewImpl import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.SimpleRoutingChild1Child1 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child1.SimpleRoutingChild1Child1ViewImpl import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.SimpleRoutingChild1Child2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child1_child2.SimpleRoutingChild1Child2ViewImpl import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2 import com.badoo.ribs.samples.simplerouting.rib.simple_routing_child2.SimpleRoutingChild2ViewImpl import com.badoo.ribs.samples.simplerouting.rib.simple_routing_parent.SimpleRoutingParent import com.badoo.ribs.samples.simplerouting.rib.simple_routing_parent.SimpleRoutingParentViewImpl object AppCustomisations : RibCustomisationDirectoryImpl() { init { +SimpleRoutingParent.Customisation( viewFactory = SimpleRoutingParentViewImpl.Factory(R.layout.rib_customisation_parent) ) SimpleRoutingParent::class { +SimpleRoutingChild1.Customisation( viewFactory = SimpleRoutingChild1ViewImpl.Factory(R.layout.rib_customisation_child1) ) +SimpleRoutingChild2.Customisation( viewFactory = SimpleRoutingChild2ViewImpl.Factory(R.layout.rib_customisation_child2) ) +SimpleRoutingChild1Child1.Customisation( viewFactory = SimpleRoutingChild1Child1ViewImpl.Factory(R.layout.rib_customisation_child1_child1) ) +SimpleRoutingChild1Child2.Customisation( viewFactory = SimpleRoutingChild1Child2ViewImpl.Factory(R.layout.rib_customisation_child1_child2) ) } } } <file_sep>package com.badoo.ribs.tutorials.tutorial5.rib.option_selector import androidx.lifecycle.Lifecycle import com.badoo.mvicore.android.lifecycle.createDestroy import com.badoo.mvicore.binder.using import com.badoo.ribs.android.text.Text import com.badoo.ribs.clienthelper.interactor.Interactor import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelector.Output import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView.Event import com.badoo.ribs.tutorials.tutorial5.rib.option_selector.OptionSelectorView.ViewModel import io.reactivex.functions.Consumer class OptionSelectorInteractor( buildParams: BuildParams<Nothing?>, private val output: Consumer<Output>, options: List<Text> ) : Interactor<OptionSelector, OptionSelectorView>( buildParams = buildParams ) { private val initialViewModel = ViewModel( options ) private val viewEventToOutput: (Event) -> Output = { TODO() } override fun onViewCreated(view: OptionSelectorView, viewLifecycle: Lifecycle) { view.accept(initialViewModel) viewLifecycle.createDestroy { bind(view to output using viewEventToOutput) } } } <file_sep>package com.badoo.ribs.minimal.reactive fun <T> just(producer: () -> T): Source<T> = object : Source<T> { override fun observe(callback: (T) -> Unit): Cancellable { callback(producer()) return Cancellable.Empty } } fun <A : Any, B : Any, C> combineLatest(source1: Source<A>, source2: Source<B>, combination: (A, B) -> C): Source<C> = object : Source<C> { /** * The internal state (first / second values) should be recreated for each new call to observer * Otherwise new subscriptions will not start from empty state but will share values, which is not desirable */ override fun observe(callback: (C) -> Unit): Cancellable { var firstValue: A? = null var secondValue: B? = null fun emitCombined() { if (firstValue != null && secondValue != null) { callback(combination(firstValue!!, secondValue!!)) } } val cancellable1 = source1.observe { firstValue = it emitCombined() } val cancellable2 = source2.observe { secondValue = it emitCombined() } return Cancellable.cancellableOf { cancellable1.cancel() cancellable2.cancel() } } } fun <T, R> Source<T>.map(transform: (T) -> R): Source<R> = object : Source<R> { override fun observe(callback: (R) -> Unit): Cancellable = [email protected] { callback(transform(it)) } } fun <T> Source<T>.filter(predicate: (T) -> Boolean): Source<T> = object : Source<T> { override fun observe(callback: (T) -> Unit): Cancellable = [email protected] { if (predicate(it)) callback(it) } } fun <T> Source<T>.startWith(value: T): Source<T> = object : Source<T> { override fun observe(callback: (T) -> Unit): Cancellable { callback(value) return [email protected](callback) } }
80a1621b8025c32e6883092ddb302ad1db3cfef3
[ "Markdown", "Kotlin", "Gradle" ]
124
Kotlin
antonshilov/RIBs
d23c9fc9f07c9dd21abee24dae66f2546fccc20d
e42f110f1d13c18e63c0f1924fde315522012dd0